Python Forum

Full Version: Help with conditions in loops
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Given a sequence of integer numbers ending with the number 0. Determine the length of the widest fragment where all the elements are equal to each other.

The following code works. However, if I un-indent the "if statement" in red, some cases do not work. I don't see how this should affect how the program operates.
n, k = int(input()), int(input())
streak1, streaksum = 1, 1
 
while k != 0: 
    if n == k:
        streak1 += 1

        # Why does unindenting the following change results?
        if streak1 >= streaksum:
            streaksum = streak1     
    else: 
        streak1 = 1
         
    n, k = k, int(input())
 
print(streaksum)
If you unindent that block, the else lines up with the wrong block.  Your if statement does not need to be in the other if, but the else does need to be with the first block.

For instance:
n, k = int(input()), int(input())
streak1, streaksum = 1, 1
 
while k != 0: 
    if n == k:
        streak1 += 1
    else: 
        streak1 = 1

    if streak1 >= streaksum:
        streaksum = streak1

    n, k = k, int(input())

print(streaksum)
Because if you unindent that if block the else block will belong to that if not to the first one and all the programming logic is gone.