简体   繁体   中英

How do I exit a loop in python

Sorry, I am still a beginner in Python and am unsure how to exit a loop. Firstly I am having trouble with the "q to quit" input. I've messed around with it and can't get the program to exit using q or Q.

full_name = input ('Enter a customers name (or q to quit): ')
address = input ("Enter the customer's address: ")
location = input("Enter customer's city, state, and zip code: " )
cancel = 'q'
while cancel == 'q' or cancel == 'Q':
  print ()
  thin_M = 'Thin Mints'
  thin_M = int(input('Enter the number of Thin Mints: ')) 
  while thin_M > 10:
    print ('Sorry we are accepting a maximum of 10 boxes per type.')

Secondly, once I reach the while portion I find that if the number entered is over 10 my print statement will just continue to loop over and over again. What should I do to make sure the last print statement does not loop? The program should re-prompt and issue the sorry message. I am not sure if the top is also considered a loop but how would I get q or Q to work with to exit this code as well?

First, you never change cancel variable so the condition is always True and it then loops forever. I assume you rather wanted to check full_name against q as per your input prompt.

Also thin_M = 'Thin Mints' assignment is pointless as it gets overwritten before any read, so just remove it.

And finally, 2nd while should rather be plain if .

full_name = input ('Enter a customers name (or q to quit): ')
address = input ("Enter the customer's address: ")
location = input("Enter customer's city, state, and zip code: " )
cancel = full_name.lower() == 'q'
while cancel == False:
  print ()
  thin_M = int(input('Enter the number of Thin Mints: '))
  if thin_M > 10:
    print ('Sorry we are accepting a maximum of 10 boxes per type.')
  else:
    cancel = True

You can use break to get out of a loop. Your code also has some other errors, which I've fixedd. Try this:

full_name = input ('Enter a customers name (or q to quit): ')
if full_name == 'q':
  exit()
address = input ("Enter the customer's address: ")
location = input("Enter customer's city, state, and zip code: " )

text = ''
while text.lower() != 'q':
  thin_M = int(input('Enter the number of Thin Mints: '))
  if thin_M > 10:
    print ('Sorry we are accepting a maximum of 10 boxes per type.')
  else:
    break  

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