Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
try except issue
#11
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
Frankduc likes this post
Reply
#12
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.
Reply
#13
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.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020