Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
error mod = num % 2
#1
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?
Reply
#2
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
>>>
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
The input function returns a string. You need to convert it to an integer with int().

Edit: what buran said.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020