Python Forum

Full Version: Two exact "Fors" giving me different results?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
So, I was practicing the For loop that I've found on the internet but if I copy-paste the original code, the list of numbers appears before the final odd an even numbers print. If I do it by myself, the numbers appear one by one before the odd and even prints...I don't know what I'm doing differently from the guy. I examined the code soo many times and I don't see any difference. My code is the one translated to Portuguese:

num = [0,1,2,3,4,5,6,7,8,9]

impar = 0
par = 0

for x in num:
    print(x)
    resto = x % 2
    if resto == 0:
        par = par + 1
    else:
        impar = impar + 1

    print("O Número de Pares é", par)
    print("O Número de Impares é", impar)
Result:

0
O Número de Pares é 1
O Número de Impares é 0
1
O Número de Pares é 1
O Número de Impares é 1
2
O Número de Pares é 2
O Número de Impares é 1
3
O Número de Pares é 2
O Número de Impares é 2
...

This is the one that I copied and it gives me the list of numbers before the last prints:

numbers = [1,2,3,4,5,6,7,8,9]

odd_number = 0
even_number = 0

for x in numbers:
    print(x)
    remainder = x % 2
    if remainder == 0:
        even_number = even_number + 1
    else:
        odd_number = odd_number + 1

print('number of even: ', even_number)
print('number of odd: ', odd_number)
Result:
1
2
3
4
5
6
7
8
9
number of even: 4
number of odd: 5

I'm new to Python and I really don't know what is the difference...I feel that there is something really obvious that I cannot see Wall Cry
the indentation of lines 13 and 14. In the first snippet they are inside the loop, so they get printed with every iteration. In the second snippet they are printed once - after the loop execution has completed

Indentation matters in python
(May-04-2020, 12:27 PM)buran Wrote: [ -> ]the indentation of lines 13 and 14. In the first snippet they are inside the loop, so they get printed with every iteration. In the second snippet they are printed once - after the loop execution has completed

Indentation matters in python

OMG Shocked
I knew it was something obvious...dam Doh .
I knew about the indentation but don't know how I've forgotten to inspect that
Well, thanks for the fast response...Feel kinda dumb right now.