-6

我正在制作一个简单的基于文本的游戏,但出现错误。我必须将代码中的 int 转换为 str。我的代码如下所示:

tax1 = input("You May Now Tax Your City.  Will You? ")
        if tax1 == "Yes" or tax1 == "yes":
            tax2 = input("How Much Will You Tax Per Person In Dollars? ")
            if tax2 > 3:
                print("You Taxed To High!  People Are Moving Out")
                time.sleep(1.5)
                population -= (random.randint(2, 4))
                print("The Population Is Now " + str(population))
                time.sleep(1.5)
                money += (population * 2)
                print("From The Rent You Now Have $" + str(money) + " In Total.")
            if tax2 < 3:
                print("You Have Placed A Tax That Citizens Are Fine With.")
                time.sleep(1.5)
                money += (tax2+(population * 2))
                print("From The Rent And Tax You Now Have $" + str(money) + " In Total")

我将在我的代码中添加什么来做到这一点?

4

3 回答 3

1

你可以说:

tax2 = int( input("How Much Will You Tax Per Person In Dollars? ") )

如果您确定输入不包含小数。如果您不确定,并且想要保留十进制值,您可以使用:

tax2 = float( input("How Much Will You Tax Per Person In Dollars? ") )

或者使用整数,但要安全地使用

taxf = round( float( input("How Much Will You Tax Per Person In Dollars? ") ) )
tax2 = int( taxf )
于 2013-05-31T12:43:31.380 回答
0

采用

if int(tax2) > 3:

因为input返回一个字符串,所以你应该从中解析一个 int 。

另请注意,如果玩家输入的不是数字,您的游戏将会崩溃。

并且以防万一您使用的是 Python 2(而不是 Python 3),您应该使用input_raw而不是input因为后者也会将给定的字符串评估为 Python 代码,而您不想要 this

于 2013-05-31T12:42:00.613 回答
0

input()返回一个字符串(在 Python 3 中),它显然不能用于数学表达式(正如您所尝试的那样)。

使用内置int()函数。它将一个对象转换为一个整数(如果可能,否则它会给出 a ValueError)。

tax2 = int(input("How Much Will You Tax Per Person In Dollars? "))
# tax2 is now 3 (for example) instead of '3'.

但是,如果您使用的是 Python 2.x,int()则在使用 时不需要input(),因为(如文档中所示)它等同于eval(raw_input(prompt)). 但是,如果你想输入一个字符串,你会想像"this".

于 2013-05-31T12:51:31.703 回答