Python Forum
Help with conditions in loops
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with conditions in loops
#1
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)
Reply
#2
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)
Reply
#3
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.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020