Home > Enterprise >  I don't understand why my for loop code works
I don't understand why my for loop code works

Time:12-13

I was following a lesson on for loops that told me, as an assignment, using for loops, to print out the even numbers from 1-10, and then print out how many even numbers there are. I was playing around with that and came to this solution:

number_even = 0

for i in range(1,10):
    if i % 2 == 0:
        print(i)
        number_even  = 1
if i:
     print ('We have', number_even, 'even numbers')

I understand everything up until

if i:
         print ('We have', number_even, 'even numbers')

I honestly was just playing around with Python, but dont understand how I get an expected output from this code. Please help.

CodePudding user response:

At the end of your loop, i=9, that's why it prints. If you set i=0 before if i: but after the loop, nothing prints.

if i: is equivalent to if i!=0:

CodePudding user response:

Your code is generally fine but the last if has no sense - you can just delete that condition and leave print statement. if some_number evaluates to True if and only if some_number is 0 (with assumption it's an integer)

But let me share one more version of this task that can help you understand python a bit more:

even_numbers = [] # This will be our list of even numbers

for i in range(1,10):
    if i % 2 == 0:
        even_numbers.append(i) # We add number to the list

print(even_numbers) 
print ('We have', len(even_numbers), 'even numbers')

CodePudding user response:

I think your confusion comes from the confusing nature of Python scopes.

The variable i doesn't fall out of scope when your loop ends, like it might in other languages. So, when you reach if i, this will succeed because i == 9

  • Related