Skip to content

Commit e8418c2

Browse files
Caleb CurryCaleb Curry
authored andcommitted
looping yo
1 parent 0a854f7 commit e8418c2

1 file changed

Lines changed: 84 additions & 0 deletions

File tree

‎beginner_python/09-nested-loops.py‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
########## NESTED FOR LOOP PT2 ###########
22

3+
34
#The previous section had this loop.
45
#The only thing we did was print j and a new line.
56
for i in range(4):
@@ -46,3 +47,86 @@
4647
#etc.
4748

4849

50+
########## NESTED WHILE ##########
51+
52+
53+
#We now have to worry bout the initialization and increment.
54+
55+
#print 0-4, 4 times:
56+
i = 0
57+
while i < 4:
58+
j = 0
59+
while j < 5:
60+
print(j, end=" ")
61+
j += 1
62+
print()
63+
i += 1
64+
65+
#not as clean...initialization and inrement has to be correct
66+
#pay close attention
67+
68+
#This won't work as expected:
69+
70+
print("Let's try this again:")
71+
i = 0
72+
j = 0
73+
while i < 4:
74+
while j < 5:
75+
print(j, end=" ")
76+
j += 1
77+
print()
78+
i += 1
79+
80+
print("What happened?") #j is never reset back to zero
81+
82+
83+
########## LOOP TO SUM ALL NUMBERS ##########
84+
85+
86+
#I want to calculate the sum of numbers 0-10: 10+9+8+7+6+5+4+3+2+1
87+
88+
sum = 0
89+
j = 10
90+
while j > 0:
91+
sum += j
92+
j -= 1
93+
print(sum) #55
94+
95+
#But now I want to get the sum of 9-0, 8-0, 7-0, 6-0, etc...
96+
#Here will be the structure:
97+
98+
i = 10
99+
while (i > -1): #include zero. Could also do >= 0
100+
#print sum from i to zero.
101+
i -= 1
102+
103+
104+
#We just coded how to sum to zero...so copy/paste that there....
105+
#change to j = i (dynamic from 10 to 0)
106+
print("All the sums:")
107+
i = 10
108+
while (i > -1):
109+
sum = 0
110+
j = i
111+
while j > 0:
112+
sum += j
113+
j -= 1
114+
print(sum)
115+
i -= 1
116+
117+
#We can now customize the output to be more readable:
118+
print("All the sums with output:")
119+
i = 10
120+
print("Getting sums up to", i)
121+
while (i > -1):
122+
sum = 0
123+
j = i
124+
while j > 0:
125+
if j > 1:
126+
print(j, "+", end=" ")
127+
else:
128+
print(j, "=", end=" ")
129+
sum += j
130+
j -= 1
131+
print(sum)
132+
i -= 1

0 commit comments

Comments
 (0)