Python 为什么在检查";中的变量时总是出现此错误;如果;条件
当我运行此代码时:Python 为什么在检查";中的变量时总是出现此错误;如果;条件,python,Python,当我运行此代码时: #!/usr/bin/python from time import strftime #welcome state = input("Morning? [y/n] ") if state == y: print("Good morning sir! Welcome to our system!") pass else: print("Good afternoon sir! Welcome to our system!") pass u
#!/usr/bin/python
from time import strftime
#welcome
state = input("Morning? [y/n] ")
if state == y:
print("Good morning sir! Welcome to our system!")
pass
else:
print("Good afternoon sir! Welcome to our system!")
pass
user = input("What is your name? ")
print("Hello World.")
print("{} is using this computer right now".format(user))
print(strftime("%Y-%m-%d %H:%M:%S"))
我得到这个错误:
Morning? [y/n] y
Traceback (most recent call last):
File "C:/Users/toshiba/py/hello/hello_world.py", line 7, in <module>
if state == y:
NameError: name 'y' is not defined
早上好?[y/n]y
回溯(最近一次呼叫最后一次):
文件“C:/Users/toshiba/py/hello/hello\u world.py”,第7行,在
如果state==y:
名称错误:未定义名称“y”
此代码旨在根据用户的输入显示自定义打印消息,如第一种输入方法所示。我用python 3编写代码,但我无法找出问题所在。您的if语句应该是:
if state == 'y':
状态的类型是字符串
此外,如果用户输入Y
或yes
,if语句当前将失败。现在这不是非常重要,但你可以这样处理:
if state in ('y', 'Y', 'yes'):
这对将来来说是件好事。阅读错误消息并检查代码。。。7号线出问题了!