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

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

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**
Screen Shot 1

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:
Screen Shot 2

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

Example:
sum for 1-50
Screen Shot 3

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
Screen Shot 4

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:
Screen Shot 5

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

Example 2:
Screen Shot 6

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:
Screen Shot 5

a = 0
n = 10000
while ( n <= 13000):
    n *= 1.1
    a += 1
    
print(a)
print("a is %d" %a)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值