Python返回错误
Traceback (most recent call last):
File "<stdin>", line 29, in <module>
NameError: name 'subject_t' is not defined
代码:
name = raw_input('Enter your name')
if name == 'Truxten':
print "Hello Truxten"
user_name = 'truxten'
if name == 'Hannah':
print "Hello Hannah"
user_name = hannah
if name == 'Matthew':
print "Hello Matthew"
user_name = matthew
if name == 'Jax':
print "Hello Jax"
user_name = jax
if name == 'Ellie':
print "Hello Ellie"
user_name = ellie
def t_subject():
subject_t = raw_input('Enter the Subject')
if user_name == 'truxten':
t_subject()
print subject_t
答案 0 :(得分:3)
这是因为subject_t
超出了范围,确实未定义。
变量subject_t
仅存在于t_subject()
函数中。所以你无法显示它。
您可以使用:
def t_subject():
subject_t = raw_input('Enter the Subject')
print subject_t
但我建议,与许多函数一样,你包含一个return语句:
subject = None
def t_subject():
subject_t = raw_input('Enter the Subject')
return subject_t
if name == 'truxten':
subject = t_subject()
if subject is not None:
print subject
祝你好运!
答案 1 :(得分:1)
在subject_t
函数中为变量t_subject
指定值时,实际将其分配给函数的本地范围。您必须在全局范围内定义subject_t
,如下所示:
subject_t = None
def t_subject():
global subject_t
subject_t = raw_input('Enter the Subject')
您无条件打印subject_t
。如果您使用全局范围方法,subject_t
将包含None
(或您已全局分配给它的其他值),如果t_subject()
从未调用过。
此外,这与您提出的问题没有直接关系,但是您要指定名为hannah
,matthew
的变量,而不是字符串,例如'truxten'
。