Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 打印用户输入字符串_Python_Python 2.7 - Fatal编程技术网

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

如果这让人困惑,我很抱歉,我对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 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
。当然可以,但请不要鼓励人们使用Python2
input
。最好使用
raw\u input
并对用户输入字符串进行显式
float
int
转换。