当前位置:网站首页>Day3: branch structure
Day3: branch structure
2022-07-24 11:51:00 【Sumarua】
Branching structure
Application scenarios
so far , We wrote Python The code is executed one by one , This kind of code structure is usually called sequential structure . However, only sequential structure can not solve all problems , For example, we design a game , The first pass condition of the game is that the player obtains 1000 branch , So after finishing this game , We have to decide whether to enter the second level according to the score obtained by the player , Or tell the player “Game Over”, There will be two branches , And only one of these two branches will be executed . There are many similar scenes , We call this structure “ Branching structure ” or “ Selection structure ”. Give everyone a minute , You should be able to think of at least 5 More than one such example , Give it a try .
if Use of statements
stay Python in , To construct a branching structure, you can use if、elif and else keyword . So-called keyword Is a word with a special meaning , image if and else It's a key word used to construct a branching structure , Obviously you can't use it as a variable name ( in fact , You can't use it as any other identifier ). The following example demonstrates how to construct a branch structure .
"""
User authentication
"""
username = input(' Please enter a user name : ')
password = input(' please input password : ')
# User name is admin And the code is 123456 Then the authentication succeeds or the authentication fails
if username == 'admin' and password == '123456':
print(' Authentication succeeded !')
else:
print(' Authentication failed !')
It should be noted that and C/C++、Java Different languages ,Python Instead of using curly braces to construct code blocks, instead Indentation is used to represent the hierarchy of code , If if If the condition holds, multiple statements need to be executed , Just keep multiple statements with the same indentation . let me put it another way If continuous code keeps the same indentation, they belong to the same code block , It is equivalent to an executive whole . Indent You can use any number of spaces , but Usually use 4 A space , recommend Do not use tab keys perhaps Set your code editing tool to automatically change the tab key to 4 A space .
Of course, if you want to construct more branches , have access to if...elif...else... Structured or nested if...else... structure , The following code demonstrates how to use multi branch structure to realize piecewise function evaluation .

"""
Piecewise function evaluation
3x - 5 (x > 1)
f(x) = x + 2 (-1 <= x <= 1)
5x + 3 (x < -1)
"""
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 actual development needs , Branch structures can be nested , For example, after judging whether to pass the customs, you should give a level to your performance according to the number of treasures or props you get ( Like lighting up two or three stars ), Then we need to be in if A new branch structure is constructed inside of , Empathy elif and else We can also construct new branches in , We call it a nested branch structure , In other words, the above code can also be written as the following .
"""
Piecewise function evaluation
3x - 5 (x > 1)
f(x) = x + 2 (-1 <= x <= 1)
5x + 3 (x < -1)
"""
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))
explain : You can feel which of these two writing methods is better . As we mentioned earlier Python There is a saying in Zen “Flat is better than nested.”, The reason why code is advocated “ flat ” Because the nesting level of the nesting structure will seriously affect the readability of the code , So don't use nesting when you can use flat structures .
practice
practice 1: The English unit inch is interchangeable with the metric unit centimeter .
Refer to the answer :
"""
English units inches and metric units centimeters are interchangeable
"""
value = float(input(' Please enter the length : '))
unit = input(' Please enter the unit : ')
if unit == 'in' or unit == ' Inch ':
print('%f Inch = %f centimeter ' % (value, value * 2.54))
elif unit == 'cm' or unit == ' centimeter ':
print('%f centimeter = %f Inch ' % (value, value / 2.54))
else:
print(' Please enter a valid unit ')
practice 2: Conversion of a 100% grade to a graded grade .
requirement : If the score entered is in 90 More than ( contain 90 branch ) Output A;80 branch -90 branch ( Not included 90 branch ) Output B;70 branch -80 branch ( Not included 80 branch ) Output C;60 branch -70 branch ( Not included 70 branch ) Output D;60 The output is as follows E.
Refer to the answer :
"""
Conversion of a 100% grade to a graded grade
"""
score = float(input(' Please enter the grade : '))
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
elif score >= 60:
grade = 'D'
else:
grade = 'E'
print(' The corresponding level is :', grade)
practice 3: Enter three side lengths , If you can form a triangle, calculate the perimeter and area .
Refer to the answer :
"""
Judge whether the input side length can form a triangle , If so, calculate the perimeter and area of the triangle
"""
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(' Perimeter : %f' % (a + b + c))
p = (a + b + c) / 2
area = (p * (p - a) * (p - b) * (p - c)) ** 0.5
print(' area : %f' % (area))
else:
print(' Can't make a triangle ')
explain : The formula used above to calculate the area of a triangle by its side length is called Helen's formula .
Relevant code has been uploaded to https://download.csdn.net/download/weixin_43510203/86242452
边栏推荐
- DevOps及DevOps常用的工具介绍
- Database operation through shell script
- [deserialization vulnerability-02] principle test and magic method summary of PHP deserialization vulnerability
- The third day of hcip mGRE experiment
- JMeter runtime controller
- 字符串——344.反转字符串
- String - 541. Reverse string II
- Introduction to Devops and common Devops tools
- 1184. Distance between bus stops: simple simulation problem
- MySql的DDL和DML和DQL的基本语法
猜你喜欢

1184. Distance between bus stops: simple simulation problem

Linked list - 142. Ring linked list II

Hcip OSPF interface network type experiment day 4
什么是云原生,云原生技术为什么这么火?

HCIP MGRE实验 第三天
![[mathematical basis of Cyberspace Security Chapter 9] finite field](/img/2b/27ba1f3c6ec2ecff4538f9a63a79e8.jpg)
[mathematical basis of Cyberspace Security Chapter 9] finite field

Ctfshow ThinkPHP topic 1

一周精彩内容分享(第13期)

使用Prometheus+Grafana实时监控服务器性能

源码分析Sentry用户行为记录实现过程
随机推荐
L1-049 seat allocation of ladder race
生信周刊第37期
字符串——剑指 Offer 05. 替换空格
L2-011 玩转二叉树
Optimization method of "great mathematics for use" -- optimal design of Cascade Reservoir Irrigation
Sorting out the ideas of data processing received by TCP server, and the note of select: invalid argument error
Install JMeter
[mathematical basis of Cyberspace Security Chapter 9] finite field
JVM visualvm: multi hop fault handling tool
L1-059 敲笨钟
Linked list - 142. Ring linked list II
哈希——349. 两个数组的交集
Introduction to Devops and common Devops tools
Oracle 11.2.0.4 ASM single instance does not start automatically with system startup
Leetcode 112. path sum
[mathematical basis of Cyberspace Security Chapter 3] congruence
2 万字详解,吃透 ES!
Differences between JS map and foreach
Install MariaDB columnstore (version 10.3)
容错、熔断的使用与扩展