2.python control loop

1. Three control structures

  • Sequence structure : the code is executed in the order of the context, line by line

  • Choose a structure

    • if select structure-execute the code block if the condition is true, otherwise do nothing
    • if/else-alternative structure
    • if/elif/elif/else choose one more
  • Loop structure : repeatedly execute a block of code

    • for loop
    • while loop

Second, choose the structure

  • Simple if language
1. 基本形式
   if 条件表达式:
      语句/代码块
      
2. 例子
	x = 3
	y = 2
	if x > y :
		print("666")
  • if/else alternative structure
a = int(input('请输入:'))
b = int(input('请输入:'))  # ctrl + D 复制光标所在的行
if a > b:
    print("最大值为:", a)
else:
    print("最大值为:", b)
  • if / elif / elif / elif… else
msg = "您好,欢迎致电中国联通客户服务热线....."
print(msg)
number = int(input("请选择:"))

# 全部使用if判断  效率低
# if number == 1:
#     print("您选择了话费查询")
# if number == 2:
#     print("您选择了流量查询")
# if number == 3:
#     print("您选择了业务咨询")


if number == 1:
    print("您选择了话费查询")
elif number == 2:
    print("您选择了流量查询")
elif number == 3:
    print("您选择了业务咨询")
else:
    print("输入错误")

Three, statements and indentation

1. Statement

在代码中,能够表达某个意思、操作、逻辑的短代码,称之语句
print("abc")  # 一条语句   在python 一条语句结束时不需要加分号
# C语言   printf("abc");  分号是语句结束的标志
a = 3 
b = 5
s = a * b
print(s)
a = 3
b = 5
c = 8
# 有折行时 需要加转义字符 \
x = a + \  
    b + \
    c

2. Code block

if 3 > 2:
    print("哟,数学不错哦!!!")
    print("end!")

Use {} to determine the code block in C language:

if (3 > 2){
    
    
    printf("哟,数学不错哦!!!")
    printf("end!")
}

3. Indent

It is recommended to use the tab key for indentation

if 3 > 2:
    print("哟,数学不错哦!!!")
  print("end!")   # 错误的 

# IndentationError: unexpected indent 缩进错误

4. Pass statement

The pass statement is a point statement. If you don’t know how to implement the code in if, while, for, or functions, or you need to implement it later, you can add a pass statement first to prevent the code from reporting errors.

def f():
    pass 

Fourth, the loop structure

Loop: When a certain condition is met, a certain code block is repeatedly executed, and the executed code block is also called the loop body

  • for loop

Basic syntax:

for 变量名 in 序列/可迭代对象:
	循环体代码(可以有多行)
for i in 'helloworld':
    print(i)     # h    e    l    l .....
    
for i in [2,4,6,8,22]:
    print(i)      

Basic usage two:

for 变量名  in  range(start,end,[,step])  # step参数可选
	语句
for i in range(0,10):
    print(i)    # 0 1 2 3 4 5 6 7 8 9
  • Detailed usage of range() function in Python:
    • range(0,10) means an integer in the range of 0-9 is an interval with left closed and right open
    • range(10) means starting from 0 by default, to 10-1 (stop-1)
    • The default of the third parameter of range(0,10,2) is 1 step up stairs
    • range(10,1,-1) The descending stairs start from 10 and go to 2
# 0-100以内的所有的偶数
for i in range(0,101,2):
    print(i,end=" ")


# 0-100以内的所有的偶数 不使用步长
for i in range(100):
    if i%2 == 0:
        print(i)
  • Range() in Python3 returns an iterable object-it can be looped
  • Range() in Python2 returns a list range(1,5)-> [1,2,3,4]

counter:

counter = 1 # 计数器
for i in [2,4,6,8,22]:
    print('第'+str(counter)+'个值为'+str(i))
    counter += 1

C++ language:

for (int i=0;i<5;i++){
    //循环体代码
}
  • while loop

Basic form:

while 条件表达式(bool):   
	代码块
while 3 > 2:
    print("哈哈哈哈")
# 写一个死循环
while True:
    pass
while 1:
    pass 

# Python3中while 1和 while True是等价 

Chestnut: # Input an integer from the keyboard, output each digit in reverse order, and calculate the sum of the digits

12345 -> 54321 15


```python
number = int(input('请输入一个整数:'))
n = number
sum = 0
while n:
    left = n % 10
    sum += left
    print(left,end='')
    n = n // 10

print()
print(str(number)+"的各位数之和为:"+str(sum))

Five, break and continue

1. Break statement

counter = 1
while 1:
    if counter <= 100:
        print('哈哈')
        counter += 1
    else:
        break   # 终止循环-break所在循环

note:

  • If there are multiple loops, break will only jump out of the current layer
  • Break can only be used in a loop, usually when a certain condition is met.

Find the factorial of n

Enter a number from the keyboard and find the factorial of this number

number = int(input('请输入一个整数:'))
n = number
result = 1
while 1:
    result *= n
    n -= 1
    if n == 1:
        break
print(str(number) + '的阶乘为:'+str(result))

2、continue

continue is used inside the loop body, the function is to end (skip) this loop and continue to the next loop

for l in 'Python':
    if l == 'y':
        continue  # 遇到continue 结束本次循环 后面不再执行 继续下一次的循环
    print('当前字母为:', l)

Six, loop nesting

The inner loop goes fast, the inner loop completes once, and the outer loop adds 1

for i in range(0, 10):
    for j in range(0, 10):
        print(i, j, end=',')  
    print()
# 实现99乘法表
for i in range(1,10):
    for j in range(1,i+1):
        print(j,"*",i,"=",i*j,end=' ')
    print()

Seven, scope leaks

a = int(input('请输入:'))
b = int(input('请输入:'))
if a > b:
    max = a 
else:
    max = b
print(max)  

Please leave a message for infringement
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_54730385/article/details/113987182