Alibaba Cloud Python Training Camp (day2)


Introduction

Today, I learned the two sections of conditional statements and loop statements. These two sections have been exposed to other languages ​​before learning, and they are all must be mastered. I will briefly talk about the specific usage in python.


One, conditional statement

1. if statement

if a:
b
The b code block of the if statement is executed only when the result of the conditional expression a is true, otherwise it will continue to execute the statement following the code block.

code show as below:

a=1
if a=1:
print("哈哈")
#哈哈

2. if-else statement

Python provides the else used with if, if the result of the conditional expression of the if statement is false, the program will execute the code after the else statement

Tips:
if statements support nesting, that is, if one if statement is embedded in another if statement to form a different level of selection structure.


3. if-elif-else statement

The elif statement is the else if, used to check whether multiple expressions are true, and execute the code in a specific code block when it is true.

The demo code is as follows:

temp = input('请输入成绩:')
source = int(temp)
if 100 >= source >= 90:
    print('A')
elif 90 > source >= 80:
    print('B')
elif 80 > source >= 60:
    print('C')
elif 60 > source >= 0:
    print('D')
else:
    print('输入错误!')

#请输入成绩:82
#B

4. assert keywords

The keyword assert is called "assertion". When the condition behind this keyword is False, the program automatically crashes and throws an AssertionError exception.

The demo code is as follows:

my_list = ['lsgogroup']
my_list.pop(0)#pop()函数随机移出列表中的一个元素,pop(0)直接把lspgorroup删除了
assert len(my_list) > 0
# AssertionError


Two, loop statement

1. while loop

The most basic form of the while statement includes a boolean expression at the top, and one or more indented statements belonging to the while code block.

while 布尔表达式:
    代码块

The code block of the while loop will continue to loop until the value of the Boolean expression is Boolean false.

The demo code is as follows:

string = 'abc'
while string:
    print(string)
    string = string[1:]#string[1:]获取从1开始后面的字符(默认首位是0)
#abc
#ab
#c

2. while-else loop

When the while loop is executed normally, the else output is executed. If the statement that jumps out of the loop is executed in the while loop, such as break, the content of the else code block will not be executed.

The demo code is as follows:

count = 0
while count < 5:
     print("%d is  less than 5" % count)
     count = 6
     break
else
     print("%d is not less than 5" % count)
# 0 is  less than 5

3. for loop

The for loop is an iterative loop, which is equivalent to a general sequence iterator in Python. It can traverse any ordered sequence, such as str, list, tuple, etc., as well as any iterable object, such as dict.

for 迭代变量 in 可迭代对象:
    代码块

In each loop, the iteration variable is set to the current element of the iterable object and provided to the code block.

The demo code is as follows:

a='ILOVEWJ'
for i in a:
    print(i,end='')#不换行输出
#ILOVEWJ

Insert other content (python dictionary related knowledge):

dic = {
    
    'a': 1, 'b': 2, 'c': 3, 'd': 4}
#dic为Python字典的定义
#dic.keys()函数以列表返回一个字典所有的键
#dic.values()函数以列表返回一个字典所有的键对应的值
#dic.item()函数以列表返回一个字典所有的元组数组(键和值)

4. for-else loop

When the for loop is executed normally, the else output is executed. If the statement that jumps out of the loop is executed in the for loop, such as break, the content of the else code block will not be executed, which is the same as the while-else statement. (No examples Up)


5. range() function

range([start,] stop[, step=1])

(1). This BIF (Built-in functions) has three parameters, two of which are enclosed in square brackets indicate that these two parameters are optional.
(2). step=1 means that the default value of the third parameter is 1.
(3). Range The function of this BIF is to generate a sequence of numbers starting with the value of the start parameter and ending with the value of the stop parameter. The sequence contains the value of start but not the value of stop.

The demo code is as follows:

for i in range(2, 9):  # 不包含9
    print(i,end='')
#2345678

for i in range(2, 9, 2):
    print(i,end='')
#2468

6. enumerate() function

enumerate(sequence, [start=0])

(1). sequence: a sequence, iterator or other object that supports iteration.
(2). start: the starting position of the subscript.
(3). Return enumerate (enumeration) object

The demo code is as follows:

seasons = ['Spring', 'Summer', 'Fall', 'Winter']
lst = list(enumerate(seasons))
print(lst)
lst = list(enumerate(seasons, start=1))  # 下标从 1 开始
print(lst)

# [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
# [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

Combination of enumerate() and for loop:

    for i, a in enumerate(A)
        do something with a 

Using enumerate(A) not only returns the element in A, but also gives the element an index value (starting from 0 by default). In addition, use enumerate(A, j) to determine the starting value of the index j.


7. Break statement and continue statement

The break statement can jump out of the loop of the current layer.

continue terminates the current cycle and starts the next cycle.

8. The pass statement

The pass statement means "do nothing". If you don't write any statement where there is a statement, the interpreter will prompt an error, and the pass statement is used to solve these problems.

The demo code is as follows:

def a_func():
    pass
#用pass不会提示出错

Pass is an empty statement, does not do any operation, only plays the role of a placeholder, its role is to maintain the integrity of the program structure. Although the pass statement does nothing, if you are not sure what kind of code to put in a location for the time being, you can place a pass statement first to make the code run normally.

Guess you like

Origin blog.csdn.net/qq_44250569/article/details/108734951