欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python study notes Day 2 ‘for‘ loop and ‘while‘ loop

程序员文章站 2022-05-27 22:08:18
...

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**
Python study notes Day 2 ‘for‘ loop and ‘while‘ loop

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:
Python study notes Day 2 ‘for‘ loop and ‘while‘ loop

List2 = range(1,5)
for idx in List2:
    print(idx)

Example:
sum for 1-50
Python study notes Day 2 ‘for‘ loop and ‘while‘ loop

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
Python study notes Day 2 ‘for‘ loop and ‘while‘ loop

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:
Python study notes Day 2 ‘for‘ loop and ‘while‘ loop

Sum = 0
n = 1
while n <= 50:
    Sum += n
    n += 1
    
print("Summary is %d" %Sum)

Example 2:
Python study notes Day 2 ‘for‘ loop and ‘while‘ loop

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:
Python study notes Day 2 ‘for‘ loop and ‘while‘ loop

a = 0
n = 10000
while ( n <= 13000):
    n *= 1.1
    a += 1
    
print(a)
print("a is %d" %a)