2011-04-23 75 views
6

不幸的是,raw_input没有按照我的需要去做。我想要做的是得到totPrimes =无论我在提示中输入什么。如果我将while count < totPrimes替换为while count < 50此脚本有效。如果我在提示符中键入50,这个脚本不起作用,我害怕raw_input不是我想要使用的函数吗?这里是我的代码片段:Python:raw_input读取数字时出现问题

testNum = 3 
div = 2 
count = 1 
totPrimes = raw_input("Please enter the primes: ") 

while count < totPrimes : 
    while div <= testNum : 
+0

考虑将标题更改为更充分的标题。 p.e.'problem with raw_input reading a number',或类似的问题。 – joaquin 2011-04-23 07:52:27

+0

仅供参考,这是Python 2.x中的一个问题,因为您可以比较不同类型的对象。在Python 3.x中它会引发一个'TypeError:unorderable types'。 – katrielalex 2011-04-23 08:57:03

回答

11

totPrimes = int(totPrimes) 
while count < totPrimes: 
    # code 

raw_input给你,你必须转换为整数或浮点数作出任何数值比较之前的字符串。

+0

尽管在循环之前进行转换并将其保存为局部变量会更好。否则,您会在进行比较时每次在循环中不必要地调用“int”。 – ncoghlan 2011-04-23 12:24:35

+0

@ncoghlan你是对的。我用这种方式写下来,以便将问题集中在一行中。我将它更新为您引用的更高效的版本。 – joaquin 2011-04-23 20:31:25

0

你需要转换totPrimes成一个int这样的:

integer = int(totPrimes) 
0

你只需要你的原始输入转换成一个整数。对于您的代码,只需将您的代码更改为:

testNum = 3 
div = 2 
count = 1 
totPrimes = raw_input("Please enter the primes: ") 
totPrimes=int(totPrimes) 
while count < totPrimes : 
    while div <= testNum : 
0

然后使用输入。

原始输入返回字符串。

输入返回int。

0

的的raw_input函数总是返回raw_input docs一个“字符串”类型,所以我们必须在这种情况下totPrimes“串”类型转换为“廉政”或“浮动”型是这样的:

totPrimes = raw_input("Please enter the primes: ") 
totPrimes = float(totPrimes) 

你可以这样将它们组合起来:

totPrimes = float(raw_input("Please enter the primes: ")) 

为了在python count < totPrimes比较的东西,比较需要有意义(数字到数字,字符串为字符串)或程序将崩溃,while count < totPrimes :得到控制而e循环将不会运行。

您可以使用try/except来保护您的程序。 managing exceptions

对于参加“为所有人编程”课程的人,您可以花几小时时间并按此方式评分。您应该尝试弄清楚if/else语句。

0

您必须将每个数字更改为“hrs”或“rate”。

例如:40*10.50+(h-40)*10.50*1.5是错的,40*r+(h-40)*r*1.5是正确的。

相关问题