Python:原始输入读取数字时出现问题

Python:原始输入读取数字时出现问题,python,raw-input,Python,Raw Input,不幸的是,原始输入没有完成我需要它完成的任务。我要做的是获取totPrimes=我在提示符处键入的任何内容。如果我将计数

不幸的是,原始输入没有完成我需要它完成的任务。我要做的是获取totPrimes=我在提示符处键入的任何内容。如果我将计数时的
替换为计数<50时的
,则此脚本可以工作。如果我在提示符中输入50,这个脚本就不起作用了,恐怕原始输入不是我想要使用的函数?以下是我的代码片段:

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

while count < totPrimes :
    while div <= testNum :
testNum=3
div=2
计数=1
totPrimes=原始输入(“请输入素数:”)
当count
totPrimes=int(totPrimes)
当count

raw\u input
为您提供一个字符串,在进行任何数字比较之前,您必须将其转换为整数或浮点。

您需要将totPrimes转换为int,如下所示:

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

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

testNum = 3
div = 2
count = 1
totPrimes = raw_input("Please enter the primes: ")
totPrimes=int(totPrimes)
while count < totPrimes :
    while div <= testNum :
testNum=3
div=2
计数=1
totPrimes=原始输入(“请输入素数:”)
totPrimes=int(totPrimes)
当count
原始输入返回字符串


input返回int。

原始输入函数始终返回“string”类型,因此在这种情况下,我们必须将
totPrimes
的“string”类型转换为“int”或“float”类型,如下所示:

integer = int(totPrimes)
totPrimes = raw_input("Please enter the primes: ")
totPrimes = float(totPrimes)
totPrimes = float(raw_input("Please enter the primes: "))
您可以这样组合它们:

integer = int(totPrimes)
totPrimes = raw_input("Please enter the primes: ")
totPrimes = float(totPrimes)
totPrimes = float(raw_input("Please enter the primes: "))
为了在python中比较事物,比较需要有意义(数字到数字,字符串到字符串),否则程序将崩溃,而计数
while循环将不会运行

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


对于修读“为每个人编程”课程的人,你可以用小时数,并以这种方式进行评分。您应该尝试找出if/else语句。

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


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

考虑将标题更改为更合适的名称。p、 e.“原始输入读取数字的问题”或类似内容。仅供参考,这在Python2.x中是一个问题,因为您可以比较不同类型的对象。在Python3.x中,它将引发一个
TypeError:unorderable types
。不过最好在循环之前进行转换并将其保存为局部变量。否则,在进行比较时,每次循环都会不必要地调用
int
。@ncoghlan您是对的。我这样写是为了把问题浓缩成一行。我将其更新为您提到的更高效的版本。不,Python 2中的
input
对表达式求值。如果输入字符串表达式,它将返回字符串。如果您输入一个数值表达式,它将返回一个数字(float或int,具体取决于您的表达方式)。