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 :
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
Method 2
You need to cast totPrimes into an int like this:
integer = int(totPrimes)
Method 3
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 :
Method 4
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.
Method 5
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.
Method 6
Use input then.
Raw input returns string.
input returns int.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0