Python:无法连接 'str' 和 'int' 对象错误

标签 python syntax-error

我正在尝试创建一个小程序,让用户可以从商店购买东西或用钱购买工作。

代码:

#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

谁能解释一下发生了什么?

最佳答案

使用 str 函数将“货币”转换为字符串

def shop():
      print "Hello " + name + ", what would you like? You have $" + str(currency)

关于Python:无法连接 'str' 和 'int' 对象错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46869701/

相关文章:

php - PHP解析/语法错误;以及如何解决它们

c#-4.0 - C#上传数据错误->为空间返回 “�”

python - BeautifulSoup:我可以在不添加额外标签的情况下进行美化吗?

python - 如何使用 Python 列出 Azure 云存储中特定子目录内的所有 blob?

python - 为python配置Vs code 2.0.0 Build Task

Python(jupyter) 用于素数

objective-c - 指向 struct C/ObjC 中指针的指针

sql - SQL Server中的转换错误-为什么?

python - 我如何减少这里的 try/catch 语句的数量?

python - 循环而不在 tensorflow 中展开