Python技术问询:如何检测循环中连续两次输入是否相同,且连续输入0时终止程序
Solution
Hey there! You don't need an extra loop to add this feature—all you need is a single variable to track the previous input value. Here's how to implement it:
Key Ideas
- Add a variable like
previous_numberto store the last integer the user entered. Initialize it to a non-zero value (likeNone) so the first input of 0 doesn't accidentally trigger the termination. - After each new input, check if both the current input and the previous one are 0. If yes, print your termination message and exit the loop immediately.
- Even if you haven't collected all the requested numbers yet, the program should stop as soon as two consecutive zeros are detected.
Modified Full Code
amount_of_integers = int(input("How many numbers do you want to count together: ")) total_sum = 0 repeat_counter = 1 previous_number = None # Tracks the last input, starts as None to avoid false triggers while repeat_counter <= amount_of_integers: current_num = int(input(f"Enter the value of the number {repeat_counter}: ")) # Check for two consecutive zeros if previous_number == 0 and current_num == 0: print("\nTwo consecutive zero's detected. The program ends.") break total_sum += current_num previous_number = current_num # Update the previous number to current input repeat_counter += 1 else: # This block runs only if the loop finishes normally (no break triggered) print() print("The sum of counted numbers is", total_sum)
Breakdown of Changes
previous_numberVariable: This keeps track of the last input. Starting withNoneensures that if the first input is 0, there's no "previous" 0 to trigger the termination.- Consecutive Zero Check: Right after getting the current input, we check if both it and the previous input are 0. If so, we print the message and use
breakto exit the loop immediately. whileLoopelseBlock: This is a handy Python feature—this block runs only when the loop completes all iterations (i.e., we collected all requested numbers without hitting the consecutive zero condition). It prints the total sum in that case.- Renamed
sumtototal_sum:sumis a built-in Python function, so using it as a variable name can cause unexpected issues. Renaming it avoids that conflict.
Test Examples
Termination Triggered
How many numbers do you want to count together: 5
Enter the value of the number 1: 1
Enter the value of the number 2: 0
Enter the value of the number 3: 0Two consecutive zero's detected. The program ends.
Normal Completion
How many numbers do you want to count together: 3
Enter the value of the number 1: 2
Enter the value of the number 2: 4
Enter the value of the number 3: 6The sum of counted numbers is 12
内容的提问来源于stack exchange,提问作者lute
相关产品推荐
相关产品推荐

