如何在if语句中将这个int转换成字符串?

2024-04-19 19:30:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个简单的基于文本的游戏,但遇到了一个错误。我必须将代码中的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")

我将向代码中添加什么来执行此操作?你知道吗


Tags: the代码inyouiftimesleepnow
3条回答

input()返回一个字符串(在python3中),这显然不能用于数学表达式(正如您所尝试的)。你知道吗

使用内置的^{}函数。它将对象转换为整数(如果可能,否则它将给出一个ValueError)。你知道吗

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

但是,如果您使用的是python2.x,那么如果您使用的是^{},则不需要int(),因为(如文档中所示)它相当于eval(raw_input(prompt))。但是,如果您想输入一个字符串,您应该像"this"那样输入它。你知道吗

使用

if int(tax2) > 3:

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

还要注意,如果玩家输入的不是一个数字,你的游戏就会崩溃。你知道吗

如果您使用的是Python 2(而不是Python 3),您应该使用input_raw而不是input,因为后者也会将给定的字符串作为Python代码进行计算,您不希望这样。你知道吗

你可以说:

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 )

相关问题 更多 >