SoFunction
Updated on 2024-10-30

Learning python branching structure

Application Scenarios for Branch Structure

So far, we have written Python code that executes sequentially, one statement at a time, and this structure is called sequential. However, sequential structure alone cannot solve all problems. For example, if we design a game where the condition for passing the first level of the game is that the player gets 1,000 points, and then after completing the game, we have to decide whether to go to the second level or to tell the player to "Game Over" based on the number of points that the player gets, then we have two branches, and only one of them will be executed. There will be two branches, and only one of these two branches will be executed, which is the branching structure of the program. There are many similar scenarios, give you a minute, you should be able to think of at least 5 such examples, hurry up and try.

Use of if Statements

In Python, you can use the if, elif, and else keywords to construct branching structures. A keyword is a word with a special meaning, and if and else are keywords that are specifically used to construct branching structures, so obviously you can't use them as variable names (and, in fact, you can't use them as any other identifiers either). The following example shows how to construct a branching structure.

"""
User authentication

Version: 0.1
Author: Luo Hao
"""

username = input('Please enter user name: ')
password = input('Please enter the password: ')
# If you want the password to be entered without being displayed in the terminal, you can use the getpass function of the getpass module.
# import getpass
# password = ('Please enter a password: ')
if username == 'admin' and password == '123456':
  print('Authentication successful!')
else:
  print('Authentication failed!')

The only thing to note is that unlike C/C++, Java and other languages, Python does not use braces to construct code blocks but uses indentation to set up the hierarchy of code. If the if condition is valid and you need to execute more than one statement, you just need to keep multiple statements with the same indentation, in other words consecutive pieces of code can be executed as long as they have the same indentation, in other words they belong to the same block of code if they have the same indentation. belong to the same block of code, which is equivalent to an execution as a whole.

Of course to construct more branches, you can use if...elif...else... constructs, such as the segmented function evaluation below.

$$f(x)=\begin{cases} 3x-5&\text{(x>1)}\x+2&\text{(-1}\leq\text{x}\leq\text{1)}\5x+3&\text {(x<-1)}\end{cases}$$

"""
Segmented function to find the value

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

Version: 0.1
Author: Luo Hao
"""

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 the actual development, the branch structure can be nested, for example, to determine whether the pass after you get the number of treasures or props on your performance to give the level (such as lighting up two or three stars), then we need to construct a new branch structure within the if, the same reason that the elif and else can be constructed in the new branch, we call it a nested branch structure, that is, the above code can also be written as follows.

"""
Segmented function to find the value
		3x - 5	(x > 1)
f(x) =	x + 2	(-1 <= x <= 1)
		5x + 3	(x < -1)

Version: 0.1
Author: Luo Hao
"""

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 for yourself which of these two ways of writing is better. In the Zen of Python we mentioned before, there is a saying "Flat is better than nested." The reason for this idea is that the nested structure of the nesting level will seriously affect the readability of the code, if you can use the flat structure, do not go to use nested! The reason for this is that a nested structure with many levels of nesting can seriously affect the readability of the code, so if you can use a flat structure, don't use nested.

Exercise 1: Interchanging Imperial and Metric Units

"""
Interchanging imperial units of inches and metric units of centimeters

Version: 0.1
Author: Luo Hao
"""

value = float(input('Please enter the length: '))
unit = input('Please enter the unit: ')
if unit == 'in' or unit == 'inches':
  print('%finch (unit of length equal 2.54 cm.) = %fcentimetre' % (value, value * 2.54))
elif unit == 'cm' or unit == 'centimeters':
  print('%fcentimetre = %finch (unit of length equal 2.54 cm.)' % (value, value / 2.54))
else:
  print('Please enter valid units')

Exercise 2: Rolling the Dice to Decide What to Do

"""
Rolling 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 = 'Barking like a dog'
elif face == 4:
  result = 'Doing push-ups'
elif face == 5:
  result = 'Read the tongue twister'
else:
  result = 'Telling cold jokes'
print(result)

**Description:** The above code uses the randint function of the random module to generate a specified range of random numbers to simulate a dice roll.

Exercise 3: Conversion of percentage grades to a grading system

"""
Percentile grades to graded grades
90 points or more --> A
80~89 --> B
70~79 points --> C
60~69 points --> D
Below 60 --> E

Version: 0.1
Author: Luo Hao
"""

score = float(input('Please enter a 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 rank is:', grade)

Exercise 4: Calculate perimeter and area by entering the lengths of three sides if they form a triangle.

"""
Determine if the input side lengths can form a triangle
If so, calculate the perimeter and area of the triangle.

Version: 0.1
Author: Luo Hao
"""

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 = (p * (p - a) * (p - b) * (p - c))
  print('Area: %f' % (area))
else:
  print('Cannot form a triangle')

Exercise 5: Personal Income Tax Calculator.

"""
Entering monthly income and five insurance policies to calculate personal income tax

Version: 0.1
Author: Luo Hao
"""

salary = float(input('Income for the month:'))
insurance = float(input('Five insurance and one pension:'))
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$' % tax)
print('Actual revenue in hand: ¥%.2f$' % (diff + 3500 - tax))