Python Forum

Full Version: error mod = num % 2
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I try to print out odd and even number but I get error message at line 2 mod = num % 2
Here is the code
num = input ("Enter a number:")
mod = num % 2
if mod > 0:
    print("You picked an even number")
else:
    print("You picked an odd number")
and here is the error code
Error:
C:\Users\Lenovo\PycharmProjects\Scientific\venv\Scripts\python.exe C:/Users/Lenovo/.PyCharmCE2018.2/config/scratches/age.py Enter a number:6 Traceback (most recent call last): File "C:/Users/Lenovo/.PyCharmCE2018.2/config/scratches/age.py", line 2, in <module> mod = num % 2 TypeError: not all arguments converted during string formatting Process finished with exit code 1
What am I doing wrong?
input() returns str. And when used with str % is used for old-style formatting.
You need to conver user input to int, so then % will be modulo operator

>>> 'some string %d' % 3 # old-style str formatting
'some string 3'
>>> 4 % 3 # modulo operator
1
>>>
The input function returns a string. You need to convert it to an integer with int().

Edit: what buran said.