[Python Basic Tutorial] Program Flow Control Statements in Python


foreword

This blog will talk about the flow control statements in the Python language. In high school, we learned program flow problems in mathematics. To achieve a goal, we often need to go down step by step from the beginning, sometimes in sequence, sometimes facing choices, sometimes facing loops. Loops and selections control the entire process. Does the picture below look familiar? The sequential structure is executed step by step from the top to the next step, so we won't talk about it here. Just kidding with branching statements in the Python language.

insert image description here


The branch statement

In Python, the branch statement has only if...elif...else...no switch...case..., the official believes that if...else... can already meet the demand. The function of the branch statement is to make a judgment and filter out the data that meets a certain situation. In other words, different situations do different things.

# 单分支结构
if 80>70:
    print('无敌666')
# 多分支结构
s=int(input("请输入您的考试成绩:"))
if 100>=s>=90:
    print("你的成绩无敌了")
    if s>95:
        print('你的成绩至高无上')
    else:
        print('你的成绩一人之下万人之上')
elif 90>s>60:
    print('你的成绩仅仅是合格')
else:
    print('你的成绩不合格,或输入不规范')

# 条件表达式【类似于C++语言中的三目运算符】
print("我是对的" if 90>80 else "我是错的")

# 占位符与对象的布尔值
# 每个对象都有布尔值,所以对象可以直接放到条件语句中,作为判别条件
# python中也是只有0或空为bool中的false
# 占位符就是当你不知道那里写什么,但确实缺少语句处站住位置,编译器不报错 pass
ss=int(input("输入对象:"))
if ss:
    print('yes')
    pass
elif ss>1:
    print('no')
else:
    pass

Second, the loop statement

1. Iterable objects

Before talking about the loop statement, let's talk about what an iterable object is. An iterable object returns one element at a time
, mainly including sequences, file objects, iterator objects, and generator functions. An iterator is an object that represents
an iterable collection of data. Its main features include the methods __iter__() and __next__(), which can implement
iteration functions. A generator is a function, using the yield statement, that yields one value at a time. The range object is an iterator object.
The loop statement in Python is divided into while and for loops.

2.while loop

while后面是循环条件,在下面的例子中i就是循环变量,当循环变量不满足循环条件时就退出循环
以下例子打印1-100的和

code show as below:

i=1
mysum=0
while i<=100:
   mysum+=i
   i+=1
#    print(mysum)
print(mysum)

3.for loop

for循环的使用方法如下,一般结合迭代器对象使用。

code show as below:


# for循环计算100-999之间的水仙花数

for temp in range(100,1000):
   if temp==(temp%10)**3+(temp//10%10)**3+(temp//100)**3:
      print(temp)
# 迭代打印语句
for _ in range(5):
   print('Hello World')


# 利用else 实现密码输入错误三次报错,以及输入正确跳出循环

passward=0
for passward in range(3):
   if input('请输入您的密码:')!='888888':
      print('密码输入错误!')
      passward+=1
   else:
      print('密码正确!')
      break
else:
   print('密码多次输入错误,自动退出!')

4. Ninety-nine multiplication table

# 综合案例,嵌套打印99乘法表
for teg in range(1,10):
   temp=1
   while temp<=teg:
      print(str(temp)+'*'+str(teg)+'='+str(teg*temp),end='  ')
      temp+=1
   print()

insert image description here

3. Loop Control Statement

1.break

Jump out of this loop

2.continue

skip this cycle

3.goto

This statement is not built-in, but some third-party libraries contain this statement,
such as python-goto, and interested partners can use it.

4.else

This is still very unique. Python's loop statement supports the else statement,
that is, an else statement can be added after the loop statement. The condition for the code in the else code
block to be executed is that the loop body is not broken.
Also take the nine-nine multiplication table as an example

for teg in range(1,10):
   temp=1
   while temp<=teg:
      print(str(temp)+'*'+str(teg)+'='+str(teg*temp),end='  ')
      temp+=1
   print()
else:
    print("asdholcnnl")

Fourth, loop-related built-in functions

1.enumerate()

The function of this function is to add an index to the traversable sequence, and the starting value of the index is something we can specify

s=["Tom","jack","lisa"]
for i,name in enumerate(s,start=1):
    print(f"第{
      
      i}个人是{
      
      name}")

insert image description here

2.zip()

If you need to traverse multiple objects in parallel, you can use this function to pack. The role of zip is to pack multiple iterable objects into tuples and return an iterable object. If each compressed iterable has different lengths, merge them according to the shortest length. Tuples can also be unpacked into lists using the * operator.
[*zip(x,y)] Pack x, y and then convert to list form
zip(*zip(x,y)), if x, y represent a matrix, then zip(*zip(x,y)) its transpose

for i,j in zip(range(0,10),range(0,10)):
    print(i*j)

insert image description here

3.map()

The map function can pass a function and multiple iterable lists. If the function passed by map is None, then the map function is the same as the zip function.
If other functions are passed, the functions will be applied to each object. It should be noted that the number of iterable objects should be consistent with the
number of parameters passed into the function.

#结果1,1,12
list(map(abs,[-1,-1,-12]))
#结果1 1 4
list(map(pow,range(3),range(3)))


Summarize

This blog mainly shares the branch statement and loop statement in the flow control statement. The branch statement is relatively simple to operate. We mainly master the loop statement, especially several built-in functions in the loop statement, whether you are writing an algorithm problem or a are commonly used in data analysis.


insert image description here

Guess you like

Origin blog.csdn.net/apple_51931783/article/details/123095598