04-5 python syntax of the entry process control

[TOC]

# A primer:

That flow control flow control, specifically refers to the flow of the control program execution, the execution flow of the program is divided into three structures: the structure of the sequence (before we write the code is sequential structure), a branched structure (if used judgment), the cyclic structure (used while and for)

Illustration: spoof 20
04-5 python syntax of the entry process control

# Biantennary structure

2.1 What is the branch structure

Branch structure different branches is to perform the corresponding determination condition in accordance with subcode genuineness

2.2 Why use a branch structure

Sometimes humans need to decide to do something based on conditions, such as: If it rains today, umbrella
04-5 python syntax of the entry process control

Therefore, the program must have the appropriate mechanism to control a computer provided with this human judgment

2.3 How to use the branch structure

### 2.3.1 if grammar

Illustration: spoof 18
04-5 python syntax of the entry process control

If using keywords to achieve the branching structure, full syntax

if 条件1:   # 如果条件1的结果为True,就依次执行:代码1、代码2,......
   代码1
    代码2
    ......
elif 条件2: # 如果条件2的结果为True,就依次执行:代码3、代码4,......
   代码3
    代码4
    ......
elif 条件3: # 如果条件3的结果为True,就依次执行:代码5、代码6,......
   代码5
    代码6
    ......
else:     # 其它情况,就依次执行:代码7、代码8,......
    代码7
    代码8
    ......
# 注意:
# 1、python用相同缩进(4个空格表示一个缩进)来标识一组代码块,同一组代码会自上而下依次运行
# 2、条件可以是任意表达式,但执行结果必须为布尔类型
     # 在if判断中所有的数据类型也都会自动转换成布尔类型
       # 2.1、None,0,空(空字符串,空列表,空字典等)三种情况下转换成的布尔值为False
       # 2.2、其余均为True 

### 2.3.2 if application case

Illustration: spoof 19
04-5 python syntax of the entry process control

Case 1:

If: a woman's age> 30 years old, then: call aunt

age_of_girl=31
if age_of_girl > 30:
    print('阿姨好')

Case 2:

If: a woman's age> 30 years old, then: call aunt, otherwise: a lady

age_of_girl=18
if age_of_girl > 30:
    print('阿姨好')
else:
    print('小姐好')

Case 3:

If: a woman's age> = 18 and <22 years of age and height> 170 and the weight <100 and is beautiful, then: tell the truth, or else: call aunt **

age_of_girl=18
height=171
weight=99
is_pretty=True
if age_of_girl >= 18 and age_of_girl < 22 and height > 170 and weight < 100 and is_pretty == True:
    print('表白...')
else:
    print('阿姨好')

Case 4:

If: score> = 90, then: Excellent

If the score> = 80 and <90, then: good

If the score> = 70 and <80, then: general

Other conditions: poor

score=input('>>: ')
score=int(score)

if score >= 90:
    print('优秀')
elif score >= 80:
    print('良好')
elif score >= 70:
    print('普通')
else:
    print('很差')

Case 5: if Nesting

#在表白的基础上继续:
#如果表白成功,那么:在一起
#否则:打印。。。

age_of_girl=18
height=171
weight=99
is_pretty=True
success=False

if age_of_girl >= 18 and age_of_girl < 22 and height > 170 and weight < 100 and is_pretty == True:
    if success:
        print('表白成功,在一起')
    else:
        print('什么爱情不爱情的,爱nmlgb的爱情,爱nmlg啊...')
else:
    print('阿姨好')

Illustration: spoof 23

Spoof 23

Exercise 1: Log function

name=input('请输入用户名字:').strip()
password=input('请输入密码:').strip()
if name == 'tony' and password == '123':
    print('tony login success')
else:
    print('用户名或密码错误')

Exercise 2:

#!/usr/bin/env python
#根据用户输入内容打印其权限

'''
egon --> 超级管理员
tom  --> 普通管理员
jack,rain --> 业务主管
其他 --> 普通用户
'''
name=input('请输入用户名字:')

if name == 'egon':
    print('超级管理员')
elif name == 'tom':
    print('普通管理员')
elif name == 'jack' or name == 'rain':
    print('业务主管')
else:
    print('普通用户')

Three-cycle structure

3.1 What is a circular structure

Repeat the loop structure is a piece of code blocks

3.2 Why cycle structure

04-5 python syntax of the entry process control

Humans sometimes need to repeat something

So the program must have the appropriate mechanisms to control people's computers have the ability to do things this cycle

3.3 How to use the loop structure

3.3.1 while loop syntax

Illustration: spoof 21
04-5 python syntax of the entry process control

There python while the loop for two kinds of mechanisms, which is called a conditional loop while loop, syntax

while 条件:  
    代码1
    代码2
    代码3
    ......
# while的运行步骤:
# 步骤1:如果条件为真,那么依次执行:代码1、代码2、代码3、......
# 步骤2:执行完毕后再次判断条件,如果条件为True则再次执行:代码1、代码2、代码3、......,如果条件为False,则循环终止

Illustration: while loop

while loop

3.3.2 while loop Applications

Illustration: spoof 19
04-5 python syntax of the entry process control

Case I: basic use of the while loop

User authentication program
04-5 python syntax of the entry process control

#用户认证程序的基本逻辑就是接收用户输入的用户名密码然后与程序中存放的用户名密码进行判断,判断成功则登陆成功,判断失败则输出账号或密码错误
username = "jason"
password = "123"

inp_name =  input("请输入用户名:")
inp_pwd =  input("请输入密码:")
if inp_name == username and inp_pwd == password:
    print("登陆成功")
else:
    print("输入的用户名或密码错误!")
#通常认证失败的情况下,会要求用户重新输入用户名和密码进行验证,如果我们想给用户三次试错机会,本质就是将上述代码重复运行三遍,你总不会想着把代码复制3次吧。。。。
username = "jason"
password = "123"

# 第一次验证
inp_name =  input("请输入用户名:")
inp_pwd =  input("请输入密码:")
if inp_name == username and inp_pwd == password:
    print("登陆成功")
else:
    print("输入的用户名或密码错误!")

# 第二次验证
inp_name =  input("请输入用户名:")
inp_pwd =  input("请输入密码:")
if inp_name == username and inp_pwd == password:
    print("登陆成功")
else:
    print("输入的用户名或密码错误!")

# 第三次验证
inp_name =  input("请输入用户名:")
inp_pwd =  input("请输入密码:")
if inp_name == username and inp_pwd == password:
    print("登陆成功")
else:
    print("输入的用户名或密码错误!")

#即使是小白的你,也觉得的太low了是不是,以后要修改功能还得修改3次,因此记住,写重复的代码是程序员最不耻的行为。
#那么如何做到不用写重复代码又能让程序重复一段代码多次呢? 循环语句就派上用场啦(使用while循环实现)

username = "jason"
password = "123"
# 记录错误验证的次数
count = 0
while count < 3:
    inp_name = input("请输入用户名:")
    inp_pwd = input("请输入密码:")
    if inp_name == username and inp_pwd == password:
        print("登陆成功")
    else:
        print("输入的用户名或密码错误!")
        count += 1

Case II: while + break of use

After using a while loop, the code does more streamlined, but the problem is after the user enters the correct username and password can not be the end of the cycle, how does it off the end of a cycle? That's where a break!

username = "jason"
password = "123"
# 记录错误验证的次数
count = 0
while count < 3:
    inp_name = input("请输入用户名:")
    inp_pwd = input("请输入密码:")
    if inp_name == username and inp_pwd == password:
        print("登陆成功")
        break # 用于结束本层循环
    else:
        print("输入的用户名或密码错误!")
        count += 1

Case III: while nested loop + break

If the while loop nested many layers, each layer in order to exit the loop you need to have a break in each layer cycle

username = "jason"
password = "123"
count = 0
while count < 3:  # 第一层循环
    inp_name = input("请输入用户名:")
    inp_pwd = input("请输入密码:")
    if inp_name == username and inp_pwd == password:
        print("登陆成功")
        while True:  # 第二层循环
            cmd = input('>>: ')
            if cmd == 'quit':
                break  # 用于结束本层循环,即第二层循环
            print('run <%s>' % cmd)
        break  # 用于结束本层循环,即第一层循环
    else:
        print("输入的用户名或密码错误!")
        count += 1

Case Four: while the use of nested loop + tag

For a while loop nested multi-layered, if our purpose is clear is to withdraw from circulation all layers directly on a layer, in fact, there is a trick, let all the while loop condition to have a single variable, the variable's initial value is True, once the value of a variable to the layer of the False, then the end of the cycle all layers

username = "jason"
password = "123"
count = 0

tag = True
while tag: 
    inp_name = input("请输入用户名:")
    inp_pwd = input("请输入密码:")
    if inp_name == username and inp_pwd == password:
        print("登陆成功")
        while tag:  
            cmd = input('>>: ')
            if cmd == 'quit':
                tag = False  # tag变为False, 所有while循环的条件都变为False 
                break
            print('run <%s>' % cmd)
        break  # 用于结束本层循环,即第一层循环
    else:
        print("输入的用户名或密码错误!")
        count += 1

Case 5: while + continue to use

Representative break the end of the loop layer, and then continue to the end of this cycle, the next cycle directly into

# 打印1到10之间,除7以外的所有数字
number=11
while number>1:
    number -= 1
    if number==7:
        continue # 结束掉本次循环,即本次循环continue之后的代码都不会运行了,而是直接进入下一次循环
    print(number)

Case 5: while + else use

In the back of the while loop, we can with the else statement, while loop when done properly and there should be break stay of execution, they would perform behind the else statement, else we can use to verify whether the end of the normal cycle

count = 0
while count <= 5 :
    count += 1
    print("Loop",count)
else:
    print("循环正常执行完啦")
print("-----out of while loop ------")
输出
Loop 1
Loop 2
Loop 3
Loop 4
Loop 5
Loop 6
循环正常执行完啦   #没有被break打断,所以执行了该行代码
-----out of while loop ------

If the implementation process is break, will not be executed else statements

count = 0
while count <= 5 :
    count += 1
    if count == 3:
        break
    print("Loop",count)
else:
    print("循环正常执行完啦")
print("-----out of while loop ------")
输出
Loop 1
Loop 2
-----out of while loop ------ #由于循环被break打断了,所以不执行else后的输出语句

Illustration: spoof 23
04-5 python syntax of the entry process control

Exercise 1:

Looking number between 1 and a maximum of 1007 fold (98 result)

number=100
while number>0:
    if number%7==0:
        print(number)
        break
    number-=1

Exercise 2:

age=18
count=0
while count<3:
    count+=1
    guess = int(input(">>:"))
    if guess > age :
        print("猜的太大了,往小里试试...")
    elif guess < age :
        print("猜的太小了,往大里试试...")
    else:
        print("恭喜你,猜对了...")

3.3.3 for loop syntax

Illustration: spoof 22

04-5 python syntax of the entry process control

The second implementation cycle structure is the for loop, a for loop can do while loop can be implemented, because the reason for loop is used when the cycle value (ie traversal value) for loop while loop is more than concise,

The syntax for loop

for 变量名 in 可迭代对象: # 此时只需知道可迭代对象可以是字符串\列表\字典,我们之后会专门讲解可迭代对象
    代码一
    代码二
    ...

#例1
for item in ['a','b','c']:
    print(item)
# 运行结果
a
b
c

# 参照例1来介绍for循环的运行步骤
# 步骤1:从列表['a','b','c']中读出第一个值赋值给item(item=‘a’),然后执行循环体代码
# 步骤2:从列表['a','b','c']中读出第二个值赋值给item(item=‘b’),然后执行循环体代码
# 步骤3: 重复以上过程直到列表中的值读尽

for loop

3.3.4 for cycling Applications

Illustration: spoof 19
04-5 python syntax of the entry process control

Case I: Digital Printing 0-5

# 简单版:for循环的实现方式
for count in range(6):  # range(6)会产生从0-5这6个数
    print(count)

# 复杂版:while循环的实现方式
count = 0
while count < 6:
    print(count)
    count += 1

Case II: traversing dictionary

# 简单版:for循环的实现方式
for k in {'name':'jason','age':18,'gender':'male'}:  # for 循环默认取的是字典的key赋值给变量名k
    print(k)

# 复杂版:while循环确实可以遍历字典,后续将会迭代器部分详细介绍

Case III: for nested loop

#请用for循环嵌套的方式打印如下图形:
*****
*****
*****

for i in range(3):
    for j in range(5):
        print("*",end='')
    print()  # print()表示换行

Note: break and continue can also be used for recycling, use the same syntax while loop

Illustration: spoof 23
04-5 python syntax of the entry process control

Exercise 1:

Print multiplication table

for i in range(1,10):
    for j in range(1,i+1):
        print('%s*%s=%s' %(i,j,i*j),end=' ')
    print()

Exercise Two:

Print Pyramid
04-5 python syntax of the entry process control

# 分析
'''
#max_level=5
     *        # current_level=1,空格数=4,*号数=1
    ***       # current_level=2,空格数=3,*号数=3
   *****      # current_level=3,空格数=2,*号数=5
  *******     # current_level=4,空格数=1,*号数=7
 *********    # current_level=5,空格数=0,*号数=9

# 数学表达式
空格数=max_level-current_level
*号数=2*current_level-1
'''
# 实现:
max_level=5
for current_level in range(1,max_level+1):
    for i in range(max_level-current_level):
        print(' ',end='') #在一行中连续打印多个空格
    for j in range(2*current_level-1):
        print('*',end='') #在一行中连续打印多个空格
    print()

Guess you like

Origin blog.51cto.com/egon09/2461047