【问题标题】:New to python, when i run this code with inputs >= it runs smoothly when i run it with input<= i get an errorpython 的新手,当我使用输入运行此代码时 >= 它运行平稳 当我使用输入运行它时 <= 我收到错误
【发布时间】:2022-12-24 13:09:52
【问题描述】:
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,当我将高度设置为 120+ 时会出现错误代码运行顺利)提前抱歉我是编码新手

我收到错误

Traceback (most recent call last):
  File "main.py", line 14, in <module>
    if payment <= 18:
NameError: name 'payment' is not defined

【问题讨论】:

  • payment 可以未定义,因为它在 if 语句中。
  • 这类错误最好先为你的程序画一个图来解决。问问自己:如果height &lt; 120,你想让程序继续吗?如果不是,您应该如何修改代码以反映这一点?
  • height_input &gt;= 120..?在第三行
  • @YashMehta 这只是多余的,但不会造成伤害。

标签: python


【解决方案1】:

这实际上不是因为&lt;=,而是因为,当您在height_input 中输入一个大于 120 的值时,下面的代码永远不会执行。

if height_input <= 120: # >= to <=
 payment = (int(input("How old are you? ")))

这意味着该程序从不要求您输入支付输入的值。因为它从来没有定义你 NameError

【讨论】:

    【解决方案2】:

    您在“if”中定义了变量“payment”

    所以,当您输入的高度小于 120 时:

    if height_input >= 120:
     payment = (int(input("How old are you? ")))
    

    它给出了错误的。所以,线 -

     payment = (int(input("How old are you? ")))
    

    不运行。 之后,当您询问有关变量的代码时,它不明白您在说什么。因为它甚至没有被宣布!

    【讨论】:

      猜你喜欢
      • 2018-12-09
      • 1970-01-01
      • 2023-01-30
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 2020-10-11
      相关资源
      最近更新 更多