我试图创建一个小程序,让用户从商店购买东西或者在工作中购买金钱。
代码:
#Info before user starts
print "Enter job, shop, or exit"
print ""
#--------------------------------------------------------------------------------------------
#Variabls
name = raw_input("What is your name?")
ask = raw_input("Where do you want to go:")
currency = 20
#--------------------------------------------------------------------------------------------
#Functions
def job():
print "hello"
def shop():
print "Hello " + name + ", what would you like? You have $" + currency
#-------------------------------------------------------------------------------------------
#Body
while (ask != "job") and (ask != "shop") and (ask != "exit"):
print "That is not an option. Please choose job, shop, or exit"
ask = raw_input("Where do you want to go:")
if(ask == "job"):
job()
elif (ask == "shop"):
shop()
程序询问用户的姓名并询问他想去哪里。对于功能性商店,程序应打印:"您好[用户名],您想要什么?你有20美元"。当我运行它时,它会显示此错误:
Traceback (most recent call last):
File "python", line 30, in <module>
File "python", line 18, in shop
TypeError: cannot concatenate 'str' and 'int' objects
有人能解释发生了什么吗?
答案 0 :(得分:2)
使用str函数转换&#34; currency&#34;到一个字符串
def shop():
print "Hello " + name + ", what would you like? You have $" + str(currency)
答案 1 :(得分:1)
Python对类型采取严格的观点,并且不像动态语言那样隐式地在类型之间进行转换。如果您希望数字成为字符串,则必须使用str
函数显式转换为字符串。这是Zen of Python:
明确比隐含更好。
通过要求程序员在类型之间进行显式转换,可以消除添加数字或字符串的一些意外情况。例如,如果2 + 3 + "foo"
应该等于"23foo"
或"5foo"
有时您不必显式转换为字符串,例如在print语句中,如果语句中的唯一内容,数字将自动转换为字符串。但是,如果您在将数字传递给print语句之前尝试将其添加到字符串中,则必须显式转换为字符串。
如果你的情况,你想说
print "Hello " + name + ", what would you like? You have $" + str(currency)
答案 2 :(得分:0)
'+'运算符对某些变量类型(或对象类,更准确)有自己的行为。这称为运算符重载。在添加两个整数的情况下,结果显而易见:
a = 1
b = 5
print(a+b)
Out[0]: 6
另一方面,当您尝试添加两个字符串时,Python将其理解为连接。所以:
a = 'hi '
b = 'my friend'
print(a+b)
Out[0]: 'hi my friend'
在您的情况下,您正在尝试添加字符串和整数。 Python不知道如何添加这些,或者更确切地说,添加对象'str'和'int'时未定义'+'运算符。为了修复代码,您需要将变量currency
强制转换为字符串:
def shop():
print "Hello " + name + ", what would you like? You have $" + str(currency)