Ad

Why Does The Code Executes Differently Once I Introduce Else-statement

- 1 answer

I was doing exercises at CodingBat today and came across an interesting problem:

Given an array of ints, return True if the array contains a 2 next to a 2 somewhere.

This code runs wrong half times:

for i in range(len(nums)-1):
    if nums[i] == 2 and nums[i+1] == 2:
        print(True)
    else: 
        print(False)

for the input nums = [1, 2, 2] it gives the output: False

And this code gives True:

for i in range(len(nums)-1):
    if nums[i] == 2 and nums[i+1] == 2:
        print (True)

print (False)

My question is why does the introduction of else statement changes the way the code works?

Ad

Answer

You are giving half outputs, as your first code prints False and then True. This is because you are printing on each iteration. So the first iteration checks whether 1 == 2 and False is printed. The next iteration checks if 2 == 2 so True is printed.

What you should do, is only print True if the condition is found and break from the loop, and print False only if the loop was exhausted without breaking. This means no consecutive numbers found and can be done with an else clause on the for loop:

nums = [1, 2, 2]
for i in range(len(nums)-1):
    if nums[i] == 2 and nums[i+1] == 2:
        print(True)
        break
else:
    print(False)

As to your question:

why does the introduction of else statement changes the way code works?

Well this is because it is equivalent to adding another condition. For example, this program:

x = 5
if x > 7:
    print("BIG!")
else:
    print("small...")

is equivalent to:

x = 5
if x > 7:
    print("BIG!")
if x <= 7:
    print("small...")

So by adding this second condition you are giving the code an alternative way of action in case the first one fails. If you omit the else (the second condition), the code has no alternative and simply does....nothing

For example, in the two pieces of code above, small... will be printed. But in this code:

x = 5
if x > 7:
    print("BIG!")

Nothing will be printed at all!

Ad
source: stackoverflow.com
Ad