1

我正在制作一个基于文本的游戏,并且一直做得很好,但现在我遇到了一个错误int。到目前为止,我的代码如下所示:

money = 500
print("You Have $500 To Spend On Your City.  The Population Is 0 People")
input_var3 = input("What Will You Spend Your Money On?  A House Or A Restraunt. ")
if input_var3 == "House":
    money - 100
    print("You Have Spent Your Money On A House")
    print("You Now Have $" + money)
if input_var3 == "Restraunt":
    money - 150
    print("You Have Spent Your Money On A Restraunt")
    print("You Now Have $" + money)

你的钱等于 500 美元,但如果你把它花在房子或休闲场所上,你的钱会更少,而且外壳会打印出你还剩下多少。但是我总是得到这个错误:

Traceback (most recent call last):
  File "C:\Users\Jason\Desktop\City Text.py", line 11, in <module>
    print("You Now Have $" + money)
TypeError: Can't convert 'int' object to str implicitly

我已经意识到我必须做一个刺痛而不是 Int 但我不知道该怎么做。任何人都可以帮忙吗?

4

4 回答 4

3

money变量是一个整数。将它们连接在一起时,不能将整数与字符串混合。使用str()将整数转换为字符串的函数:

print("You Now Have $" + str(money))

另外,我认为您打算从货币价值中扣除 100。money - 100只是返回500 - 100,即400。如果要money等于400,请执行以下操作:

money -= 100

这相当于:

money = money - 100
于 2013-05-26T11:07:59.727 回答
1

您需要将值存储在变量中。

if input_var3 == "House":
    money -= 100   # Notice the usage of -=
    print("You Have Spent Your Money On A House")
    print("You Now Have $" + str(money))   # Type casting
if input_var3 == "Restraunt":
    money = money - 150  # Same as -=
    print("You Have Spent Your Money On A Restraunt")
    print("You Now Have $" + str(money))   # Type casting
于 2013-05-26T11:06:18.853 回答
0

采用:

print("You Now Have $" + str(money))

您不能将字符串与数字连接,因此将您的数字转换为字符串。

于 2013-05-26T11:06:28.110 回答
0

您可以使用该str()功能。例如:

print("You Now Have $" + str(money))
于 2013-05-26T11:06:34.967 回答