开发者

Python: Problem with raw_input reading a number [duplicate]

开发者 https://www.devze.com 2023-02-28 10:46 出处:网络
This question already has answers here: How can I read inputs as numbers? (10 answers) 开发者_JAVA技巧Closed 7 months ago.
This question already has answers here: How can I read inputs as numbers? (10 answers) 开发者_JAVA技巧 Closed 7 months ago.

unfortunately raw_input is not doing what I need it to do. What I am trying to do is get totPrimes = whatever I type in at the prompt. If i replace while count < totPrimes with while count < 50 this script works. If I type 50 into the prompt, this script doesnt work, I'm afraid raw_input isn't the function im looking to use? 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.


You need to cast totPrimes into an int like this:

integer = int(totPrimes)


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:

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.

You can use try/except to protect your program. 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.


You have to change every number to "hrs" or "rate".

For example: 40*10.50+(h-40)*10.50*1.5 is wrong, 40*r+(h-40)*r*1.5 is right.


Use input then.

Raw input returns string.

input returns int.

0

精彩评论

暂无评论...
验证码 换一张
取 消