How can I only allow the input of numbers using exception handling?

Question:

I’m still learning python and I’m trying to figure out how to only allow numerical input using try except. How would I do this?

My code:

def main():
    
    print("College Classification")
    print("")
    credits = float(input("Enter number of credits: "))
    if credits > 0 and credits <= 7:
        print("The classification is Freshman") 
    elif credits > 7 and credits <= 16:
        print("The classification is Sophomore")
    elif credits > 16 and credits <= 25:
        print("The classification is Junior")
    elif credits > 25:
        print("The classification is Senior")
    else:
        print("Error")
    input("")
    
if __name__ == "__main__":
    main()
Asked By: juniorsandwich

||

Answers:

Update related line to this:

credits = 0
try:
    credits = float(input("Enter number of credits: "))
except ValueError:
    print("unsupported input")
    return
Answered By: Majid

You simply need to declare the input variable. Try to convert it, and catch an exception. If the code fails to convert the input to a float, it will remain 0 and return to the top of the loop.

def main():
    
    print("College Classification")
    print("")
    credits = 0
    while credits == 0:
        try:
            credits = float(input("Enter number of credits: "))
        except:
            print("Please enter a valid number")
    if credits > 0 and credits <= 7:
        print("The classification is Freshman") 
    elif credits > 7 and credits <= 16:
        print("The classification is Sophomore")
    elif credits > 16 and credits <= 25:
        print("The classification is Junior")
    elif credits > 25:
        print("The classification is Senior")
    else:
        print("Error")
    input("")
    
if __name__ == "__main__":
    main()
Answered By: Dylan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.