首页 > 解决方案 > NameError:名称'x'未定义(Python 3.7)

问题描述

我是 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

标签: pythonpython-3.xnameerror

解决方案


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')

推荐阅读