7
votes

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 :
6
consider changing the title to something more adequate. p.e.'Problem with raw_input reading a number', or similar. - joaquin
FYI, this is a problem in Python 2.x, since you can compare objects of different types. In Python 3.x it will raise a TypeError: unorderable types. - Katriel

6 Answers

12
votes

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.

0
votes

You need to cast totPrimes into an int like this:

integer = int(totPrimes)
0
votes

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 :
0
votes

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.

0
votes

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.

-1
votes

Use input then.

Raw input returns string.

input returns int.