# Python sequence structure, selection structure, loop structure (super detailed)

Python sequence structure (end)

In 1996, computer scientists proved that any simple or complex algorithm can be composed of three basic structures: sequential structure, selection structure, and loop structure.

```# sequential structure
print("first statement")
print("second statement")
print("third statement")
# select structure
if 1 < 2:
print("first statement")
else:
print("second statement")
# loop structure
# syntax of for loop
for custom variable in iterable object:
pass
# Syntax of while loop
while Analyzing conditions:
pass```

Sequential structure: The code is executed step by step from top to next.

```print("first statement")
print("second statement")
print("third statement")
# first statement
# second statement
# third statement```

Python selection structure (end)

In 1996, computer scientists proved that any simple or complex algorithm can be composed of three basic structures: sequential structure, selection structure, and loop structure.

```# sequential structure
print("first statement")
print("second statement")
print("third statement")
# select structure
if 1 < 2:
print("first statement")
else:
print("second statement")
# loop structure
# syntax of for loop
for custom variable in iterable object:
pass
# Syntax of while loop
while Analyzing conditions:
pass```

Selection structure: Selectively execute a certain piece of code according to whether the judgment condition is true or not.

```if 1 < 2:
print("first statement")
else:
print("second statement")
# first statement```

The selection structure is divided into: single-branch structure, double-branch structure, multi-branch structure.

```# single branch structure         # double branch structure          # multi-branch structure
a = b = 100          a = b = 100           a = b = 100
if a < b:            if a < b:             if a < b:
pass                 pass                  pass
else:                 elif a > b:
pass                   pass
else:
pass```

The if keyword is used for the single-branch structure, the if...else keyword is used for the double-branch structure, and the if...elif...else keyword is used for the multi-branch structure.

```# single branch structure
a = 10
b = 20
if a < b:
print(f"{a}<{b}")
# double branch structure
a = 10
b = 20
if a < b:
print(f"{a}<{b}")
else:
print(f"{a}>{b}")
# multi-branch structure
a = 10
b = 20
if a < b:
print(f"{a}<{b}")
elif a > b:
print(f"{a}>{b}")
else:
print(f"{a}={b}")```

The if keyword is a conditional branch, if followed by the condition, if the condition is true, execute all the indented content under if, if the condition is not true, nothing will be executed.

```a = 10
b = 20
if a < b:
print(f"{a}<{b}")
# 10<20```

The if...else keyword is a conditional branch. The if is followed by the condition. If the condition is true, all the indented content under the if is executed. If the condition is not true, all the indented content under the else is executed.

```a = 10
b = 20
if a < b:
print(f"{a}<{b}")
else:
print(f"{a}>{b}")
# 10 < 20```

if...elif...else keyword is a conditional branch, if and elif are followed by conditions, if the condition is true, execute all the indented content under if or elif, if the condition is not true, then execute all the indented content under else content.

```a = 10
b = 20
if a < b:
print(f"{a}<{b}")
elif a > b:
print(f"{a}>{b}")
else:
print(f"{a}={b}")
# 10<20```

The first method uses all if, the first judgment is established and the letter A is printed, and then the second, third, fourth, and fifth judgments are performed until the conditions are not met before exiting the program. In the second and third methods, the first judgment Established, you can exit the program directly after printing the letter A.

```# the first method
if 100 >= x >= 90:
print("A")
if 90 > x >= 80:
print("B")
if 80 > x >= 70:
print("C")
if 70 > x >= 60:
print("D")
if 60 > x >= 0:
print("failed")
if 100 < x or x < 0:
print("Input error, please enter the correct score")
# The second method
if 100 >= x >= 90:
print("A")
elif 90 > x >= 80:
print("B")
elif 80 > x >= 70:
print("C")
elif 70 > x >= 60:
print("D")
elif 60 > x >= 0:
print("failed")
else:
print("Input error, please enter the correct score")
# third method
if 100 >= x >= 90:
print("A")
else:
if 90 > x >= 80:
print("B")
else:
if 80 > x >= 70:
print("C")
else:
if 70 > x >= 60:
print("D")
else:
if 60 > x >= 0:
print("failed")
else:
print("Input error, please enter the correct score")```

Assuming that each judgment consumes one CPU time, the first method consumes 400% more time than the second method.

```# the first method
if 100 >= x >= 90:
print("A")
if 90 > x >= 80:
print("B")
if 80 > x >= 70:
print("C")
if 70 > x >= 60:
print("D")
if 60 > x >= 0:
print("failed")
if 100 < x or x < 0:
print("Input error, please enter the correct score")
# The second method
if 100 >= x >= 90:
print("A")
elif 90 > x >= 80:
print("B")
elif 80 > x >= 70:
print("C")
elif 70 > x >= 60:
print("D")
elif 60 > x >= 0:
print("failed")
else:
print("Input error, please enter the correct score")
# third method
if 100 >= x >= 90:
print("A")
else:
if 90 > x >= 80:
print("B")
else:
if 80 > x >= 70:
print("C")
else:
if 70 > x >= 60:
print("D")
else:
if 60 > x >= 0:
print("failed")
else:
print("Input error, please enter the correct score")```

If a colon is entered in the correct position: the compiler will automatically indent the next line.

```if True:
pass
else:
pass```

Add a colon: after if, elif, else.

```a = 10
b = 20
if a < b:
print(f"{a}<{b}")
elif a > b:
print(f"{a}>{b}")
else:
print(f"{a}={b}")
# 10<20```

Python does not stipulate that if-elif must be followed by else.

```a = 10
b = 20
if a < b:
print(f"{a}<{b}")
elif a > b:
print(f"{a}>{b}")
# 10<20```

Conditional branches support nesting, and if, elif, and else can all be nested with each other.

```# single branch structure         # double branch structure          # multi-branch structure
a = b = 100          a = b = 100           a = b = 100
if a < b:            if a < b:             if a < b:
pass                 pass                  pass
else:                 elif a > b:
pass                   pass
else:
pass```

In the judgment condition, multiple conditions can be judged at the same time, and they can be connected with logical operators.

```a = input("please enter the letter A or a:")
if a == "A" or "a":
print("you successfully entered A or a")
else:
print("what you typed is not A or a")```

Although else wants to match the outer if, but according to the nearest matching principle of the C language, this else belongs to the inner if, which is the famous hanging else, and it is impossible to create a hanging else in Python.

```if a > b:
if a > c:
pass
else:
pass```

Python loop structure (end)

In 1996, computer scientists proved that any simple or complex algorithm can be composed of three basic structures: sequential structure, selection structure, and loop structure.

```# sequential structure
print("first statement")
print("second statement")
print("third statement")
# select structure
if 1 < 2:
print("first statement")
else:
print("second statement")
# loop structure
# syntax of for loop
for custom variable in iterable object:
pass
# Syntax of while loop
while Analyzing conditions:
pass```

Loop structure: Depending on whether the loop condition is true, a certain piece of code is repeatedly executed.

```# for loop syntax			        # Syntax of while loop
for custom variable in iterable object:		while Analyzing conditions:
pass    		    	               pass```

Python loops are divided into: for loop (traversal loop) and while loop (infinite loop).

```# for loop syntax			        # Syntax of while loop
for custom variable in iterable object:		while Analyzing conditions:
pass    		    	               pass```

Python's loops are divided into: infinite loop (dead loop), controllable loop (such as waiting for the user to input q to end), and limited number of loops (when the number of times is exhausted, the loop ends).

```# for loop syntax			        # Syntax of while loop
for custom variable in iterable object:		while Analyzing conditions:
pass    		    	               pass```

A for loop is called a value loop and a while loop is called a conditional loop.

```# for loop syntax			        # Syntax of while loop
for custom variable in iterable object:		while Analyzing conditions:
pass    		    	               pass```

In theory, the for loop can do everything the while loop can do.

```# for loop syntax			        # Syntax of while loop
for custom variable in iterable object:		while Analyzing conditions:
pass    		    	               pass```

for loops and while loops should be followed by a colon: .

```# for loop syntax			        # Syntax of while loop
for custom variable in iterable object:		while Analyzing conditions:
pass    		    	               pass```

The in in the for loop means to take values ​​sequentially from the sequence, also known as traversal.

```for i in range(3):
print(i)
# 0
# 1
# 2
for i in "Friday":
print(i)
# star
# Expect
# Fives```

The for loop is often used to iterate over iterable objects (strings, lists, tuples, dictionaries, sets, range() functions).

```# iterate over the string
a = "Friday"
for i in a:
print(i)
# traverse the list
a = [1, 2, 3]
for i in a:
print(i)
# iterate over tuples
a = (1, 2, 3)
for i in a:
print(i)
# iterate over the dictionary
a = {1: "Monday", 2: "Tuesday"}
for i in a.items():
print(i)
# iterate through the collection
a = {1, 2, 3}
for i in a:
print(i)
# range() function
for i in range(1, 4):
print(i)```

The for loop is often paired with the range() function.

```for i in range(3):
print(i)
# 0
# 1
# 2```

If you do not need to use the custom variable in the for loop, write the custom variable as an underscore _.

```for _ in range(3):
print("cycle three times")
# cycle three times
# cycle three times
# cycle three times```

You can nest loop constructs within select constructs, and you can nest select constructs within loop constructs.

```# nested loop constructs within select constructs
if conditional judgment:
for custom variable in iterable object:
pass
else:
while conditional judgment:
pass
# Nested selection constructs within loop constructs
for custom variable in iterable object:
if conditional judgment:
pass
else:
pass
while conditional judgment:
if conditional judgment:
pass
else:
pass```

for loops can be nested, the outer loop is executed once, and the inner loop is executed once from beginning to end.

```for x in range(4):                  # List
for y in range(4):              # Row
print("*", end=" ")
print()                         # new line
# * * * *
# * * * *
# * * * *
# * * * *```

The outer loop is mainly used to control the number of rows of the loop, and the inner loop is mainly used to control the number of columns of the loop.

```for x in range(4):                  # List
for y in range(4):              # Row
print("*", end=" ")
print()                         # new line
# * * * *
# * * * *
# * * * *
# * * * *```

When looping a sequence, you cannot delete elements in the looping sequence. You can create a new sequence, and loop through the new sequence to delete elements in the original sequence (both tuples and strings are immutable sequences).

```a = [1, 1.1, "Friday", [1, 2], (1, 2)]
b = a.copy()        # generate a new sequence
for i in b:         # loop new sequence
a.remove(i)     # remove elements from the original sequence
print(a)
# []```

Use a while loop to loop when the condition is met, and exit the loop when the condition is not met.

```while True:
print("Infinite loop")```

Three-step loop method: initialize variables, conditional judgment, and change variables (the while loop must meet these three conditions to end the loop, otherwise the loop will execute forever).

```x = 1                       # Initialize variables
y = 0
while x <= 100:             # conditional judgment
y += x                  # loop body
x += 1                  # change variable
print(y)                    # 5050```

The initialized variable and the conditional judgment variable are the same as the changed variable.

```x = 1                       # Initialize variables
y = 0
while x <= 100:             # conditional judgment
y += x                  # loop body
x += 1                  # change variable
print(y)                    # 5050```

Loops can be nested within a while loop, the outer loop is executed once, and the inner loop is executed once from beginning to end.

```a = 1
while a <= 4:
b = 1
while b <= 4:
print("*", end=" ")
b += 1
print()
a += 1
# * * * *
# * * * *
# * * * *
# * * * *```

The outer loop is mainly used to control the number of rows of the loop, and the inner loop is mainly used to control the number of columns of the loop.

```a = 1
while a <= 4:
b = 1
while b <= 4:
print("*", end=" ")
b += 1
print()
a += 1
# * * * *
# * * * *
# * * * *
# * * * *```

The else keyword can be used in conjunction with the for loop and the while loop. If the break keyword and the continum keyword are not encountered in the loop, the else keyword will be executed, and if it is encountered, the else keyword will not be executed.

```# Use the for loop with the else keyword
for i in range(6):
pass
else:
pass
# Use while loop with else keyword
while True:
pass
else:
pass```

The infinite loop is to let the program execute forever, and it is realized by setting the judgment condition to True.

```while True:
pass```

The role of the break keyword is to terminate the current loop and jump out of the loop body.

```a = ["Monday", "Tuesday", "Wednesday"]
for i in a:
if i == "Tuesday":
break
print(i)
# Monday```

The role of the continue keyword is to terminate the current cycle and start the next cycle. The loop condition needs to be tested before starting the next cycle.

```a = ["Monday", "Tuesday", "Wednesday"]
for i in a:
if i == "Tuesday":
continue
print(i)
# Monday
# Wednesday```

The break keyword and continue keyword can only act on one level of loop.

```a = ["Monday", "Tuesday", "Wednesday"]
for i in a:
if i == "Tuesday":
break
print(i)
# Monday
a = ["Monday", "Tuesday", "Wednesday"]
for i in a:
if i == "Tuesday":
continue
print(i)
# Monday
# Wednesday```

Posted by nabeel21 on Sun, 08 Jan 2023 18:01:12 +0530