i am new to python and i've been trying to wrap my head around this code:
stop = int(input())
result = 0
for a in range(4):
print(a, end=': ')
for b in range(2):
result = a b
if result > stop:
print('-', end=' ')
continue
print(result, end=' ')
print()
i was wondering why the output is
0: 0 1
1: 2 4
2: 6 -
3: - -
why isn't it
0: 0 1
1: 3 4 --> since we're starting out with a = 1 and b = 2 so result is 1 2 = 3.
etc
i feel like im missing something funamentally. thank u in advance
CodePudding user response:
Value of b will never be 2. Each iteration of loop will initialise the scope variables. i.e. while looping first loop, value of b will range between 0 & 1.
Whereas, Value of result (a global variable) will be cumulative (value obtained from prev iteration).
iteration | a | b | result | output |
---|---|---|---|---|
1 | 0 | 0 | 0 | 0: 0.. |
2 | 0 | 1 | 1 | 0: 0 1 |
3 | 1 | 0 | 2 | 1: 2.. |
4 | 1 | 1 | 4 | 1: 2 4 |
5 | 2 | 0 | 6 | 2: 6.. |
6 | 2 | 1 | 9 | 2: 6 9 |
7 | 3 | 0 | 12 | 3: 12.. |
8 | 3 | 1 | 16 | 3: 12 16 |
CodePudding user response:
when a = 0 and b = 1, result = 0 0 1 = 1,
so, for a = 1 and b = 0, result = 1 1 0 = 2
when a = 1 and b = 1, result = 2 1 1 = 4
so, it will print 1: 2 4