Search code examples
pythonstringinputvalueerror

How can I use the ValueError function correctly?


This is my code:

from time import sleep

def Kontostand_Berechnen():
    if float(Kontostand_Nachfragen) >= float(Preis_Nachfragen):
        sleep(1)
        print("")
        print("Du hast genug Geld!")
        print("")
        sleep(1)
    else:
        sleep(1)
        print("")
        print("Du hast nicht genug Geld!")
        print("")
        sleep(1)

sleep(1)
print("")
Kontostand_Nachfragen = input("Wie viel Geld hast du?: ")
sleep(2)
print("")
Preis_Nachfragen = input("Wie viel kostet das Produkt?: ")
if ValueError:
    print("")
    sleep(1)
    print("Bitte nur Zahlen eingeben! Kein Text!")
    print("")
    sleep(1)
else:
    Kontostand_Berechnen()

I wrote this code just for practice and for fun. The print text is german. But I don't think that's hindering. I would like that if the user writes text and not a number, an error message is received. But that doesn't work as hoped. With this code, I ALWAYS get the error message, even when I write numbers. (I'm sure the code is not very understandable. I also only started using Python recently)


Solution

  • You are receiving the error because if else clauses aren't for checking for errors. That why python have try except clauses.

    Following on my answer here Check if String can be Converted to Float, you might want to take a look into to take a look into try except clause and check if the user put a number as input. Then, you will be able to treat input's that aren't numbers, like:

    try:
        your_input = float(input("")) # fill in with input text
    except Exception as e:
        raise ValueError("") # here you fill in the message you want to give to users
    

    However you might be able to check that when you do float(input("message")) you are already receiving a ValueError with a standard message, so with the code above you can just edit that message (putting it in german, for example).