so basically this is my code, it's supposed to check if num is divisible by 4 and and 2 and print that out. If not it should only check if even or odd. If the user inputs a string instead of int it gives a different message.
num = (input("number:"""))
try:
val= int(num)
if int(num % 2)== 0 and int(num % 4)== 0:
print("this number is even and divisible by 4!")
elif (num % 2 == 0):
print("this number is even")
else:
print("this number is odd")
except ValueError:
print("bro just put a number")
I do realise while creating this that I could solve it by just checking if the number is a multiple of 4 with a single statement as it will always be even so checking if it is also divisible by 2 is redundant. However I'm more interested as to why I'm getting an error.
Error:
dario@Darios-MacBook-Pro Coding % /usr/local/bin/python3 /Users/dario/Desktop/Coding/test.py
number:5
Traceback (most recent call last):
File "/Users/dario/Desktop/Coding/test.py", line 4, in <module>
if int(num % 2)== 0 and int(num % 4)== 0:
TypeError: not all arguments converted during string formatting
CodePudding user response:
Is there a way to check if the user did indeed input an int
instead of string without converting "num" to "val"?
str.isdigit()
returns True
if all characters in the string are digits and there is at least one character, False
otherwise.
while True:
inp = input('number: ')
if inp.isdigit():
if int(inp) % 2:
print(f'{inp} is odd')
else:
if not (int(inp) % 4):
print(f'{inp} is divisible by 4')
else:
print(f'{inp} is even')
else:
print('bro just put a number')
CodePudding user response:
You need to parse the num
value, use int(num)
instead of int(num % 2) == 0
or just replace num
with val
.
At the end you will have this:
num = (input("number: """))
try:
val = int(num)
if val % 2 == 0 and val % 4 == 0:
print("this number is even and divisible by 4!")
elif (val % 2 == 0):
print("this number is even")
else:
print("this number is odd")
except ValueError:
print("bro just put a number")
CodePudding user response:
Take a look at your code again. You have defined
val= int(num)
But you never use the val variable in your code.
CodePudding user response:
So I just fixed it with help of the comments, since I converted string "num" to int "val" I had to then use "val" for the statements.
num = (input("number:"""))
try:
val= int(num)
if int(val % 2)== 0 and int(val% 4)== 0:
print("this number is even and divisible by 4!")
elif (val % 2 == 0):
print("this number is even")
else:
print("this number is odd")
except ValueError:
print("bro just put a number")
This is the working code.
CodePudding user response:
put the input() function inside the try... except... block, and convert the input value direct with int(input("number: "))
try:
num = int(input("number: "))
if num % 4 == 0:
print("this number is even and divisible by 4!")
elif num % 2 == 0:
print("this number is even")
else:
print("this number is odd")
except ValueError:
print("bro just put a number")````