[英]Python: Problem with raw_input reading a number
unfortunately raw_input is not doing what I need it to do.不幸的是 raw_input 没有做我需要它做的事情。 What I am trying to do is get totPrimes = whatever I type in at the prompt.
我想要做的是得到 totPrimes = 我在提示符下输入的任何内容。 If i replace
while count < totPrimes
with while count < 50
this script works.如果我将
while count < totPrimes
替换为while count < 50
此脚本有效。 If I type 50 into the prompt, this script doesnt work, I'm afraid raw_input isn't the function im looking to use?如果我在提示中输入 50,这个脚本不起作用,恐怕 raw_input 不是我想要使用的函数吗? Here is a snippet of my code:
这是我的代码片段:
testNum = 3
div = 2
count = 1
totPrimes = raw_input("Please enter the primes: ")
while count < totPrimes :
while div <= testNum :
Do做
totPrimes = int(totPrimes)
while count < totPrimes:
# code
raw_input
gives you a string you must convert to an integer or float before making any numeric comparison. raw_input
为您提供一个字符串,您必须在进行任何数字比较之前将其转换为整数或浮点数。
You just need to convert your raw input in a integer.您只需要将原始输入转换为整数。 For your code just change your code as:
对于您的代码,只需将代码更改为:
testNum = 3
div = 2
count = 1
totPrimes = raw_input("Please enter the primes: ")
totPrimes=int(totPrimes)
while count < totPrimes :
while div <= testNum :
The raw_input function always returns a 'string' type raw_input docs , so we must in this case convert the totPrimes
'string' type to an 'int' or 'float' type like this: raw_input 函数总是返回一个 'string' 类型的raw_input docs ,所以在这种情况下我们必须像这样将
totPrimes
'string' 类型转换为一个 'int' 或 'float' 类型:
totPrimes = raw_input("Please enter the primes: ")
totPrimes = float(totPrimes)
You can combine them like this:你可以像这样组合它们:
totPrimes = float(raw_input("Please enter the primes: "))
In order to compare things in python count < totPrimes
, the comparison needs to make sense (numbers to numbers, strings to strings) or the program will crash and the while count < totPrimes :
while loop won't run.为了比较 python
count < totPrimes
,比较需要有意义(数字到数字,字符串到字符串),否则程序将崩溃并且while count < totPrimes :
while 循环不会运行。
You can use try/except to protect your program.您可以使用 try/except 来保护您的程序。 managing exceptions
管理异常
For people taking the course "Programming for Everybody" you can take in hours and rate this way.对于参加“面向所有人的编程”课程的人,您可以花几个小时来进行评分。 the if/else statement you should try to figure out.
您应该尝试找出 if/else 语句。
You have to change every number to "hrs" or "rate".您必须将每个数字更改为“hrs”或“rate”。
For example: 40*10.50+(h-40)*10.50*1.5
is wrong, 40*r+(h-40)*r*1.5
is right.例如:
40*10.50+(h-40)*10.50*1.5
是错误的, 40*r+(h-40)*r*1.5
是正确的。
您需要像这样将 totPrimes 转换为 int:
integer = int(totPrimes)
Use input then.然后使用输入。
Raw input returns string.原始输入返回字符串。
input returns int.输入返回整数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.