打印用户输入字符串

时间:2018-05-10 00:31:46

标签: 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 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 >>>

1 个答案:

答案 0 :(得分:0)

python 2.7和3之间的输入和打印语法略有不同。 在2.7 input中评估数据,而raw_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 

Python 3.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
相关问题