NameError: name 'x' is not defined(Python 3.7)

NameError: name 'x' is not defined(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

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

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