首页 > 解决方案 > python: NameError 名称输入

问题描述

我试图在 python 中获得一些输入,但我不知道我的问题是什么

 name = input("What's your name?")
age = int(input("How old are you?"))
year = str((100 - age) + 2018)
print("Hello "+ name + ",in " + year + "you'll be 100 y.o")

当我使用我的名字作为“shayan”之类的输入时,就出来了:

name = input("What's your name? ")
File "<string>", line 1, in <module>
NameError: name 'shayan' is not defined

我在“atom”、“sublime”、“visual studio code”中尝试了我的代码

标签: python

解决方案


这是因为您使用的是 python 2,所以input在 python 中基本上是eval(input(...))在 python 3 中,所以它将输入作为代码,而不是字符串,所以必须raw_input在 python 2 中使用:

name = raw_input("What's your name?")
age = input("How old are you?")
year = str((100 - age) + 2018)
print("Hello "+ name + ",in " + year + "you'll be 100 y.o")

推荐阅读