如何检查循环中的两个连续输入是否相同(PYTHON)?

How to check if two consecutive inputs in a loop are the same (PYTHON)?

我目前正在尝试制作一个程序,它首先询问用户可数整数的数量。然后程序继续向用户单独询问每个可数整数,最后,程序打印计算出的总整数的总和。 这是我的程序的代码:

amount_of_integers = int(input("How many numbers do you want to count together: "))
sum = 0
repeat_counter = 1

while repeat_counter <= amount_of_integers:
    countable_integer = int(input(f"Enter the value of the number {repeat_counter}: "))
    sum += countable_integer
    repeat_counter += 1

print()
print("The sum of counted numbers is", sum)

这是目前的工作方式:

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: 2
Enter the value of the number 3: 3
Enter the value of the number 4: 4
Enter the value of the number 5: 5

The value of the counted numbers is: 15

现在,棘手的部分来了:如果两个 CONSECTUTIVE 输入均为零 (0),程序应该结束。如何创建一个变量,检查程序中每个连续输入的值是否不为零?我需要创建另一个循环还是什么?

这就是我希望程序运行的方式:

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: 0

Two consectutive zero's detected. The program ends.

提前致谢!

好吧,让我们首先将问题分解成它的组成部分,您有两个要求。

  1. 数字总和
  2. 如果连续给出两个零则退出

你已经完成了一个,因为两个考虑有一个 if 来确定给定值是否是一个非零值,如果它是一个零值检查它不等于最后一个值。

您可以按如下方式修改您的代码

amount_of_integers = int(input("How many numbers do you want to count together: "))
sum = 0
repeat_counter = 1
# last integer variable
last_integer = None

while repeat_counter <= amount_of_integers:
    countable_integer = int(input(f"Enter the value of the number {repeat_counter}: "))
    # if statement to validate that if the last_integer and countable_integer
    # are equal and countable_integer is zero then break the loop
    if countable_integer == last_integer and countable_integer == 0:
        break
    else:
        last_integer = countable_integer
    sum += countable_integer
    repeat_counter += 1
    
print()
print("The sum of counted numbers is", sum)