我试图创建一个小程序,让用户从商店买东西,或者花钱买工作。
代码:
#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有人能解释一下发生了什么吗?
发布于 2017-10-22 01:38:26
使用str函数将“货币”转换为字符串
def shop():
print "Hello " + name + ", what would you like? You have $" + str(currency)发布于 2017-10-22 01:54:43
Python对类型有严格的看法,不像动态语言那样隐式地在类型之间进行转换。如果希望数字成为字符串,则必须使用str函数显式转换为string。这是Python的禅宗的一部分
外显好于内隐。
通过要求程序员在类型之间显式转换,可以消除添加数字或字符串的一些意外。例如,如果2 + 3 + "foo"应该等于"23foo"或"5foo",则不太明显。
有时,您不必显式转换为字符串,例如,在print语句中,如果数字是语句中的唯一内容,则数字将自动转换为字符串。但是,如果试图在将数字传递给print语句之前将数字添加到字符串中,则必须显式转换为字符串。
如果你的案子,你想说
print "Hello " + name + ", what would you like? You have $" + str(currency)发布于 2017-10-22 01:44:20
“+”运算符对于某些变量类型(更准确地说,是对象类)有它自己的行为。这被称为操作符重载。在添加两个整数的情况下,结果是显而易见的:
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转换为string:
def shop():
print "Hello " + name + ", what would you like? You have $" + str(currency)https://stackoverflow.com/questions/46869701
复制相似问题