2013-05-31 29 views
-6

我正在制作一个简单的基于文本的游戏,并得到一个错误。我必须将我的代码中的int转换为str。我的代码如下所示:如何将这个int转换为if语句中的字符串?

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") 

我会在代码中添加哪些内容?

+3

请发布错误和堆栈跟踪。只是告诉我们你得到了一个错误并没有帮助。 –

+0

作为参考,您可能想使用'if tax1.lower()==“yes”'而不是'如果tax1 ==“Yes”或者tax1 ==“yes”' - 读起来会更简单一些用户更多选项(大写和小写的任意组合)。 – thegrinner

+0

你必须照顾一个城市好吗,这就是为什么有税! –

回答

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) 
0

使用

if int(tax2) > 3: 

因为input回报你一个字符串,所以你应该解析来自它的int。

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

而就在你使用Python 2的情况下(而不是到Python 3)你应该input_raw代替input因为后者去也将评估给出的字符串作为Python代码,你不想要这个

+2

它是['raw_input()'](http://docs.python.org/2/library/functions.html#raw_input),而不是'input_raw'。您可能还想包含使用它的原因(即'input()'将评估用户提供的Python)。 – thegrinner

+0

@thegrinner哦,谢谢。 – kirelagin

0

input()返回一个字符串(在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(),因为(如文档所示),它相当于eval(raw_input(prompt))需要int()。但是,如果你想输入一个字符串,你应该想输入它像"this"

相关问题