Flow Control

PYTHON IS A SPACE SENSITIVE LANGUAGE, PLEASE FORMAT YOUR CODE WELL

If.. elif.. else

Like other oop languages, Python also has its own if-else statement, like C, there is no else if instead to use elif
example

//Code==========
score = 100
if score>=90:
    print ('excellent')
elif score>=80:
    print ('good')
elif score>=60:
    print ('passed')
else:
    print ('failed')
//Result==========
excellent

for loop

It is different to othoer oop languages, Python does for loop like iterator. for item in items:
example: (calculate the average score)

//Code==========
L = [75, 92, 59, 68]
sum = 0
for i in L:
    sum+=i
print (sum / 4)
//Result==========
73.5

while loop

If satisfied with the condition, it will execute the code chunck of while
example: (calculate the sum of odds which less than 100)

//Code==========
sum = 0
x = 1
while x<100:
    sum+=x
    x+=1
print (sum)
//Result==========
4950

Break the loop

using break allows user break the current layer of loop, if you are in nested loop, then you need one more break to jump out of the outter loop.
example: (calculate the sum of front 20 items 1 + 2 + 4 + 8 + 16 + ... )

//Code==========
sum = 0
x = 1
n = 1
while True:
    sum+=x
    x*=2
    n+=1
    if (n)>20:
        break
print (sum)
//Result==========
1048575

Skip the loop by condition

using continue allows user skip the current iterator of loop
example: (calculate the sum of odds of 100)

//Code==========
sum = 0
x = 0
while True:
    x = x + 1
    if x > 100:
        break
    if x%2==0:
        continue
    else:
        sum+=x
print (sum)
//Result==========
2500

Nested loop

example: (calculate the sum of two-digits items which first digit is less than second digit of 100)

//Code==========
for x in range(10):
    for y in range(10):
        if (x < y) and (x>0) and (y>0):
            print(x*10+y)
//Result==========
12 13 14 15 16 17 18 19 23 24 25 26 27 28 29 34 35 36 
37 38 39 45 46 47 48 49 56 57 58 59 67 68 69 78 79 89
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容