Chapter 3: Branch Structure

Chapter 3: Branch Structure

See previous articles:
Chapter 1: Initial Python
Chapter 2: Language Elements
or go to the column "Python Tutorial" to view


Resource directory: Code (3)
Article resource download: (1-15 chapters)
Link: https://pan.baidu.com/s/1Mh1knjT4Wwt__7A9eqHmng?pwd=t2j3
Extraction code: t2j3

Application Scenario

So far, the Python code we have written is executed sequentially one by one. This code structure is usually called a sequential structure. However, the sequence structure alone cannot solve all problems. For example, if we design a game, the condition for clearing the first level of the game is that the player obtains 1000 points. In the second level, tell the player "Game Over", two branches will be generated here, and only one of these two branches will be executed. There are many similar scenarios, and we call this structure "branch structure" or "selection structure". Give everyone a minute, and you should be able to think of at least 5 such examples, so give it a try.

Use of if statement

In Python, you can use the if, elifand elsekeywords to construct a branch structure. The so-called keywords are words with special meanings, like ifand elseare keywords specially used to construct branch structures. Obviously, you cannot use it as a variable name (in fact, it is not allowed to be used as other identifiers). The following example demonstrates how to construct a branch structure.

"""
用户身份验证

Version: 0.1
Author: 骆昊
"""
username = input('请输入用户名: ')
password = input('请输入口令: ')
# 用户名是admin且密码是123456则身份验证成功否则身份验证失败
if username == 'admin' and password == '123456':
    print('身份验证成功!')
else:
    print('身份验证失败!')

It should be noted that unlike C/C++, Java and other languages, Python does not use curly braces to construct code blocks but uses indentation to represent the hierarchical structure of the code . If ifthe condition is true, multiple statements need to be executed , as long as you keep multiple statements with the same indentation. In other words, if consecutive codes maintain the same indentation, they belong to the same code block , which is equivalent to a whole of execution. Any number of spaces can be used for indentation , but 4 spaces are usually used . It is recommended that you do not use the tab key or set your code editing tool to automatically change the tab key to 4 spaces .

Of course, if you want to construct more branches, you can use if...elif...else...a structure or a nested if...else...structure. The following code demonstrates how to use a multi-branch structure to implement segmented function evaluation.

"""
分段函数求值

        3x - 5  (x > 1)
f(x) =  x + 2   (-1 <= x <= 1)
        5x + 3  (x < -1)

Version: 0.1
Author: 骆昊
"""

x = float(input('x = '))
if x > 1:
    y = 3 * x - 5
elif x >= -1:
    y = x + 2
else:
    y = 5 * x + 3
print('f(%.2f) = %.2f' % (x, y))

Of course, according to the needs of actual development, the branch structure can be nested. For example, after judging whether to pass the level, you will be given a level according to the number of treasures or props you have obtained (such as lighting up two or three stars). Then we need to ifconstruct a new branch structure inside, similarly, elifwe elsecan also construct a new branch in and, we call it a nested branch structure, that is to say, the above code can also be written as follows.

"""
分段函数求值
		3x - 5	(x > 1)
f(x) =	x + 2	(-1 <= x <= 1)
		5x + 3	(x < -1)

Version: 0.1
Author: 骆昊
"""

x = float(input('x = '))
if x > 1:
    y = 3 * x - 5
else:
    if x >= -1:
        y = x + 2
    else:
        y = 5 * x + 3
print('f(%.2f) = %.2f' % (x, y))

Explanation: You can feel for yourself which of these two writing methods is better. In the Zen of Python we mentioned earlier, there is such a sentence "Flat is better than nested." Readability, so don't use nesting when you can use a flat structure.

practise

Exercise 1: Exchange the imperial unit inches with the metric unit centimeters.

Reference answer:

"""
英制单位英寸和公制单位厘米互换

Version: 0.1
Author: 骆昊
"""
value = float(input('请输入长度: '))
unit = input('请输入单位: ')
if unit == 'in' or unit == '英寸':
    print('%f英寸 = %f厘米' % (value, value * 2.54))
elif unit == 'cm' or unit == '厘米':
    print('%f厘米 = %f英寸' % (value, value / 2.54))
else:
    print('请输入有效的单位')

Exercise 2: Convert percentile grades to grade grades.

Requirements : If the input score is above 90 points (including 90 points), output A; 80 points-90 points (excluding 90 points) output B; 70 points-80 points (excluding 80 points) output C; 60 points-70 points Points (excluding 70 points) output D; 60 points or less output E.

Reference answer:

"""
百分制成绩转换为等级制成绩

Version: 0.1
Author: 骆昊
"""
score = float(input('请输入成绩: '))
if score >= 90:
    grade = 'A'
elif score >= 80:
    grade = 'B'
elif score >= 70:
    grade = 'C'
elif score >= 60:
    grade = 'D'
else:
    grade = 'E'
print('对应的等级是:', grade)

Exercise 3: Enter the lengths of three sides, and calculate the perimeter and area if a triangle can be formed.

Reference answer:

"""
判断输入的边长能否构成三角形,如果能则计算出三角形的周长和面积

Version: 0.1
Author: 骆昊
"""
a = float(input('a = '))
b = float(input('b = '))
c = float(input('c = '))
if a + b > c and a + c > b and b + c > a:
    print('周长: %f' % (a + b + c))
    p = (a + b + c) / 2
    area = (p * (p - a) * (p - b) * (p - c)) ** 0.5
    print('面积: %f' % (area))
else:
    print('不能构成三角形')

Explanation: The formula used above to calculate the area of ​​a triangle by side length is called Heron's formula .

Guess you like

Origin blog.csdn.net/xyx2023/article/details/129628769