Python Forum

Full Version: try except issue
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
Why not move the difficulty to one function? That would make the rest of the program simple.
def input_float(texte: str) -> float:
    while True:
        try:
            result = float(input(texte))
            break
        except ValueError:
            print("allo n'est pas un nombre, veuillez recommencer")
    return result


print('Choisir une conversion')
print("   1. Gallon américain")
print("   2. Litre")
choix = input_float("Votre choix? ")
print("")

if (choix == 1.0):
    val_L = input_float("Entrez un volume en gallons:  ")
    r = val_L * 3.78
    print(val_L, 'gallons équivaut à ', r, 'litres')

elif (choix == 2.0):
    val_G = input_float("Entrez un volume en litres:  ")
    r = val_G / 3.78
    print(val_G, 'litres équivaut à ', r, 'gallons')

else:
    print("Choisir entre 1 et 2 svp")
Output:
Choisir une conversion 1. Gallon américain 2. Litre Votre choix? 2 Entrez un volume en litres: t allo n'est pas un nombre, veuillez recommencer Entrez un volume en litres: 4 4.0 litres équivaut à 1.0582010582010584 gallons
Try/except isn't the only way to do error handling - you can instead have your functions return a value that represents a success or failure and work with those (exceptions then are turned into failures). This is the idea of a result type and I've given examples of how they work here.
These are all interesting solutions but when the teacher say you can only use methods from chap 1 to 4. You're stuck with those limits.
Pages: 1 2