03. branch structure

Branch structure

Scenarios

So far, we write Python code is a statement in the order of execution, this code structure commonly referred to as sequential structure. However, only the sequence structure does not solve all the problems, such as we design a game, the game first hurdle clearance condition is the player get 1000 points, then the game after the completion of the Council, we have to decide whether to enter the first player gets points according to two off, or tell the player "Game Over", where it will have two branches, but only one of these two branches will be executed. There are many similar scenes, we will call this structure "branch structure" or "choice architecture." Give us a minute, you should be able to think of at least five such examples, and quickly try.

Use the if statement

In Python, can be used to construct a branch structure if, elifand elsekeyword. The so-called keywords that have special meaning to the word, like if, and elseis constructed specifically for keywords branched structure, it is clear that you can not use it as a variable name (in fact, used for other identifiers is not allowed). 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('身份验证失败!')

The only explanation is and C / C ++, Java, etc. in different languages, Python does not use braces to construct a block of code but the use of indentation way to set up a hierarchy of code, if ifyou need to perform in the case of a number of conditions are met statement, as long as they have the same plurality of statements will be indented, in other words, if successive code while maintaining the same indentation then they belong to the same block, the equivalent of a whole is performed.

Of course, if you want to construct a more branches, may be used if…elif…else…the structure, for example the following piecewise 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 actual development of the branched structure it can be nested, for example, given a rating is determined also on whether your performance after the number you get clearance or treasures props (such as two or three lighting stars), then we need the ifinternal structure of a new branch structure, empathy elif, and elsecan also be re-configured to the new branch, which we call nested branched structure, i.e. the above code can be written in the following way.

"""
分段函数求值
		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))

Note: you can feel yourself both written in the end is which one is better. Council may have serious implications code in Python Zen Before we mentioned in so many words "Flat is better than nested." , The reason to promote the code "flat" because the nesting level of the nested structure after more of reading, so do not use nested when flattened structure can be used.

Exercise

Exercise 1: English units and metric units centimeters inches exchange.

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: percentile score is converted into hierarchical grades.

Requirements : If the entered score 90 points or more (including 90 minutes) the output A; 80 -90 minutes (90 minutes excluding) the output B; 70 min -80 minutes (excluding 80) outputs C; 60 minutes -70 points (70 points excluding) the output D; 60 minutes following output E.

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 length of three edges, if they can form a triangle on the perimeter and the area calculated.

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 for calculating the area of the triangle by using the above-side length is called Heron's formula .


I welcome the attention of the public number, reply keyword " Python ", there will be a gift both hands! ! ! I wish you a successful interview ! ! !

Published 95 original articles · won praise 0 · Views 3074

Guess you like

Origin blog.csdn.net/weixin_41818794/article/details/104243607