7

不幸的是 raw_input 没有做我需要做的事情。我想做的是让 totPrimes = 我在提示符下输入的任何内容。如果我while count < totPrimeswhile count < 50这个脚本替换有效。如果我在提示中输入 50,这个脚本不起作用,恐怕 raw_input 不是我想要使用的函数?这是我的代码片段:

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

while count < totPrimes :
    while div <= testNum :
4

6 回答 6

12

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

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

于 2011-04-23T07:39:05.927 回答
0

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

integer = int(totPrimes)
于 2011-04-23T07:40:48.893 回答
0

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

testNum = 3
div = 2
count = 1
totPrimes = raw_input("Please enter the primes: ")
totPrimes=int(totPrimes)
while count < totPrimes :
    while div <= testNum :
于 2014-04-04T04:19:58.603 回答
0

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

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

你可以像这样组合它们:

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

为了在 python 中比较事物count < totPrimes,比较需要有意义(数字到数字,字符串到字符串),否则程序会崩溃并且while count < totPrimes :while 循环不会运行。

您可以使用 try/except 来保护您的程序。管理异常

对于参加“面向所有人的编程”课程的人,您可以花费数小时并以这种方式进行评分。if/else 语句你应该试着弄清楚。

于 2016-11-29T23:49:48.960 回答
0

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

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

于 2017-06-29T08:52:58.737 回答
-1

然后使用输入。

原始输入返回字符串。

输入返回 int。

于 2016-08-21T18:38:26.350 回答