Python 打印用户输入字符串
如果这让人困惑,我很抱歉,我对Python和这个网站还不熟悉,需要一些帮助。我希望我清楚地知道我想得到什么帮助。当我尝试打印两个用户输入时,输入食物名称后会出现错误。我做错了什么Python 打印用户输入字符串,python,python-2.7,Python,Python 2.7,如果这让人困惑,我很抱歉,我对Python和这个网站还不熟悉,需要一些帮助。我希望我清楚地知道我想得到什么帮助。当我尝试打印两个用户输入时,输入食物名称后会出现错误。我做错了什么 foodname=input('please enter food name.') # I ask the user for the name of their food foodcost=input('please enter food cost.') # I ask for the cost of the same
foodname=input('please enter food name.') # I ask the user for the name of their food
foodcost=input('please enter food cost.') # I ask for the cost of the same food
print foodname, foodcost #I print both of the given inputs
以下是错误消息:
Traceback (most recent call last):
File "C:/Python27/test.py", line 1, in <module> foodname=input('please enter food name.')
File "<string>", line 1, in <module> NameError: name 'cheese' is not defined >>>
回溯(最近一次呼叫最后一次):
文件“C:/Python27/test.py”,第1行,foodname=input('请输入食品名称')
文件“”,第1行,在名称中错误:未定义名称“cheese”>>
python 2.7和3的输入和打印语法略有不同。
在2.7中,input
计算数据,而raw\u input
将数据作为字符串读入。
在3.x中,input
将以字符串形式读取数据。
print
在2.7中不需要括号,但在3.x中需要括号
Python 2.7
foodname=raw_input('please enter food name.') # raw_input returns a string
foodcost=int(raw_input('please enter food cost.')) # read as string cast to int
print foodname, foodcost
Python3.x
foodname=input('please enter food name.') # Input returns a string
foodcost=int(input('please enter food cost.'))
print(foodname, foodcost) # add brackets to print
错误是什么?您的错误与上面发布的3行代码无关。我们需要查看文件的其余部分。这个错误确实解释了这个问题-您使用的是一个变量/名称
cheese
,但它尚未定义可能是您运行的文件错误?在Python 3上,只要将print
statement更改为print()
函数调用,您的代码就可以了。但在Python2上可能会出现这种错误。解决方案:确保您正在运行Python3解释器。如果必须使用Python2,请将那些input
调用更改为raw\u input
。当然可以,但请不要鼓励人们使用Python2input
。最好使用raw\u input
并对用户输入字符串进行显式float
或int
转换。