Simple and easy to understand: branching and looping in Python

insert image description here

foreword

In Python programming, branch (Branch) and loop (Loop) are one of the key elements to master. They allow you to conditionally execute different blocks of code, as well as repeat specific tasks. This article delves into these key concepts, details their usage, provides examples, and offers best practice recommendations.

branch structure

The branch structure allows us to choose different execution paths according to different conditions, so that the program can take different actions according to the situation.

What is a branch?
Branching is a decision-making mechanism in programming that allows different blocks of code to be executed based on conditions. It's like playing a game where you need to make choices based on the situation.

if statement: single conditional judgment

ifStatements are used to determine whether a condition is true and execute a specific block of code if the condition is true.

Example:

x = 10
if x > 5:
    print("x大于5")

In this example, if xthe value of x is greater than 5, the program will output "x is greater than 5".

else statement: provides an alternative

elseStatements: Provide Alternatives

Sometimes, we need to execute another set of code when the condition is not met. At this time you can use the else statement.

x = 10
if x > 5:
    print("x大于5")
else:
	print("x小于5")

elif statement: multi-condition judgment

Sometimes, we need to check multiple conditions and choose different actions based on the conditions. At this time, you can use the elif (short for else if) statement.

Usage:
elif The statement is used to select a satisfied branch among multiple conditions.

Example:

x = 5
if x > 5:
    print("x大于5")
elif x == 5:
    print("x等于5")
else:
    print("x小于5")

When there are multiple conditions to be judged, Python will judge from top to bottom and execute the first code block that meets the conditions.

Nested branching structure: complex conditional logic

Usage:
The branch structure can be nested, that is, one branch is nested within another branch to handle complex conditional logic.

Example:

x = 10
if x > 5:
    if x < 15:
        print("x在5和15之间")
    else:
        print("x大于等于15")
else:
    print("x小于等于5")

In this example, we first check to see xif it is greater than 5, and if so, we then check to see xif it is less than 15.

loop structure

Looping constructs allow us to repeatedly perform the same task until a certain condition is met. It's like a robot performing the same task over and over in order to handle situations that require repetitive actions.

for loop: traverse the sequence

Usage:
for Loops are used to iterate over each element in a sequence (such as a list, string, tuple, etc.).

Example:

fruits = ["苹果", "香蕉", "橙子"]
for fruit in fruits:
    print(fruit)

forThe loop assigns each element in the sequence to the variable fruit and then executes the code block.

range() function and for loop

Usage:
The range() function is used to generate a series of consecutive numbers, usually in combination with a for loop.

Example:

for i in range(5):
    print(i)

range(5) will generate a sequence of numbers from 0 to 4, which in turn will be fed to the for loop.

while loop: conditional repetition

Usage:
A while loop repeatedly executes a block of code while a condition is met.

Example:

count = 0
while count < 5:
    print(count)
    count += 1

Attention should be paid to avoid infinite loops, that is, the condition is always true, causing the program to fail to end.

Loop control: break and continue

Sometimes, we need special control in the loop, such as ending the loop early or skipping the current loop iteration.

usage:

  1. breakstatement is used to terminate the loop immediately.

    Example:

    numbers = [1, 2, 3, 4, 5]
    for num in numbers:
    	if num == 3:
        	break
    	print(num)
    
  2. continueThe statement is used to skip the rest of the current loop and continue to the next loop.
    Example:

    numbers = [1, 2, 3, 4, 5]
    for num in numbers:
        if num == 3:
            continue
        print(num)
    

Comprehensive Application of Branch and Loop

Example 1: Judging prime numbers

Example:

num = int(input("请输入一个数字:"))
if num > 1:
    for i in range(2, num):
        if num % i == 0:
            print(num, "不是素数")
            break
    else:
        print(num, "是素数")
else:
    print(num, "不是素数")

In this example, we use a loop to determine whether the input number is a prime number. A prime number is a positive integer divisible only by 1 and itself.

Print the ninety-nine multiplication table

Example:

for i in range(1, 10):
    for j in range(1, i + 1):
        print(f"{
      
      i} * {
      
      j} = {
      
      i * j}", end="\t")
    print() # 换行

This example uses nested for loops to print the nine-nine multiplication table. The inner loop is responsible for the output of each line, and the outer loop is responsible for the number of lines.

Best Practices for Branching and Looping

  • Best Practices for Branching and Looping
  • Avoid excessive nesting and keep the code concise.
  • Use breakand reasonably continueto ensure that the logic is not broken.
  • Use functions to encapsulate complex branching and looping logic, improving code maintainability and modularity.

If you have any questions or need further explanation, please feel free to ask in the comments section. In the upcoming studies, we will delve into other important topics of Python programming.

Guess you like

Origin blog.csdn.net/qq_72935001/article/details/132646950