-5
var=int(input("Enter anything ==>"))
if(var%2==0): 
    print(var," is a Even number")
elif((var>="a" and var<="z") or (var>="A" and var<="Z")):
    print(var," is String")
    print("Enter a number to find it is even or odd")
else:
    print(var," is a Odd number")

OUTPUT

C:\Users\HP\OneDrive\Desktop\All Desktop apps\Python>python input.py
Enter an enter code everything ==>6
6 is a Even number

C:\Users\HP\OneDrive\Desktop\All Desktop apps\Python>python input.py
Enter anything ==>sdsd
Traceback (most recent call last):
File "C:\Users\HP\OneDrive\Desktop\All Desktop apps\Python\input.py", line 5, in var=int(input("Enter anything ==>"))
ValueError: invalid literal for int() with base 10: 'sdsd'

#if the user enters anything like any alphabet or special character, then how can we show msg to the user that the input is invalid or its an alphabet or a special character or an integer or about specific data type
==> var=int(input("Enter anything ==>"))
==> #var=input("Enter anything ==>")




Incorrect Code -->



Incorrect Output -->



Correct code using exception handling-->



Correct output-->



1

1 Answer 1

3

The simplest way is try/except:

var = input("Enter anything ==>")
try:
    if int(var) % 2:  
        print(f"{var} is an odd number")
    else:
        print(f"{var} is an even number")
except ValueError:
    print(f"{var} is not a number")

If you want to re-prompt the user when they enter something that's not a number, put the whole thing in a while loop and break it when they enter a valid number.

while True:
    var = input("Enter anything ==>")
    try:
        if int(var) % 2:  
            print(f"{var} is an odd number")
        else:
            print(f"{var} is an even number")
        break
    except ValueError:
        print(f"{var} is not a number")
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.