You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中函数内条件成立时如何跳转到函数外的指定代码行

Python 实现输入n后重新输入手机号的解决方案

Python 原生没有跨作用域的跳转语法,无法直接从函数内部跳转到函数外之前执行过的代码位置,我们可以通过函数返回值+外层循环的方式实现需求效果。

修改后的完整代码

def confirm():
    while True:
        response = input("Type 'y' to confirm and 'n' to enter the number again>>>")
        if response == "y":
            print("Your phone number has been verified")
            # 确认通过返回True
            return True
        elif response == "n":
            print("Let's try that again")
            # 需要重输返回False
            return False
        else:
            print("Kindly enter a valid response")


digits_map = {
    "0" : "Zero",
    "1" : "One",
    "2" : "Two",
    "3" : "Three",
    "4" : "Four",
    "5" : "Five",
    "6" : "Six",
    "7" : "Seven",
    "8" : "Eight",
    "9" : "Nine"
}

# 外层循环控制是否重新输入手机号
while True:
    phone_number = input("Enter your phone number>>>")
    words = ""
    for ch in phone_number:
        words += digits_map.get(ch, "non-numeric character!") + " "
    print(f"Confirm your phone number {phone_number} in words is {words}")
    # 拿到confirm的返回值判断是否终止循环
    if confirm():
        break

核心修改说明

  • 给confirm()函数新增返回值:输入y返回True代表验证完成,输入n返回False代表需要重新输入手机号
  • 把手机号输入、转义、确认的全流程包裹在外层无限循环中,只要confirm()返回False就重新执行输入流程,返回True则终止循环

内容的提问来源于stack exchange,提问作者RJ BergerIII

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 14:39:02