Python新手过山车代码报错:输入身高<120cm触发NameError
过山车身高验证代码报错问题解决
我是Python新手,运行一段过山车身高验证代码时,输入身高≥120cm代码可正常运行,但输入身高≤120cm时出现报错。
原代码
print("Welcome to the rollercoaster!") height_input = int(input("What is your height in cm? ")) height_input >= 120 if height_input >= 120: print("Congrats! You're allowed to go on ride.") else: print("Sorry, you're not allowed on ride.") if height_input >= 120: payment = (int(input("How old are you? "))) if payment <= 18: print("You must pay $7") else: print("You must pay $12")
报错情况
当输入身高小于120cm时会报错,输入120cm及以上则运行正常。报错信息如下:
Traceback (most recent call last): File "main.py", line 14, in <module> if payment <= 18: NameError: name 'payment' is not defined
问题原因
payment变量仅在height_input >=120的条件成立时才会被定义。如果身高不足120cm,这部分代码不会执行,payment变量根本不存在,后续直接判断payment <=18就会触发未定义变量的错误。
修复后的代码
print("Welcome to the rollercoaster!") height_input = int(input("What is your height in cm? ")) if height_input >= 120: print("Congrats! You're allowed to go on ride.") # 将年龄输入和价格判断缩进,放到身高验证的if块内 age = int(input("How old are you? ")) if age <= 18: print("You must pay $7") else: print("You must pay $12") else: print("Sorry, you're not allowed on ride.")
说明
- 去掉了无意义的
height_input >=120单独一行代码 - 将年龄输入、价格判断的逻辑全部缩进,嵌套在身高验证的
if分支里,确保只有身高符合要求时才会执行这部分代码,避免未定义变量的问题 - 变量名从
payment改为age,更贴合实际含义,提升代码可读性
内容的提问来源于stack exchange,提问作者PEPSI
相关产品推荐
相关产品推荐

