Robert N
Robert N

Reputation: 21

I am getting an error with a modulus operator

I don't understand why my modulu operator seems to be receiving an error message. Although, I'm not even sure that's the problem. This is the error message I received :

Traceback (most recent call last):
  File "c:\projectspython\myfirstchallenge.py", line 13, in <module>
    check = (number) % (2)
TypeError: not all arguments converted during string formatting

Code:

number = input("Enter a number: ")
check = (number) % (2) 
if check == 0:
    print("your number is even.")
elif check >= 0:
    print("Your number is odd.")
else:
    print("something else")

Upvotes: 1

Views: 907

Answers (2)

Innat
Innat

Reputation: 17229

You just need to cast it at the first place. Using input method , it simply takes as a string. So here you just need to cast it. That's it.

number = int(input("Enter a number: "))
check = (number) % (2) 
print(check)
if check == 0:
    print("your number is even.")
elif check >= 0:
    print("Your number is odd.")
else:
    print("something else")

Upvotes: 1

whackamadoodle3000
whackamadoodle3000

Reputation: 6748

Try this. You need to convert to int, or % will try to format it like a string. Also, you should make sure that your program won't error if a number is not given.

while True:
    try:
        number = int(input("Enter a number: "))
        break
    except:
        print("Enter a number")
check = number % 2 
if check == 0:
    print("your number is even.")
elif check >= 0:
    print("Your number is odd.")
else:
    print("something else")

Upvotes: 3

Related Questions