Reputation: 3
I'm trying to make a program that has the user input a number and check if it's even or odd by dividing it by 2 and seeing if there's a remainder. but I keep getting an error saying "not all arguments converted during string formatting"
I haven't been able to do much because I can't find anything about it anywhere.
var = input("Enter a number!")
var1 = var % 2
if var1 > 0:
print("The entered number is odd")
else:
print("The entered number is even")
Upvotes: 0
Views: 40
Reputation: 20490
The python builtin input function gives you a string, you have to convert it to a int using int(input(..))
#Converted string to int
var = int(input("Enter a number!"))
var1 = var % 2
if var1 > 0:
print("The entered number is odd")
else:
print("The entered number is even")
Then the output will look like
Enter a number!5
The entered number is odd
Enter a number!4
The entered number is even
Note that your code will break if you provide a string as an input here
Enter a number!hello
Traceback (most recent call last):
File "/Users/devesingh/Downloads/script.py", line 2, in <module>
var = int(input("Enter a number!"))
ValueError: invalid literal for int() with base 10: 'hello'
So you can do a try/except
around conversion, and prompt the user if he doesn't give you an integer
var = None
#Try to convert to int, if you cannot, fail gracefully
try:
var = int(input("Enter a number!"))
except:
pass
#If we actually got an integer
if var:
var1 = var % 2
if var1 > 0:
print("The entered number is odd")
else:
print("The entered number is even")
else:
print("You did not enter a number")
The output will then look like
Enter a number!hello
You did not enter a number
Enter a number!4
The entered number is even
Enter a number!5
The entered number is odd
Looks much better now doesn't it :)
Upvotes: 1
Reputation: 3100
Like Austin mentioned in his comment, you need to typecast the output of the input
function.
input
returns a string, and asking for a remainder of a division between a string and a number is nonsensical.
var = int(input("Enter a number!"))
var1 = var % 2
if var1 > 0:
print("The entered number is odd")
else:
print("The entered number is even")
Upvotes: 0