如何基于用户输入重启Python脚本?解决return/continue语法错误
解决ATM脚本重启问题的可行方案
核心问题分析
你遇到的报错本质是return只能在函数内使用,continue必须在循环结构里生效。要实现查询余额后重启脚本的需求,最直接的方式是把整个ATM操作逻辑封装成循环或者函数,通过循环控制流程的重复执行。同时原脚本还有个隐藏问题:余额和取款金额是字符串类型,直接用</>比较会出错,需要先转成数值类型。
修改后的完整代码
import time import sys def atm_operation(): pin = "5327" # 把余额转成float类型,方便后续金额比较 balance = 67.32 pin_attempt = input("Please enter pin: ") if pin_attempt == pin: deposit_or_withdraw = input("Please press 1 to deposit cash, 2 to withdraw cash or 3 to check balance. ") if deposit_or_withdraw == "1": deposit_value = input("How much cash would you like to deposit? ") # 校验输入是否为合法数字 try: deposit_value = float(deposit_value) except ValueError: print("Invalid amount, please try again.") return True # 返回True表示需要重新执行 print("Processing.") time.sleep(0.5) print("Processing..") time.sleep(0.5) print("Processing...") time.sleep(0.5) print("Processing.") time.sleep(0.5) print("Processing..") time.sleep(0.5) print(f"Successfully deposited £{deposit_value} into account") return False # 返回False表示退出 elif deposit_or_withdraw == "2": withdraw_amount = input("How much cash would you like to withdraw? ") try: withdraw_amount = float(withdraw_amount) except ValueError: print("Invalid amount, please try again.") return True if withdraw_amount <= balance: print(f"Successfully withdrawn £{withdraw_amount} from your account. Please take your cash") time.sleep(3) print("💵💵💵") return False else: print(f"You cannot withdraw more cash than is in your account (£{balance}), please re enter your pin to continue.") return True elif deposit_or_withdraw == "3": print(f"You currently have £{balance} available in your account.") carry_on = input("If you would like to withdraw or deposit cash please press 1, if you would like to exit please press 2.") if carry_on == "1": return True # 返回True触发重新执行 elif carry_on == "2": print("Thank you, please don't forget to take your card.") return False else: print("Invalid input, please try again.") return True else: print("Invalid option, please try again.") return True else: print("Incorrect pin.") return True # 主循环:只要atm_operation返回True,就重新执行整个流程 while True: should_restart = atm_operation() if not should_restart: sys.exit()
关键修改点说明
- 函数封装+循环控制:把所有ATM操作逻辑放进
atm_operation函数,函数返回True表示需要重启流程,返回False表示退出。主循环通过判断返回值决定是否重复执行。 - 类型修复:把余额从字符串改成
float,同时对存款、取款金额做类型转换和异常捕获,避免非数字输入导致报错。 - 重启逻辑实现:查询余额后输入1时,函数返回
True,主循环会再次调用atm_operation,等价于“重启脚本”;其他退出场景返回False,终止循环。
内容的提问来源于stack exchange,提问作者Miles Price
相关产品推荐
相关产品推荐

