How ti create a decision prompt for a loop with python 3.6

438 Views Asked by At

I am trying to create a decision prompt for a loop with python 3.6. But it does not work

def cycle():
looping = "yes"
while looping == "No" or "no" or "n" or "N":
    looping = input('Do you want to make a new calculation? \n \t (Y/N)')
    if looping == "No" or "no" or "n" or "N":
        looping = "yes"
        break
    elif looping != "No" or "no" or "n" or "N":
        print('This is not the right answer')
        looping="no"

Can somebody help me out with this code? Thank you!

2

There are 2 best solutions below

1
On BEST ANSWER

As well as the comparison error that Jean-François Fabre pointed out, there's a logic error here too. To simplify a little bit, this is the code in your example:

looping = "yes"
while looping == "no":
    (do stuff which might change looping to something else)

The while loop never starts. You should write:

looping = "no"
while looping == "no":
    (do stuff)

or as Jean-François said,

looping = "no"
while looping.lower() in ["no","n"]:
    (do stuff)

Then you're converting someone's "No" answer into a "yes"...?

Why not try staying in the loop forever unless the user provides valid input:

def cycle():
    newcalc = "no"
    while True:
        newcalc = input('Do you want to make a new calculation? \n \t (Y/N)')
        if newcalc.lower() in ["no","n"]:
            newcalc = "no"
            break
        if newcalc.lower() in ["yes","y"]:
            newcalc = "yes"
            break
        print('This is not the right answer')
0
On

you cannot compare strings like that:

while looping == "No" or "no" or "n" or "N": # wrong

Basically the trailing or statements just check if "no" is not empty, etc.. they're useless.

  • If looping=="No", you'll get True: loop continues
  • If looping!="No", you'll get the next "non-False": "no": loop continues

correct way: converting to lowercase, and test if string belongs to a list:

while looping.lower() in ["no","n"]: