Python study notes Day 2 ‘for‘ loop and ‘while‘ loop
Python study notes Day 2
LOOP
In the day 2, I gonna to study loop. The Loop is a particularly important part in the program compilation.
There are two basic loop structures.
FOR
WHILE
I’ll explain the uses, differences, and pros and cons of each of the two loops below.
‘for’ loop
‘for’ loop is indicated by the keyword ‘for’
The ‘for’ loop have a clear number of loops, or a clear end-of-loop flag.
** for a in b:
loop body**
List1 = [1,2,3,4]
#For each element in List1, we give that element a temporary variable, idx, to print.
for idx in List1:
print(idx)
When we need to generate the list by the range function:
List2 = range(1,5)
for idx in List2:
print(idx)
Example:
sum for 1-50
ListSum = 0
for idx in range(1,51):
ListSum = ListSum + idx
print(ListSum)
‘while’ loop
Now, let’s talk about the ‘while’ loop.
When certain conditions are met, there are no specific restrictions or requirements on how many times to loop.
while( the loop condition ):
loop body
Example 1:
sum for 1-50
Sum = 0
n = 1
while n <= 50:
Sum = Sum + n
n = n + 1
print("Summary is %d" %Sum)
Or we can type the code like this:
Sum = 0
n = 1
while n <= 50:
Sum += n
n += 1
print("Summary is %d" %Sum)
Example 2:
a = 0
n = 10000
while ( n <= 13000):
n = n * 1.1
a = a + 1
print(a)
print("a is %d" %a)
We can also make the code like this:
a = 0
n = 10000
while ( n <= 13000):
n *= 1.1
a += 1
print(a)
print("a is %d" %a)