Skip to content

Tutorial 5

zwj2 edited this page Nov 18, 2022 · 4 revisions

Branches and loops

Branches

Branch structure design, a structure that is very important to us in programming. This structure can determine the next step in the execution process by assuming that certain specific conditions are satisfied. Common branching structures include single-branch, double-branch and multi-branch structures.

Single-branch

if

The if function is used to determine if the function is satisfied, and to execute it if it is satisfied, otherwise it is not executed. It is important to note that the executed statement needs to be indented relative to the conditional statement

>>> n=2
>>> if n > 0:
......print("n is a positive number")
...
n is a positive number

double-branch

if-else

This function divides the situation into two categories, executes the statement below if if it matches, otherwise executes the statement below else, and just like single-branch, you need to notice indentation.

>>> n=-5
>>> if n > 0:
......print("n is a positive number")
....else:
......print("n is a negative number")
...
n is a positive number

multi-branch

if-elif-else

The multi-branch structure is an extension of the two-branch structure; interestingly, you can have many elif branches, which will always look for a branch that satisfies the condition and jump out of the whole structure once found.

>>> score=70
>>> if score > 80:
......print("very good")
....elif 60 < score < 80:
......print("good")
....else:
......print("bad")
good

Loops

Clone this wiki locally