Int in raw_input does not work [duplicate] - python

This question already has answers here:
How can I convert a string to an int in Python?
(8 answers)
Closed 8 years ago.
while True:
a = raw_input("Your number: ")
if a == int: # letters:
if a > 0 and a % 3 == 0:
print 'fizz'
if a > 0 and a % 5 == 0:
print 'buzz'
if a > 0 and a % 3 != 0 and a % 5 != 0:
print a
if a <= 0:
print 'bad value'
else:
print "Not integer, try again"`
How do I make this raw_input work? I want this to run the game when the user input is an integer and "try again" when it is not.

raw_input() always returns a string. If you want to make it an int, call the int() builtin function. If the contents of the string cannot be converted, a ValueError will be raised. You can build the logic of your program around that, if you wish.

raw_input is a string. You can convert it to an int using int. If it's not convertible, this returns an error. So use try... except to handle the error. It's a good idea to put as little as possible into the try... part because otherwise some other error might be accidentally caught. Then put in a continue into the except part to skip back to the start.
while True:
try:
a= int(raw_input("Your number: "))
except ValueError:
print "not integer, try again"
continue
if a > 0:
if a % 3 == 0:
print 'fizz'
if a % 5 == 0:
print 'buzz'
if a % 3 != 0 and a % 5 != 0:
print a
else: #a<=0
print 'bad value'

Related

Why I am getting error as "not all arguments converted during string formatting" during this python code?

n = input("Enter your number: ")
if n%2 != 0:
print("Weird")
elif n%2 == 0:
if n>1 and n<6:
print("Not weird")
elif n>=6 and n<=20:
print("Weird")
elif n>20:
print("Not Weird")
While running this code I got the error message. I could not find the reason.
The problem is that you didn't convert your input to integer.
so instead of calculating remainder of n by 2. , You are get into string formatting in line if n%2 != 0:
The old way of formatting string was :
name = 'John'
print('hi %s' % name )
SorusH is right, you didn't convert your input to integer, you should try something like
n = int(input("Enter your number: "))
to convert the input into an integer

Invalid literal for int() with base 10: 'x' error in Python? [duplicate]

This question already has an answer here:
How do I check if input is a number in Python?
(1 answer)
Closed 4 years ago.
I'm working on a program that prompts a user for a number within a range of integers they've entered. If the number they enter is out of range, they're prompted to give another, and if they enter a letter instead they're prompted to change their answer as well. Here is what I've got:
def code_one(d, f):
s = input('Enter a number between' + str(d) + 'and' + str(f) + ': ')
s = int(s)
if int(d) <= s <= int(f):
return s
else:
while s < int(d) or s > int(f):
s = input(str(s) + 'is out of range. Please try again. ')
s = int(s)
if s < int(d) or s > int(f):
continue
else:
return s
while s.isdigit == False:
s = input(str(s) + 'is not a number. Please try again.' )
if s.isdigit == False:
continue
else:
return s
It works fine up until the line reading "while s.isdigit == False:" and then, if I input a letter instead of a number, I get the error "invalid literal for int() with base 10: 'x'", (the x being whatever letter I happen to enter). What can I do to fix this?
def code_one(d, f):
while True:
answer = input('Enter a number between %d and %d: ' % (d, f))
try:
answer = int(answer)
except ValueError:
print('%s is not a number. Please try again.' % answer)
continue
if d <= answer <= f:
return answer
else:
print('%d is out of range. Please try again.' % answer)

How to make a raw input a number? [duplicate]

This question already has answers here:
How can I convert a string to an int in Python?
(8 answers)
How do I parse a string to a float or int?
(32 answers)
Closed 8 years ago.
I wanted to make a simple program on my raspberry pi that will let a LED flash as many times as the number you type in. My program is working, but is a bit repetitive:
times = raw_input('Enter a number: ')
if times == '1':
times = 1
elif times == '2':
times = 2
elif times == '3':
times = 3
elif times == '4':
times = 4
elif times == '5':
times = 5
This would take a lot of programming to handle a larger inputs like 145.
Does anybody know a smarter and faster way of doing it?
PS: Code is finished;
# I know i need to import GPIO and stuff, this is just an example.
import time
while True:
try:
times = int(raw_input('Enter a number: '))
break
except ValueError:
print "Enter a number!"
print 'Ok, there you go:'
while times > -1:
if times > 0:
print 'hi'
times = times-1
time.sleep(1)
continue
elif times == 0:
print 'That was it.'
time.sleep(2)
print 'Prepare to stop.'
time.sleep(3)
print '3'
time.sleep(1)
print '2'
time.sleep(1)
print '1'
time.sleep(1)
print 'BYE'
break
Thank you.
times = int(raw_input('Enter a number: '))
If someone enters in something other than an integer, it will throw an exception. If that's not what you want, you could catch the exception and handle it yourself, like this:
try:
times = int(raw_input('Enter a number: '))
except ValueError:
print "An integer is required."
If you want to keep asking for input until someone enters a valid input, put the above in a while loop:
while True:
try:
times = int(raw_input('Enter a number: '))
break
except ValueError:
print "An integer is required."
Wrap your input in int or float depending on the data type you are expecting.
times = int(raw_input('Enter a number: '))
print type(times)
Outputs:
Enter a number: 10
<type 'int'>
If a user inputs something other than a number, it will throw a ValueError (for example, inputing asdf results in:)
ValueError: invalid literal for int() with base 10: 'asdf'
You can cast the input as an integer and catch the exception if it isn't:
try:
times = int(raw_input('Enter a number: '))
# do something with the int
except ValueError:
# not an int
print 'Not an integer'

Basic Program Control Flow & Exceptions Try [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 8 years ago.
I am attempting to create a basic program which requests a numeric value from the user.
If the value is between .5 and 1 the program should print "good".
If the value is between 0 to 0.49 the output states "fair".
If the numeric input the user provides is outside of 0 to 1 it states: "try again".
If the input cannot be converted to a number it states: "Invalid input".
Here is what I have got so far:
val=abs(1)
while True:
num = raw_input("Enter a number: ")
if num == "val" : break
print 'try again between 0 to 1'
try:
num = float(num)
except:
print "Invalid input"
if .5 < num < 1:
print 'Good'
if 0 < num < .49:
print 'Fair'
There's a couple issues with your code. I've cleaned up your code with regards to what I think what you actually want to do and commented most of the changes. It should be easily adjustable if you have slightly different needs.
val = 1 # abs(1) is the same as 1
while True: # get user input
num = raw_input("Enter a number: ")
try: # indented
num = float(num) # goes to except clause if convertion fails
if not 0 <= num <= val: # check against val, not "val",moved to try block
print 'try again between 0 to 1' # indented
else:
break # input ok, get out of while loop
except ValueError: # indented, only excepting ValueErrors, not processor is burning errors
print "Invalid input"
if .5 <= num <= 1:
print 'Good'
else: # 0 <= num < 0.5
print 'Fair'

Why isn't this simple code working, for Python?

x = raw_input("Write a number")
if x.isalpha():
print "Invalid!"
elif x%2==0:
print "The number you have written is EVEN"
elif x%2!=0:
print "The number you have written is ODD"
else:
print "Invalid!"
It is supposed to check if the number is odd or even and print it out. My if statement checks if the raw_input was an alphabet because that won't work. And my elif statements check for odd or even.
The return value of raw_input is always a string. You'll need to convert it to an integer if you want to use the % operator on it:
x = raw_input("Write a number")
if x.isalpha():
print "Invalid!"
x = int(x)
Instead of x.isalpha() you can use exception handling instead:
try:
x = int(raw_input("Write a number"))
except ValueError:
print 'Invalid!'
else:
if x % 2 == 0:
print "The number you have written is EVEN"
else:
print "The number you have written is ODD"
because int() will raise ValueError if the input is not a valid integer.
The return value of raw_input is a string, but you need a number to do the parity test.
You can check whether it's an alpha string, and if not, convert it to an int.
For example:
xs = raw_input("Write a number")
if xs.isalpha():
print "Invalid!"
else:
xn = int(xs)
if xn % 2 == 0:
print "The number you have written is EVEN"
elif xn % 2 != 0:
print "The number you have written is ODD"
else:
print "The universe is about to end."

Categories

Resources