课堂作业程序输入“done”后无法终止,循环重复执行求助
Hey Jordan, let's break down why your program keeps looping instead of shutting down after you enter "done" and generate the report. This is a super common loop logic issue—here are the most likely culprits and fixes:
1. You’re not exiting the main loop after generating the report
Chances are, when you input "done", your code runs the report function but doesn’t tell the outer loop to stop. For example, if your code looks something like this:
while True: employee_name = input("Enter employee name: ") if employee_name == "done": print_sales_report() # Oops—no break here, so the loop just starts over ytd_sales = input("Enter YTD sales: ")
Even after printing the report, the loop continues to the next line (asking for YTD sales) and then cycles back to the start. The fix is simple: add a break right after generating the report to exit the main loop immediately:
if employee_name == "done": print_sales_report() break # This tells the loop to stop entirely
2. Your input order is out of whack
Maybe your code is structured to ask for YTD sales after checking for "done", but you forgot to skip that step when "done" is entered. For instance:
keep_going = True while keep_going: name = input("Name: ") if name == "done": generate_report() # This runs even if you entered "done"! ytd = input("YTD sales: ") # process data...
In this case, after the report prints, the program still tries to collect YTD sales before looping again. Fix this by wrapping the non-"done" logic in an else block:
name = input("Name: ") if name == "done": generate_report() keep_going = False else: ytd = input("YTD sales: ") # process the employee's data here
3. You’re using a nested loop and only exiting the inner one
If your program uses nested loops (e.g., one for employees, one for multiple sales entries per employee), you might be breaking out of the inner loop but not the outer main loop. Double-check that when "done" is entered, you’re terminating all loops that keep the program running—you can use a flag variable to handle this cleanly:
program_running = True while program_running: name = input("Employee name (done to finish): ") if name == "done": generate_report() program_running = False continue # Skip the rest of the loop iteration # Inner loop for sales entries (if applicable) while True: sale = input("Enter sale amount (or 'next' for next employee): ") if sale == "next": break # Only exits the inner sales loop # process sale...
The core idea here is: as soon as you detect the "done" trigger, make sure all execution paths lead to terminating the main loop—don’t let the program fall through to code that prompts for more input.
内容的提问来源于stack exchange,提问作者Jordan Hawkes

