Search code examples
pythonloopsinputintegercounting

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


I'm currently trying to make a program which first asks the user the amount of countable integers. Then the program proceeds to ask each countable integer from the user individually and in the end, the program prints the sum of the total integers calculated. Here is the code for my program:

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)

And this is how it currently works:

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

Now, here comes the tricky part: If two CONSECTUTIVE inputs are both zero (0), the program should end. How do I create a variable, which checks that the values of every CONSECTUTIVE inputs in my program are not zero? Do I need to create an another loop or what?

This is how I would want the program to work:

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.

Thanks in advance!


Solution

  • well let's start by breaking the problem down into it's components, you have two requirements.

    1. sum numbers
    2. exit if two zeros are given consecutively

    you have one completed, for two consider having an if which determines whether the given value is a non zero value and if it is a zero value check it does not equal the last value.

    you could modify your code as follows

    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)