【问题标题】:NameError: name 'x' is not defined(Python 3.7)NameError:名称'x'未定义(Python 3.7)
【发布时间】:2018-09-10 15:53:55
【问题描述】:

我是 python 新手, 我正在 python 3.7 中学习“if and else”条件。

所以问题是,当我输入我的代码时

def age_group(user_age):

x = int(input("Enter your age :"))
return x

if x < 150 :
    print(age_group(x))
else :
    print("Either he is GOD or he is dead")

但执行后我得到一个 NameError:-

Traceback (most recent call last):
File ".\Enter Age.py", line 6, in <module>
if x < 150 :
NameError: name 'x' is not defined

【问题讨论】:

  • 请修正您的格式。
  • 你的代码不是合法的python。您需要修复缩进。

标签: python python-3.x nameerror


【解决方案1】:

是的,x 只存在于age_group 的范围内。 Python 中函数中使用的变量通常只存在于该范围内,除非您使用 global 关键字或执行其他一些技巧。无论哪种方式,您都应该将该值返回给调用者并将其分配给一个变量。工作示例(我还删除了一个未使用的参数):

def age_group():
  return int(input("Enter your age :"))

x = age_group()
if x < 150:
  print(x)
else:
  print('Either he is GOD or he is dead')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-09-30
    • 1970-01-01
    • 2019-11-06
    • 2013-01-26
    • 1970-01-01
    • 2013-08-14
    • 2020-09-04
    相关资源
    最近更新 更多