Branching structure
Application scenarios of branching structures
So far, we have written Python code that executes one statement at a time. We call this a sequential structure. However, the sequential structure alone cannot solve all the problems. For example, when we design a Game, the condition for finishing the first level of the Game is that the player gets 1000 points. Then, after finishing the Game, we need to decide whether to enter the second level or tell the player “Game Over” according to the player’s score. And only one of these two branches will be executed, which is the branch structure of the program. There are many more scenarios like this, you should be able to think of at least five of them in a minute, so give them a try.
The use of the if statement
In Python, you can use the if, elif, and else keywords to construct branching structures. Keywords are words that have a special meaning, like if and else are keywords that are used to build branches, and obviously you can’t use them as variable names (in fact, you can’t use them as other identifiers either). The following example demonstrates how to construct a branch structure.
User authentication Version: 0.1 Author: Luo Hao ""
username = input('Please enter user name:')
password = input('Please enter password:')
You can use the getPass function of the getPass module if you want to enter the password and there is no response from the terminal
# import getpass
# password = getpass.getpass(' Please enter password: ')
if username == 'admin' and password == '123456':
print('Authentication successful! ')
else:
print('Authentication failed! ')
Copy the code
The only thing to note is that unlike C/C++ and Java, Python does not use curly braces to construct code blocks. Instead, it uses indentation to set the code hierarchy. If multiple statements need to be executed under the if condition, just keep them with the same indentation. In other words, contiguous code that retains the same indentation belongs to the same code block, as if it were executed as a whole.
Of course, if you want to construct more branches, you can use if… Elif… The else… Structure, such as the piecewise function evaluation below.
If (x <= 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))
Copy the code
Of course, branches can be nested depending on the actual development needs. For example, if you need to rank your performance based on the number of treasures or items you get after finishing the game (like spotting two or three stars), then we need to construct a new branch structure inside the IF. In the same way, we can create new branches in elif and else, which we call nested branches, which means that the code above can also be written like this.
If (x <= 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))
Copy the code
Note: you can feel for yourself which of these two writing methods is better. In Python, Flat is better than nested. The reason for this statement is that the number of nesting levels of nested structures will seriously affect the readability of the code. If you can use Flat structures, do not use nesting. So the way I wrote it before is the better way to do it.
practice
Exercise 1: Interchange English and metric units
""" Inch "" metric centimetre"
value = float(input('Please enter length:'))
unit = input('Please enter unit:')
if unit == 'in' or unit == '"':
print('%f inches = %f cm ' % (value, value * 2.54))
elif unit == 'cm' or unit == '厘米':
print('%f cm = %f inches' % (value, value / 2.54))
else:
print('Please enter a valid unit')
Copy the code
Exercise 2: Roll the dice to decide what to do
Version: 0.1 Author: Luo Hao """
from random import randint
face = randint(1.6)
if face == 1:
result = 'Sing a song'
elif face == 2:
result = 'Do a dance'
elif face == 3:
result = 'Bark like a dog'
elif face == 4:
result = 'Do push-ups'
elif face == 5:
result = 'Say a tongue twister'
else:
result = 'Tell a bad joke'
print(result)
Copy the code
Note: The above code uses the randint function of the random module to generate random numbers in a specified range to simulate rolling dice.
Exercise 3:100-point grade system to grading system
""" > A 80分~89分 --> B 70分~79分 --> C 60分~69分 --> D 60分 --> E Version: 0.1
score = float(input('Please enter result:'))
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 rank is:, grade)
Copy the code
Exercise 4: Enter the length of three sides and calculate the perimeter and area if they make a triangle
""" Determine whether the input side length can form a triangle. If so, calculate the perimeter and area of the triangle.
import math
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 = math.sqrt(p * (p - a) * (p - b) * (p - c))
print('Area: %f' % (area))
else:
print(It doesn't make a triangle.)
Copy the code
Note: The above code uses the SQRT function of the Math module to calculate square roots. The formula for calculating the area of a triangle using side lengths is called Hellen’s formula.
Exercise 5: Personal income Tax Calculator.
""" Input monthly income and five Social insurances and one Housing Fund to calculate individual income tax
salary = float(input('Income this month:'))
insurance = float(input(Five Insurances and one Housing Fund:))
diff = salary - insurance - 3500
if diff <= 0:
rate = 0
deduction = 0
elif diff < 1500:
rate = 0.03
deduction = 0
elif diff < 4500:
rate = 0.1
deduction = 105
elif diff < 9000:
rate = 0.2
deduction = 555
elif diff < 35000:
rate = 0.25
deduction = 1005
elif diff < 55000:
rate = 0.3
deduction = 2755
elif diff < 80000:
rate = 0.35
deduction = 5505
else:
rate = 0.45
deduction = 13505
tax = abs(diff * rate - deduction)
print('Individual income tax: ¥.2F yuan' % tax)
print('Actual income: ¥%.2F yuan' % (diff + 3500 - tax))
Copy the code
Note: This code uses Python’s built-in abs() function to take the absolute value of -0.