Object-oriented language (Python) - three loops, four derivations, three built-in functions

 


Life is bitter and short, and I learn Python

Three conditional statements, four derivations


——Lungcen 

 

Table of contents

mind Mapping

 

Conditional statements

 Three forms of if else branch statement

Determine whether the expression is true

if else requirements for indentation

Nested if statements

pass statement and its role

assert assertion function and usage

while loop statement

for loop and its usage in detail

Else usage in loop structure

Loop nesting and usage

Nested loops implement bubble sort

 Ways to forcibly leave the current loop body

break statement

continue statement

Derivative Detailed Explanation

list comprehension

 Ordinary for loop bad

with judgment statement 

double for loop

tuple comprehension

Using the tuple() function, you can directly convert the generator object into a tuple

Directly use the for loop to traverse the generator object to get each element

Use the __next__() method to traverse the generator object, and you can also get each element

dictionary comprehension

Swaps the keys and values ​​of each key-value pair in an existing dictionary

set comprehension

Python built-in functions

zip function and usage

reversed function and usage

sorted function and usage


 


mind Mapping


 

 


Conditional statements


The python language has the same order of execution as the C language and the Java language. For example, the first statement is executed first, then the second, third... until the last statement, which is called a sequential structure

Judge the conditions, and then execute different codes according to different results, which is called selection structure or branch structure

 Three forms of if else branch statement

if statement

if else statement

 if elif else statement

If, elif, else statements have a colon at the end:, don't forget

Determine whether the expression is true

The Boolean type (bool) has only two values, namely True and False. Python will treat True as "true" and False as "false".

For numbers, Python treats 0 and 0.0 as "false" and all other values ​​as "true".

For other types, when the object is empty or None, Python will treat them as "false" , otherwise as true.

Example: "" empty string

           [ ] empty list

           ( ) empty tuple

           { } empty dictionary

           None Null value These expressions are not valid and will be treated as "false"

if else requirements for indentation

Python uses indentation to mark code blocks. Code blocks must be indented, and those without indentation are not code blocks. In addition, the indentation of the same code block should be the same, and the indentation of different indentation does not belong to the same code block.

How much indentation is appropriate? According to the custom, it is generally recommended to indent the position of the Tab key or indent 4 spaces

Do not indent where you don't need to use code blocks, once indented, a code block will be generated

Nested if statements

if 表达式 1:
    if 表示式 2:
        代码块 1
    else:
        代码块 2
if 表达式 1:
    if 表示式 2:
        代码块 1
    else:
        代码块 2
else:
    if 表达式3:
        代码块3
    else:
        代码块4

pass statement and its role

In actual development, sometimes we will build up the overall logical structure of the program first, but we will not implement some details for the time being, but add some comments in these places, so that we can add code later

In Python, a more professional approach is provided, which is the empty statement pass. pass is a keyword in Python, used to make the interpreter skip here and do nothing

age = int( input("请输入你的年龄:") )

if age < 12 :
    print("婴幼儿")
elif 12 <= age < 18:
    print("青少年")
elif 18 <= age < 30:
    print("成年人")
elif 30 <= age < 50:
    pass
else:
    print("老年人")

assert assertion function and usage

The assert statement, also known as the assert statement, can be regarded as a function-reduced version of the if statement , which is used to judge the value of an expression. If the value is true, the program can continue to execute; otherwise, the Python interpreter will report AssertionError error

# 输入数学成绩,判断成绩是否合法
mathMark = float(input("请输入数学成绩:"))
# 断言数学考试分数是否位于正常范围内
assert 0 <= mathMark <= 100
# 只有当 mathMark 位于 [0,100]范围内,程序才会继续执行
print("数学成绩为:", mathMark)

Obviously assert will crash the program, why use it?

This is because, instead of letting the program crash later, it is better to let the program crash directly when the error condition occurs, which is helpful for us to debug the program and improve the robustness of the program.

Therefore, assert statements are often used to check that user input is in compliance, and are often used as an aid in the initial testing and debugging of programs.

while loop statement

The specific flow of while statement execution is as follows:

First judge the value of the conditional expression, and when the value is true (True), execute the statement in the code block,

When the execution is complete, go back and re-determine whether the value of the conditional expression is true,

If still true, continue to re-execute the code block...and so on,

The loop is terminated until the conditional expression evaluates to False.

When using a while loop, be sure to ensure that the loop condition becomes false, otherwise the loop will become an infinite loop. The so-called infinite loop refers to a loop structure that cannot end the loop

for loop and its usage in detail

1. For loop for numerical loop

# 实现从 1 到 100 的累加
sum = 0
# range() 函数,此函数是 Python 内置函数,用于生成一系列连续整数
for i in range(101):
    sum += i
print(sum)

2. For loop traverses lists and tuples

# 定义列表
lt = ["Hello", "Java", "Python", "C", "C++", [12, 23]]
# 使用for循环遍历列表
for ls in lt:
    print(ls, end=", ")

3. For loop to traverse the dictionary

# 定义字典
dt = {
'Java': '因互联网而火',
'Python': '因人工智能而火',
'PHP': 'web之王'
}
# 遍历字典keys
for key in dt.keys():
    print(key, end=" ")
print()
# 遍历字典values
for value in dt.values():
    print(value, end=" ")
print()
# 遍历字典items
for item in dt.items():
    print(item, end=" ")
print()
# 直接遍历字典
for d in dt:
    print(d, end=" ")

Else usage in loop structure

Whether it is a while loop or a for loop, it can be followed by an else code block. Its function is that when the loop condition is False and jumps out of the loop, the program will first execute the code in the else code block (but in fact, add or not else does not affect)

But if break is used to jump out of the current loop body, the else code block after the loop will not be executed.

Loop nesting and usage

When two (or even more) loop structures are nested with each other, the loop structure located in the outer layer is often referred to as the outer loop or outer loop for short, and the loop structure located in the inner layer is often referred to as the inner loop or inner loop.

For the code of the loop nested structure, the execution process of the Python interpreter is as follows:

1. When the outer loop condition is True, execute the loop body in the outer loop structure

2. The outer loop body contains the ordinary program and the inner loop. When the loop condition of the inner loop is True, the loop body in this loop will be executed until the inner loop condition is False, and the inner loop will be jumped out.

3. If the condition of the outer loop is still True at this time, return to step 2 and continue to execute the body of the outer loop until the loop condition of the outer loop is False

4. When the loop condition of the inner loop is False, and the loop condition of the outer loop is also False, the entire nested loop is considered to be executed

        The total number of nested loop executions = the number of executions of the outer loop * the number of executions of the inner loop

Nested loops implement bubble sort

The implementation idea of ​​the bubble sort algorithm follows the following steps:

1. Compare adjacent elements, and if the first is greater than the second, swap them .

2. From the first pair at the beginning to the last pair at the end, do the comparison described in step 1 for each pair of adjacent elements, and put the largest element behind. In this way, when the first pair at the beginning is executed to the last pair at the end, the last element in the entire sequence is the largest number.

3. Shorten the cycle, remove the last number (because the last number is already the largest), and then repeat the operation of step 2 to get the penultimate second largest number.

4. Continue to do the operation of step 3, shorten the cycle by one bit each time, and get the maximum number in this cycle. Until the number of cycles is shortened to 1, that is, there is no pair of numbers to be compared, and a sequence sorted from small to large is obtained at this time.

lt = [5, 8, 4, 1]
# 使用冒泡排序将列表进行排序
# 外层循环控制比较回合
for i in range(len(lt) - 1):
    # 内层循环控制每回合比较的次数
    for j in range(len(lt) - 1 - i):
        # 如果前一个元素大于后一个元素,则交换位置
        if lt[j] > lt[j+1]:
            lt[j], lt[j+1] = lt[j+1], lt[j]
print(lt)

 lt[j], lt[j+1] = lt[j+1], lt[j]

This can be regarded as an assignment statement

 Ways to forcibly leave the current loop body

break statement

1. The break statement can immediately terminate the execution of the current loop and jump out of the current loop structure. Whether it is a while loop or a for loop, as long as the break statement is executed, the currently executing loop body will be ended directly.

2. After break jumps out of the current loop body, the else code block after the loop will not be executed.

3. The break statement will only terminate the execution of the loop body, and will not affect all loop bodies

continue statement

It will only terminate the execution of the rest of the code in this loop, and continue execution directly from the next loop


Derivative Detailed Explanation


Comprehensions (also known as parsers) are a unique feature of Python . Data of list, tuple, dictionary and set types can be quickly generated by using comprehension, so comprehension can be subdivided into list comprehension, tuple comprehension, dictionary comprehension and set comprehension.

list comprehension

[expression for iteration variable in iterable object [if condition expression]]

[if conditional expression] is not required

List comprehension can use data types such as range intervals, tuples, lists, dictionaries, and sets to quickly generate a list that meets specified requirements

 Ordinary for loop bad

for i in range(10):
    print(i ** 2, end=" ")
print()

list1 = [i ** 2 for i in range(10)]
print(list1)

with judgment statement 

for i in range(10):
    if i % 2 == 0:
        print(i, end=" ")
print()

list1 = [i for i in range(10) if i % 2 == 0]
print(list1)

double for loop

d_list = []
for x in range(3):
    for y in range(4):
        d_list.append((x, y))
print(d_list)

list1 = [(x, y) for x in range(3) for y in range(4)]
print(list1)

tuple comprehension

(expression for iteration variable in iterable[if conditional expression] )

Tuple comprehension can use data types such as range intervals, tuples, lists, dictionaries, and sets to quickly generate a tuple that meets the specified requirements

# 利用元组推导式生成元组
dt = (x for x in range(1, 10))
print(dt)
# 元组推导式生成的结果并不是一个元组,而是一个生成器对象,这一点和列表推导式是不同的

The result generated by tuple comprehension is not a tuple, but a generator object, which is different from list comprehension 

Using the tuple() function, you can directly convert the generator object into a tuple

# 利用元组推导式生成元组
dt = (x for x in range(1, 10))
print(tuple(dt))

Directly use the for loop to traverse the generator object to get each element

# 利用元组推导式生成元组
dt = (x for x in range(1, 10))
for i in dt:
    print(i, end=" ")

Use the __next__() method to traverse the generator object, and you can also get each element

# 利用元组推导式生成元组
dt = (x for x in range(1, 10))
for i in range(9):
    print(dt.__next__(), end=" ")

Whether you use the for loop to traverse the generator object, or use the __next__() method to traverse the generator object, the original generator object will no longer exist after traversal , which is why the original generator object is converted after traversal but gets an empty tuple

dictionary comprehension

{expression for iteration variable in iterable[if conditional expression]}

In Python, using dictionary comprehension can quickly generate a dictionary that meets the requirements with the help of lists, tuples, dictionaries, sets, and range intervals

Swaps the keys and values ​​of each key-value pair in an existing dictionary

listDemo = {'Lungcen', 'www.baidu.com'}
# 将列表中各字符串值为键,各字符串的长度为值,组成键值对
newDict = {key: len(key) for key in listDemo}
print(newDict)

# 交换字典的k和v
dt = {v: k for k, v in newDict.items()}
print(dt)

set comprehension

In Python, using set comprehension can quickly generate sets that meet the requirements with the help of lists, tuples, dictionaries, sets, and range intervals

The format of the set derivation and the dictionary derivation are exactly the same, so given a similar derivation, how to judge which derivation it is? The simplest and direct way is to judge based on the expression. If the expression is in the form of a key-value pair (key: value), it proves that the derivation is a dictionary derivation; otherwise, it is a set derivation .


Python built-in functions


zip function and usage

The zip() function is one of Python's built-in functions, which can "compress" multiple sequences (lists, tuples, dictionaries, sets, strings, and lists of range() intervals) into a zip object. The so-called "compression" is actually to recombine the elements in the corresponding positions in these sequences to generate new tuples one by one.

When the zip() function "compresses" multiple sequences, it takes the 1st element, the 2nd element, ... the nth element in each sequence respectively, and forms a new tuple respectively. It should be noted that when the number of elements in multiple sequences is inconsistent, the shortest sequence will be used for compression.

reversed function and usage

reserved() is one of Python's built-in functions. Its function is that for a given sequence (including lists, tuples, strings, and range(n) intervals), this function can return an iterator of reversed sequences (used to traverse the sequence reverse sequence)

Using the reversed() function to perform reverse operations does not modify the order of elements in the original sequence

sorted function and usage

sorted() As one of the built-in functions of Python, its function is to sort sequences (lists, tuples, dictionaries, sets, and strings)

list = sorted(iterable, key=None, reverse=False)

 Among them, iterable represents the specified sequence, and the key parameter can customize the sorting rules;

The key parameter and reverse parameter are optional parameters, which can be used or ignored.

The reverse parameter specifies whether to sort in ascending (False, default) or descending (True) order.

The sorted() function returns a sorted list.

lt1 = [5, 3, 4, 2, 1]
print(sorted(lt1))  # 默认升序排序
print(sorted(lt1, reverse=True))  # 降序排序

tup = (5, 4, 3, 1, 2)
print(sorted(tup))  # 对元组进行排序
print(sorted(tup, reverse=True))  # 降序排序

dic = {4: 1, 5: 2, 3: 3, 2: 6, 1: 8}
print(sorted(dic.items()))  # 字典默认按照key进行排序
print(sorted(dic, reverse=True))  # 降序排序

st = {1, 5, 3, 2, 4}
print(sorted(st))  # 对集合进行排序
print(sorted(st, reverse=True))  # 降序排序

str1 = "51423"
print(sorted(str1))  # 对字符串进行排序
print(sorted(str1, reverse=True))  # 降序排序

 


Life is bitter and short, and I learn Python

Three conditional statements, four derivations


——Lungcen 

 

Guess you like

Origin blog.csdn.net/qq_64552181/article/details/129823232