vendredi 21 octobre 2016

Is there a way convert an elif and a while statment into one ?

I'm am writing a simple program that look something like this:

while True:
    choice = float(input("options: "))

    if choice == 1:
        # Do something

    elif choice == 2:
        # Do something

    elif choice == 3: # <--- seems redudant
        while choice == 3:
            choice_return = input("do you want to return?: ")

                if choice_return == "yes":
                    choice = None
                else:
                   pass

     elif choice == 4:
         break

As noted in the the code, the "elif statment" seems redundant because it has the same conditions as the "while loop" below. You can of course simply write the code as follows:

while True:
    choice = float(input("options: "))

    if choice == 1:
        # Do something

    elif choice == 2:
        # Do something

    elif choice == 4:
        break

    while choice == 3: <--- three after four, no!!!
        choice_return = input("do you want to return?: ")     
             if choice_return == "yes":
                  choice = None
             else:
                 pass

which don't look to bad in this example, but in the actual code, it kinda ruins the structuring (and my OCD don't allow for that). Is there a way I can remove the redundancy while maintaining order?

NB. assume the "choice number" is fixed.

Aucun commentaire:

Enregistrer un commentaire