已实现整数位数统计,如何添加执行后用户续行询问功能?
Solution for Adding a "Continue" Prompt to Your Digit Counter
Got it, let's get this sorted for you! The core issue here is wrapping your existing digit-counting logic in a loop that keeps running until the user chooses to stop. Here's how you can adjust your code to get the exact flow you want:
def countDigits(n): return len(str(n)) # Set a flag to control if the program keeps running keep_going = True while keep_going: num = int(input("Enter a number: ")) # Show the digit count result first print("The number of digits for:", num, "is:", countDigits(num)) # Ask user for continuation, with input validation while True: choice = input("Do you want to continue? Enter 1 for yes, 0 for no: ") if choice == "1": keep_going = True break elif choice == "0": keep_going = False break else: print("Oops, that's not a valid input! Please enter 1 or 0.")
Let's break down how this works:
- Outer Loop: The
while keep_goingloop ensures the program repeats the digit-counting process until the user says "no". - Result First, Prompt Second: Right after printing the digit count, we immediately ask the user if they want to continue — exactly the order you wanted.
- Input Validation: The inner
while Trueloop makes sure we only accept valid inputs (1 or 0), so the program won't break if the user accidentally types something else.
Give this a test run: it'll show the digit result first, then prompt you to either enter a new number or exit. Perfect!
内容的提问来源于stack exchange,提问作者Ranger
相关产品推荐
相关产品推荐

