【问题标题】:How will I convert this int into a string in an if statement? [closed]如何在 if 语句中将此 int 转换为字符串? [关闭]
【发布时间】:2013-05-27 06:51:35
【问题描述】:

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

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

【问题讨论】:

  • 请发布错误和堆栈跟踪。只是告诉我们您遇到了错误并没有帮助。
  • 作为参考,您可能希望使用if tax1.lower() == "yes" 而不是if tax1 == "Yes" or tax1 == "yes" - 它更易于阅读并为用户提供更多选择(大写和小写的任意组合)。
  • 你必须照顾好一个城市,这就是税收的原因!
  • @thegrinner 没有谈论为什么要征税——评论是关于澄清你的代码。是str(money) 还是str(population) 的问题?你得到的实际错误是什么?您在调用str() 函数时查看过populationmoney 的值吗?

标签: python string int


【解决方案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 )

【讨论】:

    【解决方案2】:

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

    使用内置的int() 函数。它将一个对象转换为一个整数(如果可能,否则它会给出一个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,则如果您使用的是 input(),则不需要 int(),因为(如文档中所示)它等同于 eval(raw_input(prompt))。但是,如果你想输入一个字符串,你会想像"this"一样输入它。

    【讨论】:

      【解决方案3】:

      使用

      if int(tax2) > 3:
      

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

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

      如果你使用的是 Python 2(而不是 Python 3),你应该使用 input_raw 而不是 input,因为后者也会将给定的字符串评估为 Python 代码,而你不需要想要这个

      【讨论】:

      • 这是raw_input(),而不是input_raw。您可能还想包括使用它的原因(即input() 将评估用户提供的 Python)。
      • @thegrinner 哦,谢谢。
      猜你喜欢
      • 2019-07-04
      • 2016-08-11
      • 2019-07-03
      • 1970-01-01
      • 2017-06-30
      • 2015-08-02
      • 2022-08-19
      • 2019-07-16
      • 2013-11-21
      相关资源
      最近更新 更多