Search code examples
pythonloopsvariablesbreak

Is that a way to break a while loop in the if loop, like I want if the certain variable is true, than the while loop ends


What i want is if you choose a specific things to do by typing 1 or 2,but it will always run the 'gen' option(number 1) even if you type 2.

while True:
  a=int(input("pls choose what do you want to do.\n1=generates password \n2=acess saved passwords \n3=save passwords\nenter here:"))
  if a == 1:
    gen=True
    break

  if a==2:
    see=True
    break
  if a==3:
    save=True
    break
  else:
    print('pls enter a valid respond\n----------------------------------------')
    continue
  if gen: #*<--it will always run this*
    break
  break 
  if see:
    f = open("data.txt", "a")#*this did not run if typed '2'*
    content=f.read()
    f.close()
    print(content)

Solution

  • Remove the break from if statement

    while True:
          a=int(input("pls choose what do you want to do.\n1=generates password \n2=acess saved passwords \n3=save passwords\nenter here:"))
          if a == 1:
            gen=True
            break---> Your code break when you type 1
        
          if a==2:
            see=True
            break ---> Your code break when you type 2
          if a==3:
            save=True
            break
          else:
            print('pls enter a valid respond\n----------------------------------------')
            continue
          if gen: #*<--it will always run this*
            break
          break 
          if see:
            f = open("data.txt", "a")#*this did not run if typed '2'*
            content=f.read()
            f.close()
            print(content)`enter code here`