python - 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
解决方案
是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')
推荐阅读
- python - 创建更灵活的功能
- android - Android 8.0 设备上的 JobScheduler API 崩溃
- wampserver - 随机页面在 wamp 服务器中停止工作
- javascript - React Native Fade In Animation 不流畅
- php - 为什么我的登录代码没有从我的数据库中读取?
- css - position: absolute 导致页面溢出
- java - java在类中调用静态方法使该类成为实例化
- php - 检查月份是否大于今天的月份
- spring - 使用 Spring Boot 创建 OAuth 2.0 登录提供程序
- javascript - Ajax 请求不返回 HttpResponse