jeudi 27 février 2020

Python For loops with while and if statements: Why doesnt it return in the first case?

Hey guys I know this question might seem dumb, but I just started. This is Python 3.7.
Any way I have written 2 versions of the code, the second one works, but I've added another while loop where I thought it wasn't needed. Why doesn't the first version work? Its iterating a list of numbers (nums).

This is from a problem statement: Write a function that takes in a list of integers and returns True if it contains 007 in order.

  • spy_game([1,2,4,0,0,7,5]) --> True
  • spy_game([1,0,2,4,0,5,7]) --> True
  • spy_game([1,7,2,0,4,5,0]) --> False

My first code was this, and it always returned False:

z = 0

for i in nums:
    while z < 2:
        if i != 0:
            break
        else:
            z += 1
            break
    if i != 7:
        break
    else:
        return True

return False

Why does this change, make it work?

z = 0

for i in nums:
    while z < 2:
        if i != 0:
            break
        else:
            z += 1
            break
    while not z < 2:
        if i != 7:
            break
        else:
            return True

return False

Thanks very much!

Aucun commentaire:

Enregistrer un commentaire