'for loop and lists, new to python and programming [closed]
list = [3,4,5,6]
a = 4
for x in list:
if x <= 4:
a += x
print (a)
#can someone explain what the steps and how I got answer 11 when I print a?
Solution 1:[1]
If you use VSCode or Pycharm you have Debug option to understand what is happening in each step. Let's debug it:
a = 4
first loop:
x = 3and it's add toavariable that was4, soa = 4 + 3and nowa = 7second loop:
x = 4and it's equal to 4, so it's add toavariable that was7, soa = 7 + 4and nowa = 11third and fourth loop:
x = 5andx = 6and they are smaller than 4, so nothing happen.
and finally a is 11
Solution 2:[2]
list = [3,4,5,6]
a = 4
for x in list:
First iteration where x=3
if x<=4 === if 3<=4:
condition True, if block is executed value a will
a+=x ==== a=a+x
a=4+3 === a=7
Second iteration where x=4
if x<=4 === if 4<=4:
condition True , if block is executed value a will
a+=x ==== a=a+x
a=7+4 === a=11
Third iteration where x=5
if x<=4 === if 5<=4:
condition False
Fourth iteration where x=6
if x<=6 === if 6<=4:
condition False
No more values in list ,so for loop will terminate
print (a)
O/P --- 11
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | arya sianati |
| Solution 2 | zeeshan12396 |
