Home > Mobile >  Flowchart getting complicated with while loops in Python
Flowchart getting complicated with while loops in Python

Time:11-05

I would appreciate some help with this:

I try to make a form-program of the "Then why worry" philosophy:enter image description here

I wrote this code, but I can't understand how do I make the while loop repeat itself every time the user doesn't enter "yes" or "no" in both questions.

problem = str(input("Do you have a problem in life? "))
problem = problem.replace(" ", "").lower() #nevermind caps or spaces
while problem:
  if problem not in ("yes","no"):
   print("Please enter YES or NO")
  if problem == "no":
    break
  if problem == "yes": 
   something = str(input("Do you have something to do about it? "))
  something = something.replace(" ","").lower()
  while something:
    if something not in ("yes","no"):
      print("Please enter YES or NO")
    elif: 
     break
print("Then why worry?")

CodePudding user response:

I'd suggest to use while True loops, so you can put the input code once, then with the correct condition and break you're ok

while True:
    problem = input("Do you have a problem in life? ").lower().strip()

    if problem not in ("yes", "no"):
        print("Please enter YES or NO")
        continue

    if problem == "no":
        break

    while True:
        something = input("Do you have something to do about it? ").lower().strip()
        if something not in ("yes", "no"):
            print("Please enter YES or NO")
            continue
        break
    break

print("Then why worry?")

Using walrus operator (py>=3.8) that could be done easier

while (problem := input("Do you have a problem in life? ").lower().strip()) not in ("yes", "no"):
    pass
if problem == "yes":
    while (something := input("Do you have something to do about it? ").lower().strip()) not in ("yes", "no"):
        pass

print("Then why worry?")

CodePudding user response:

Your algorithm is linear, there is no loops in there. So, the only place you need a loop is when you try to get correct response from the user. So, I'd propose you to move that into a function and then your example turns into this:

def get_user_input(prompt):
    while True:
        reply = input(prompt).replace(" ", "").lower()
        if reply in ['yes', 'no']:
            return reply
        print("Please enter YES or NO")

problem_exists = get_user_input("Do you have a problem in life? ")
if problem_exists == 'yes':
    action_possible = get_user_input("Do you have something to do about it? ")
print("Then why worry?")
  • Related