Judgment and loop of Python series

Thanks for likes and attention, a little progress every day! come on!

Table of contents

1. Judgment statement

1.1 Judgment statement format in Shell

1.2 Judgment statement format in Python

Second, the loop statement

2.1 Python while loop

2.1.1 Basic format of while loop

2.1.2 while loop using else statement

2.2 Python for loop statement

2.2.1 Basic format of for loop

2.2.2 Loop using the else statement


1. Judgment statement


1.1 Judgment statement format in Shell


Shell double branch judgment statement :

if 条件;then
    执行动作一
else
    执行动作二
fi

Shell multi-branch judgment statement :

if 条件一;then
    执行动作一
elif 条件二;then
    执行动作二
elif 条件三;then
    执行动作三
else
    执行动作四
fi

1.2 Judgment statement format in Python


A Python conditional statement is a code block that is determined to be executed by the execution result (True or False) of one or more statements.

Use the following figure to briefly understand the execution process of conditional statements:

Python single branch judgment statement :

if 条件:                  # 条件结束要加:号(不是;号)
    执行动作一            # 这里一定要缩进(tab键或四个空格),否则报错
                          # 没有fi结束符了,就是看缩进

Python double branch judgment statement :

if 条件:
    执行动作一           
else:                   # else后面也要加:
    执行动作二

Python multi-branch judgment statement :

if 条件一:
    执行动作一
elif 条件二:             # elif 条件后面都要记得加:
    执行动作二
elif 条件三:
    执行动作三
else:
    执行动作四

if nested

if 条件一:
    if 条件二:
		执行动作一		# 条件一,二都为True,则执行动作一
    else:
        执行动作二		# 条件一True,条件二False,则执行动作二
    执行动作三			# 条件一True,条件二无所谓,则执行动作三
else:
    if 条件三:
        执行动作四		# 条件一False,条件三True,则执行动作四
    else:
        执行动作五		# 条件一False,条件三False,则执行动作五
	执行动作六			# 条件一False,条件二,三无所谓,则执行动作六
执行动作七				# 与if里的条件无关,执行动作七

Example:

import random

num = random.randint(1, 100)

if 50 < num <= 90 and num != 3:
    print(num)
elif 40 < num < 30:
    print(num)
else:
    print(num)

if num > 90:
    print(num)
    if num > 95:
        print(num)
    else:
        print(num)
else:
    print(num)

Second, the loop statement


The following is the general form of a loop statement in most programming languages:

Python provides for loop and while loop (there is no do..while loop in Python):

cycle type

describe

while loop

Execute the loop body when the given judgment condition is true, otherwise exit the loop body.

for loop

repeat statement

nested loop

You can nest for loops inside while loop bodies


loop control statement

Loop control statements can change the order in which statements are executed. Python supports the following loop control statements:

control statement

describe

break statement

Terminate the loop during the execution of the statement block and jump out of the entire loop

continue statement

Terminate the current loop during the execution of the statement block, jump out of this loop, and execute the next loop.

pass statement

pass is an empty statement, in order to maintain the integrity of the program structure.

2.1 Python while loop


The while statement in Python programming is used to execute programs cyclically, that is, to execute a certain program cyclically under certain conditions to process the same tasks that need to be processed repeatedly. Its basic form is:

while 判断条件(condition):     
    执行语句(statements)……

The execution flow chart is as follows:

2.1.1 Basic format of while loop

while 条件:
      条件满足时候:执行动作一
	  条件满足时候:执行动作二
      ......

Example: guess the number game

import random				# 导入随机数模块

num = random.randint(1, 100)	# 取1-100的随机数(包括1和100)

while True:
    gnum = int(input("你猜:"))
    if gnum > num:
        print("猜大了")
    elif gnum < num:
        print("猜小了")
    else:
        print("猜对了")
        break

print("领奖")

2.1.2 while loop using else statement

In python, while ... else executes the else block while the loop condition is false:

Example:

count = 0
while count < 5:
   print(count, " is  less than 5")
   count = count + 1
else:
   print(count, " is not less than 5")

Results of the:

2.2 Python for loop statement


The for loop traverses an object (such as a data sequence, string, list, tuple, etc.), and determines the number of cycles according to the number of traversals.

A for loop can be regarded as a definite loop , while a while loop can be regarded as an indefinite loop .

flow chart:

2.2.1 Basic format of for loop

for 变量  in  数据:
    重复执行的代码

Example:

print("++++++++++++++++++++++++++++++++++")
for line in range(6):                # [0, 5] 迭代 6 次
    for i in range(line + 1):
        print("* ", end=" ")
    print()

print("++++++++++++++++++++++++++++++++++")
for line in range(1, 4):              # [1, 4) 迭代 3 次
    for field in range(1, 4):
        print("*", end=" ")
    print()

print("++++++++++++++++++++++++++++++++++")
fruits = ['banana', 'apple', 'mango']  # 列表
for index in range(len(fruits)):       # 通过索引遍历
    print('当前水果 : %s' % fruits[index])
print("Good bye!")

Results of the:

2.2.2 Loop using the else statement

In python, for ... else means this. The statement in for is no different from ordinary ones. The statement in else will be executed when the loop is executed normally (that is, the for is not interrupted by breaking out).

for num in range(10,20):  # 迭代 10 到 20 之间的数字
   for i in range(2,num): # 根据因子迭代
      if num%i == 0:      # 确定第一个因子
         j=num/i          # 计算第二个因子
         print ('%d 等于 %d * %d' % (num,i,j))
         break            # 跳出当前循环
   else:                  # 循环的 else 部分
      print ('%d 是一个质数' % num)

Results of the:

reference:

Python for loop statement | Novice Tutorial


                               Thanks for likes and attention

Guess you like

Origin blog.csdn.net/qq_35995514/article/details/130700113