Home > front end >  Is that a way to break a while loop in the if loop, like I want if the certain variable is true, tha
Is that a way to break a while loop in the if loop, like I want if the certain variable is true, tha

Time:05-06

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)

CodePudding user response:

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`

CodePudding user response:

It's not entirely clear what you're asking, but there are at least two things you should change to accomplish what I imagine it is you're trying to do. First, you should use elif for the conditions a == 2 and a == 3:

if a == 1:
    gen = True
    break
elif a == 2:
    see = True
    break
elif a == 3:
    save = True
else:
    print(...)
    continue
...

Right now, it appears that you will ask for a valid response whenever the input is not 3 (including when it is 1 or 2), but I imagine you only wish to print this statement when the inputs is not 1, 2, or 3. Second, the reason f = open("data.txt"...) did not run is that this code block is inside the while loop. Whenever part of the code causes the program to exit the while loop (such as a break statement), nothing in the rest of the loop will be executed, including the if see: block.

  • Related