求助:如何在Python等差数列计算器中实现无效输入时重启询问环节
Hey there! Awesome job putting together your first Python arithmetic series calculator—getting something functional as a beginner is such a solid win. Let's sort out that input validation issue for the restart prompt so it keeps asking until you get a valid y or n.
The problem right now is that when a user enters an invalid command, your code just prints an error and jumps straight back to the start of the main calculation loop. Instead, we want to stick to the restart prompt until the user gives a valid response.
Here's how to adjust your code:
import time from time import sleep # Move the function outside the loop (no need to redefine it every iteration!) def sumOfAP(a, d, n): sum = 0 i = 0 while i < n: sum = sum + a a = a + d i = i + 1 return sum while True: numsterm = int(input("Enter Number OF terms: ")) firstterm = int(input("Enter First Term: ")) difference = int(input("Enter The Difference: ")) print(sumOfAP(firstterm, difference, numsterm)) # Restart prompt with validation loop while True: user_continue = input("Would you like restart [y/n]? ").lower() # Case-insensitive input! if user_continue == 'y': print("Continuing...") sleep(0.5) break # Exit inner loop, go back to main calculation elif user_continue == 'n': print("Thank you for using this program") print("") print("-PettyRap") sleep(2) exit() # Exit the entire program else: print("Error: Command not found. Please enter 'y' or 'n'.") # No break here—inner loop repeats the prompt automatically
Key changes explained:
- Moved
sumOfAPoutside the main loop: Redefining the function every time the loop runs is unnecessary and inefficient. Defining it once at the top is cleaner practice. - Added an inner
while Trueloop for the restart prompt: This loop will keep asking for input until the user enters a validyorn. - Added
.lower()to the input: Makes the prompt case-insensitive—users can enterY,N,y, ornand it will work seamlessly. - Used
exit()for the 'n' case: Since we're in an inner loop, a simplebreakwould only exit the inner loop and go back to the main calculation.exit()ends the program entirely, which is what you want when the user chooses to quit.
Now if someone enters random text like "yeah" or "nope", the program will just show an error and ask again, instead of jumping back to the start of the calculator.
内容的提问来源于stack exchange,提问作者PettyRap

