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)
本文介绍了Python编程中的两种基本循环结构:for循环和while循环。for循环常用于遍历序列,如列表,其语法清晰,循环次数明确。示例中展示了使用for循环计算1到50的和。while循环则在满足特定条件时执行,循环次数不固定。通过例子展示了while循环同样可以实现求和功能,并且在条件改变时依然适用。文章还对比了两者的优缺点和适用场景。

被折叠的 条评论
为什么被折叠?



