简体   繁体   中英

Breaking out of a loop or continuing it under certain conditions (Python)

I'm a little new to Python so I apologise in advance if this is a really simple question but I have been trying to wrap my mind around this problem for a while now.

Simply put, my code is to prompt the user if they have written down a couple of values correctly, If they have I want the loop to continue so the values can be saved to a database. If they have not I would like the code to loop back to the top of the while loop so they can re-enter the values.

For some reason when I enter 'no' It goes through the loop regardless, how may I fix this? Here's the code below:

while True:

  clear()

  print("\nPlease input the required data.\n")

  in_name = input('Name: ')
  in_email = input('Email: ')
  in_address = input('Address: ')
  
  clear()

  print("\nDoes this look correct?\n")
  
  print("#--START--#\n")
  print("Name: " + in_name)
  print("Email: " + in_email)
  print("Address " + in_address)
  print("\n#---END---#\n")

  validate == input(">>> ")

  if validate == "no":
    continue

  elif validate == "yes":
    print("/nAttempting to copy to the database...")

  cursor.execute("""
  INSERT INTO contacts(name, email, address)
  VALUES (?,?,?)
  """, (in_name, in_email, in_address))

  conn.commit ()

  print ( 'Data entered successfully.\n' )

  break

(I should note that this write program is part of a larger program, the loop is nested within another loop that acts as the main menu, perhaps that may help.)

the keyword continue will take you back to the next iteration without finishing the current one, example.

for i in range(5):
if i == 2:
    continue
print(i * 5)

This means that when i is 2 it wont print(i=2 * 5), instead it will go up to start the next loop where i=3. The output will be 0 5 15 20

If you use break, it will just completely stop and exit out of the iteration once it reaches this keyword. I think you're looking for the keyword pass.

'while True:' will always be True, meaning the loop will go on forever. I believe that you'll need to break out of the loop for it to stop. Based on Jorge Alvarez's answer, even changing 'continue' to 'pass' will allow the loop to go forever.

If I understand correctly, you'll need to change the initial 'while True:' statement to test whether validate equals 'no' or 'yes'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM