Home > Net >  I wrote a calculator together with a error handling but I do not understand why it doesnt work?
I wrote a calculator together with a error handling but I do not understand why it doesnt work?

Time:11-14

def arithmetic_sequence():
    a = float(input('Type the first term'))
    d = float(input('Type the difference'))
    n = float(input("Type the number of values"))
    if a == ValueError:
        print("Write a value")
    elif d == ValueError:
        print("Write a value")
    elif n == ValueError:
        print("Write a value")
    else:
        sum = float(n * (a   (a   d * (n - 1))) / 2)
        return sum
print(arithmetic_sequence())

My goal is that when a person writes a non number into the program for it to say Write a value but it only shows ValueError, why? I specifically write in the program for it to say "Type a value".

CodePudding user response:

When Python can't convert the user's string into a float it will raise a ValueError not return one. You need to catch the error like so:

try:
    a = float(input("Type the first term"))
except ValueError:
    print("Write a value")

CodePudding user response:

def arithmetic_sequence():
    try:
        a = float(input('Type the first term:'))
        d = float(input('Type the difference:'))
        n = float(input("Type the number of values:"))
        return float(n * (a   (a   d * (n - 1))) / 2)
    except ValueError:
        print("Write a value")


print(arithmetic_sequence())
  • Related