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

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.")

说明

  1. 去掉了无意义的height_input >=120单独一行代码
  2. 将年龄输入、价格判断的逻辑全部缩进,嵌套在身高验证的if分支里,确保只有身高符合要求时才会执行这部分代码,避免未定义变量的问题
  3. 变量名从payment改为age,更贴合实际含义,提升代码可读性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 06:45:29