Python:raw_input读取数字的问题

不幸的是raw_input没有做我需要做的事情。 我想要做的是得到totPrimes =无论我在提示中键入。 如果我更换while count < totPrimes while count < 50此脚本的作品。 如果我在提示符中键入50,这个脚本是行不通的,恐怕raw_input不是我正在使用的函数吗? 这是我的代码片段:

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

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

raw_input给你一个string,你必须在进行任何数字比较之前转换为一个整数或浮点数。

您需要将totPrimes转换为像这样的int:

 integer = int(totPrimes) 

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

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

然后使用input。

原始input返回string。

input返回int。

raw_input函数总是返回一个'string'types的raw_input docs ,所以在这种情况下,我们必须将totPrimes 'string'types转换为'int'或'float'types,如下所示:

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

你可以像这样组合他们:

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

为了比较python count < totPrimes东西,比较需要有意义(数字到数字,string到string),否则程序将崩溃, while count < totPrimes : while循环将不会运行。

您可以使用try / except来保护您的程序。 pipe理例外

对于参加“为每个人编程”课程的人,您可以花几个小时,按这种方式进行评分。 你应该试图弄清楚if / else语句。

您必须将每个号码更改为“hrs”或“rate”。

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