Python ATM代码报错:'break' outside of loop 问题求助
问题分析与修正
错误原因
- 第一个循环条件逻辑错误:
while attempts > 3初始时attempts=3,条件永远不成立,导致PIN验证流程完全跳过。应改为while attempts > 0,保证有3次输入PIN的机会。 - 第二个循环缩进错误:
choose = int(input(...))及后续的功能判断代码没有缩进在while True:循环内部,导致elif choose ==4中的break语句不在任何循环结构里,触发'break' outside of loop语法错误。
修正后的完整代码
import random balance = random.randint(100, 1000) attempts = 3 print('**Welcome To My ATM**') # 修正循环条件:从attempts>3改为attempts>0 while attempts > 0: pin = input('Please enter your 4-digit PIN: ') if pin == '0000': print('CORRECT PIN') break else: attempts -= 1 print(f'INCORRECT PIN. You have {attempts} attempt/s left, try again.') if attempts == 0: print('You have exceeded your attempts limit.') print('Please take your card') else: while True: print('1: Check Balance') print('2: Deposit') print('3: Withdraw') print('4: Exit') # 以下代码全部缩进,纳入while True循环内部 choose = int(input('Choose which service you want from 1 to 4: ')) if choose == 1: print('Your current balance is', balance) elif choose == 2: amount1 = int(input('Please enter the amount you want to deposit: ')) balance += amount1 print('Your new balance will be displayed in a moment...') print(balance) elif choose == 3: amount2 = int(input('Please enter the amount you want to withdraw: ')) if balance >= amount2: balance -= amount2 print('Cash will be out any moment...') print('Your new balance is ', balance) else: print('Sorry, insufficient funds. Current balance is ', balance) elif choose == 4: print('Thank you for using this ATM.') break else: print('Invalid choice, please try again')
额外优化说明
- 修正了原代码中
Pleas的拼写错误,改为Please - 修正了
Cash is will be out的语法错误,改为Cash will be out - 使用f-string优化了错误提示的字符串格式,让输出更简洁
内容的提问来源于stack exchange,提问作者Niac Nagrom
相关产品推荐
相关产品推荐

