Python language learning day 4_Control structure: conditional statements and loops

I. Introduction

1. A brief introduction to the control structure

Control structures are statements in a programming language that control the flow of program execution. They are divided into two main categories:

  1. Conditional statements :
    • ifStatement: Execute a block of code based on conditions.
    • elifStatement: If the previous condition does not hold, try this condition.
    • elseStatement: This block of code is executed if all conditions are not met.
  2. loop statement :
    • forLoop: iterate through each element in the sequence.
    • whileLoops: Repeat a block of code as long as a condition is true.

2. The importance of control structures in programming

The importance of control structures in programming is that they enable a program to execute specific blocks of code based on different conditions or repeatedly. This enables programs to make decisions, perform repetitive tasks, and manage complex processes to implement a variety of functions and algorithms.

  1. Decision-making ability : Through conditional statements (such as if, elif, else), the program can execute different code paths according to different conditions, thereby realizing the decision-making function.
  2. Repeated execution : Loop statements (such as for, while) allow the program to repeatedly execute blocks of code, which is crucial for handling repetitive tasks, traversing data structures, and other scenarios.
  3. Process management : The control structure can effectively manage the execution process of the program, so that the program can be executed in a logical sequence, improving the readability and maintainability of the code.
  4. Algorithm implementation : The control structure is the basis for algorithm implementation. Algorithms such as sorting, search, and dynamic programming are inseparable from the support of conditional statements and loop statements.
  5. Flexibility and scalability : Rational use of control structures can make the program more flexible and scalable, able to adapt to different inputs and scenarios, and improve the versatility of the program.

In summary, control structures are a core component of programming languages, and mastering them is crucial to writing feature-rich and logically complex programs.

2. Conditional statements

1. Basic use of if statement

In Python, ifstatements are used to execute blocks of code based on conditions. The following is ifthe basic usage of statements:

  1. Single conditional ifstatement :

    if condition:
        # 如果条件为真,则执行这里的代码
        print("条件为真,执行此代码块。")
    
  2. Multiple conditional ifstatements :

    if condition1:
        # 如果条件1为真,则执行这里的代码
        print("条件1为真,执行此代码块。")
    elif condition2:
        # 如果条件1不为真,但条件2为真,则执行这里的代码
        print("条件1不为真,条件2为真,执行此代码块。")
    else:
        # 如果条件1和条件2都不为真,则执行这里的代码
        print("条件1和条件2都不为真,执行此代码块。")
    
  3. ifCode block in statement :

    • ifA colon ( ) after a statement :marks the beginning of a code block.
    • Code blocks should be indented (usually 4 spaces or 1 tab).
    • Correct indentation is key to control structures in Python.
  4. Precautions :

    • Conditional expressions should be surrounded by parentheses, especially in the case of multiple conditions.
    • Don't forget ifto add a colon after the statement.
    • Make sure your code blocks are indented correctly.
  5. Example :

    age = 20
    if age >= 18:
        print("您已成年。")
    else:
        print("您还未成年。")
    

In this example, if agethe variable is greater than or equal to 18, print out "You are an adult."; otherwise, print out "You are not yet a minor.". Remember, ifthe basic purpose of a statement is to decide whether to execute a specific block of code based on the result of a conditional evaluation.

2. Use of else clause

In Python, elseclauses are often ifused together with statements to provide ifalternative execution paths when a condition is not met. Here are elsethe basic uses of clauses:

  1. Clauses ifafter simpleelse statements :

    if condition:
        # 如果条件为真,则执行这里的代码
    else:
        # 如果条件不为真,则执行这里的代码
        print("条件不为真,执行此代码块。")
    
  2. elifClauses and elseclauses :

    if condition1:
        # 如果条件1为真,则执行这里的代码
    elif condition2:
        # 如果条件1不为真,但条件2为真,则执行这里的代码
    else:
        # 如果条件1和条件2都不为真,则执行这里的代码
        print("条件1和条件2都不为真,执行此代码块。")
    
  3. elseClause AND foror whileLoop :

    for item in collection:
        # 循环体代码
    else:
        # 当循环正常完成时执行,即循环体未被`break`语句打断时执行
        print("循环体已全部执行完毕。")
    

When using elseclauses, you need to pay attention to the following points:

  • elseClauses must ifbe used with and after the ifstatement.
  • elseCode blocks within clauses should have the same indentation level to keep the code structure clear.
  • Within elifa clause, each elifand the corresponding elsemust have the same indentation level.
  • In an foror whileloop, elsethe clause is executed at the normal end of the loop, that is, breakwhen the body of the loop is not interrupted by a statement. For example:
x = 10
if x > 0:
    print("x 是正数")
else:
    print("x 不是正数")

In this example, if xit is greater than 0, print "x is a positive number"; otherwise, print "x is not a positive number".

3. Use of elif clause

In Python, elifthe (short for else if) clause is used to ifprovide additional condition checks when the condition of the statement is not met. elifClauses are often used to implement multi-conditional branch logic. Here are elifthe basic uses of clauses:

  1. if-elif-elsestructure :

    if condition1:
        # 如果条件1为真,则执行这里的代码
    elif condition2:
        # 如果条件1不为真,但条件2为真,则执行这里的代码
    else:
        # 如果条件1和条件2都不为真,则执行这里的代码
        print("条件1和条件2都不为真,执行此代码块。")
    
  2. elifOrder of clauses :

    • elifClauses should be ordered from most likely to least likely.
    • This allows the program to find clauses that satisfy the condition faster elifand execute them.
  3. Precautions :

    • Each elifand the corresponding elsemust have the same indentation level.
    • If the first ifcondition is not met, Python will check the first elifcondition and execute the corresponding code block if it is met.
    • If all the ifAND elifconditions are not met, elsethe clause (if any) is executed.
  4. Example :

    grade = 'B'
    if grade == 'A':
        print("优秀!")
    elif grade == 'B':
        print("良好。")
    elif grade == 'C':
        print("及格。")
    else:
        print("加油,再努力!")
    

In this example, depending on gradethe value of the variable, the program prints different messages. If gradeit is 'A', print "Excellent!"; if it is 'B', print "Good."; if it is 'C', print "Pass."; if neither, print "Come on, try harder." ! ". elifClauses are a common way to implement complex conditional judgments. They make the code clearer and easier to understand.

4. Nested if statements

Nested ifstatements refer to using another statement ifinside a statement block . ifNested ifstatements allow you to execute different code paths based on multiple conditions. The following is ifthe basic usage of nested statements:

  1. Nested ifstatements :
    x = 10
    if x > 0:
        print("x 是正数")
        if x < 100:
            print("x 是一个小于100的正数")
    else:
        print("x 不是正数")
    

In this example, first check xif it is greater than 0. If it is, then further check xif it is less than 100. 2. Notes :

  • Make sure the inner ifstatements have the ifsame indentation level as the outer statements.
  • Each nested ifstatement must have an explicit condition to avoid infinite loops.
  1. Example :
    age = 21
    if age >= 18:
        print("您已成年。")
        if age >= 21:
            print("您已超过法定饮酒年龄。")
        else:
            print("您还未达到法定饮酒年龄。")
    else:
        print("您还未成年。")
    

In this example, first check agewhether it is greater than or equal to 18, and if so, then further check whether it is greater than or equal to 21. Nested ifstatements are very useful when dealing with complex logic, but overuse or incorrect use can lead to code that is difficult to understand and maintain. So when writing nested ifstatements, make sure your logic is clear and keep it as concise as possible.

3. Logical operators

1. Use of and, orand notoperators

In Python, andthe , orand notoperators are used for logical operations. They are used to combine multiple conditions or negate a single condition.

andoperator

  • andThe result of the operator is true if both conditions are true .
  • Otherwise, the result is false.
condition1 = True
condition2 = False
result = condition1 and condition2
print(result)  # 输出:False

oroperator

  • orThe result of the operator is true if at least one of the two conditions is true .
  • Otherwise, the result is false.
condition1 = True
condition2 = False
result = condition1 or condition2
print(result)  # 输出:True

notoperator

  • Negate a single condition.
  • If the condition is true, notthe result of the operator is false.
  • Otherwise, the result is true.
condition = True
result = not condition
print(result)  # 输出:False

Precautions

  • The operands on both sides of logical operators are usually Boolean values.
  • The order of operation of logical operators is from left to right.
  • Logical operators can be used with any Boolean expression.

Example

# 组合使用 and、or 和 not 运算符
x = 10
y = 20
result = (x > 5) and (y > 10)
print(result)  # 输出:False
result = (x > 5) or (y > 10)
print(result)  # 输出:True
result = not (x == y)
print(result)  # 输出:True

These operators are very useful when writing conditional statements, and they can help you build complex logical judgments. Proper use of logical operators can improve the clarity and readability of your code.

2. Application in conditional statements

Logical operators are widely used in conditional statements, and they allow you to combine multiple conditions to make more complex decisions. In Python, the main logical operators include and, orand not.

andoperator

  • andOperators are used to check whether two or more conditions are true at the same time.
  • Within ifa statement, you can andcombine multiple conditions using.
x = 10
y = 20
if x > 5 and y > 10:
    print("x 和 y 都大于它们的阈值。")

In this example, the code block will only be executed if it xis greater than 5 and ygreater than 10.

oroperator

  • orOperators are used to check whether at least one of two or more conditions is true.
  • Within ifa statement, you can orprovide an alternative condition using .
x = 10
y = 5
if x > 5 or y > 10:
    print("x 或 y 至少有一个大于它们的阈值。")

In this example, xif it is greater than 5 or ygreater than 10, the code block will be executed.

notoperator

  • notOperator is used to negate a single condition.
  • Within ifa statement, you can use notto reverse the logic of a condition.
x = 5
if not (x > 10):
    print("x 不大于10。")

In this example, notthe operator is used to check xif it is not greater than 10. If xit is not greater than 10, the code block will be executed.

Precautions

  • When using logical operators, be careful to keep the code readable and use spaces and newlines appropriately.
  • The operands on both sides of a logical operator should be of the same data type, usually Boolean.
  • When using multiple logical operators in combination, pay attention to the priority of the operation, andwhich has a higher priority than or. By rationally using logical operators, conditional statements can be made more precise and powerful, and can handle more complex logical judgments.

4. Loop structure

1. forBasic use of loops

In Python, fora loop is an iteration statement that traverses a sequence (such as a list, tuple, string) or any iterable object. Here are forthe basics of using loops:

  1. Basic forloop :

    for item in iterable:
        # 遍历iterable中的每个item
        print(item)
    
  2. forIteration variables in loops :

    • Iteration variables are usually named item, but you can use any valid variable name.
    • On each iteration, the next element in itemis assigned .iterable
  3. forCode block in loop :

    • Code blocks should be indented (usually 4 spaces or 1 tab).
    • Correct indentation is key to control structures in Python.
  4. Example :

    # 遍历列表中的每个元素
    fruits = ["apple", "banana", "cherry"]
    for fruit in fruits:
        print(fruit)
    

In this example, forthe loop iterates over fruitseach element in the list and prints it. 5. Clauses forin the loopelse :

  • forLoops can also contain an optional elseclause that is executed on each iteration of the outer loop without being breakinterrupted by a statement.
  • elseclause is typically used to perform cleanup work or some code when the loop completes normally.
for item in iterable:
    # 循环体代码
else:
    # 当循环正常完成时执行
    print("循环体已全部执行完毕。")

forLoops are a very powerful feature in Python and are widely used in scenarios such as data processing and file operations. Loops forallow you to easily iterate and manipulate each element in a sequence.

2. whileBasic use of loops

In Python, whilea loop is a cyclic structure that repeatedly executes a block of code based on a specific condition. Here are whilethe basics of using loops:

  1. Basic whileloop :

    while condition:
        # 当condition为真时,重复执行这里的代码
        print("条件为真,继续循环。")
    
  2. The basic structure of a loop :

    • whileThe keyword marks the beginning of the loop.
    • Conditional expressions should be surrounded by parentheses.
    • Code blocks should be indented (usually 4 spaces or 1 tab).
  3. Conditional judgment :

    • The loop will continue until the condition is no longer true.
    • The condition is usually a Boolean expression that determines whether the loop continues execution.
  4. Example :

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

In this example, whilethe loop repeats until countthe variable reaches the value 5. 5. Notes :

  • Avoid infinite loops and ensure that the condition will eventually become false.
  • Indent code blocks correctly to keep your code readable. whileLoops are an important tool for implementing repetitive tasks and continuously checking conditions. It is often used to handle situations that require multiple iterations until a certain condition is met. Proper use whileof loops can improve the efficiency and maintainability of your program.

5. Loop control statements

1. breakUse of statements

In Python, breaka statement is used to immediately exit the loop structure you are currently in, whether it is fora loop or whilea loop. The following is breakthe basic usage of statements:

  1. forUsed in a loopbreak :
    for item in iterable:
        if item == "special":
            break  # 退出for循环
        print(item)
    

In this example, if the statement in the loop itemequals "special", breakit will cause the loop to terminate immediately. 2. Use in a loopwhilebreak :

count = 0
while count < 5:
    print(count)
    count += 1
    if count == 3:
        break  # 退出while循环

In this example, when countequal to 3, breakthe statement will cause whilethe loop to terminate immediately. 3. Notes :

  • breakA statement can only be used at the loop level in which it is located.
  • Once the statement is executed break, the loop structure will end immediately, and the remaining code in the loop body will no longer be executed.
  • When using it break, you should ensure that the loop will eventually end to avoid creating an infinite loop. breakStatements are one of the key ways to control loop execution, allowing you to exit the loop early when certain conditions are met, thereby avoiding unnecessary iterations. Correct use breakcan make your code more efficient and flexible.

2. continueUse of statements

In Python, continuestatement is used to skip the remaining code of the current loop and start the next iteration. When continuethe statement executes, the current loop iteration terminates immediately, program control flow jumps back to the beginning of the loop, the loop condition is checked, and if the condition is true, the next iteration begins. The following is continuethe basic usage of statements:

  1. forUsed in a loopcontinue :
    for item in iterable:
        if item == "special":
            continue  # 跳过当前迭代,继续下一次迭代
        print(item)
    

In this example, if itemequals "special" in the loop, continuethe statement will cause the current iteration to terminate immediately and start the next iteration. 2.Use in whilea loopcontinue :

count = 0
while count < 5:
    count += 1
    if count == 3:
        continue  # 跳过当前迭代,继续下一次迭代
    print(count)

In this example, when countequal to 3, continuethe statement will cause the current iteration to terminate immediately and start the next iteration. 3. Notes :

  • continueA statement can only be used at the loop level in which it is located.
  • When used continue, you should make sure that it does not cause the loop to end prematurely, unless this is the desired effect.
  • continueStatements are typically used to skip unnecessary iterations, or to perform actions within a loop under certain conditions. continueStatements are another way to control loop execution, allowing you to skip the current iteration when certain conditions are met, thereby improving the efficiency and accuracy of the loop. Proper use continuecan make your code more flexible and easier to maintain.

3. Use of pass statement

In Python, passa statement is a no-op that performs no action and is typically used as a placeholder or to maintain the integrity of the code structure. Use when your code requires a statement, but you don't want it to perform any actual action pass. The following is passthe basic usage of statements:

  1. Basic passstatement :

    pass  # 这是一个空操作,不执行任何操作
    
  2. Use in function definitionpass :

    def example_function():
        pass  # 函数中使用pass作为占位符
    

In this example, example_functionit is an empty function, which does not contain any actual code. 3. Use in class definitionpass :

class ExampleClass:
    pass  # 类中使用pass作为占位符

In this example, ExampleClassit is an empty class, which does not define any properties or methods. 4. Notes :

  • passStatements are often used to keep the structure of your code intact, especially where a statement is expected but you don't want to perform any action.
  • Using it as a placeholder in a function or class passensures that your code follows Python's syntax rules, even if the function or class does not implement any functionality for the time being. passAlthough the statement is a no-op, in some cases it is necessary to keep the code clear and consistent. Correct use passcan make the code cleaner and facilitate future code maintenance and expansion.

6. Exercises and Examples

Practice questions on conditional statements and loop structures

  1. Age judgment : Write a program to judge whether a person can vote based on the entered age (assuming the voting age is 18 years old).
age = int(input("请输入年龄:"))
if age >= 18:
    print("可以投票。")
else:
    print("还未到投票年龄。")
  1. Print a triangle : Use fora loop to print a right triangle.
for i in range(1, 6):
    for j in range(1, i + 1):
        print("*", end=" ")
    print()
  1. Number-guessing game : Write a number-guessing game. The program randomly generates an integer between 1 and 100. The player has 10 chances to guess the number.
import random
secret_number = random.randint(1, 100)
for attempt in range(10):
    guess = int(input("请猜一个1到100之间的整数:"))
    if guess < secret_number:
        print("太小了!")
    elif guess > secret_number:
        print("太大了!")
    else:
        print(f"恭喜你,猜对了!秘密数字是 {secret_number}。")
        break
    if attempt == 9:
        print("你没有足够的尝试次数来猜出数字。")

Examples of real-world problem solving

Question 1: Calculate personal income tax

Assume that personal income tax is calculated as follows:

  • If your monthly income is less than or equal to 5,000 yuan, you do not need to pay personal income tax.
  • If the monthly income is between 5,000 yuan and 15,000 yuan, the tax rate is 5%.
  • If the monthly income is between 15,000 yuan and 30,000 yuan, the tax rate is 10%.
  • If the monthly income exceeds 30,000 yuan, the tax rate is 20%.
income = float(input("请输入您的月收入:"))
if income <= 5000:
    tax = 0
elif income <= 15000:
    tax = income * 0.05
elif income <= 30000:
    tax = income * 0.10
else:
    tax = income * 0.20
print(f"您的个人所得税为:{tax:.2f}元。")

Question 2: Calculate the sum of all even numbers between 1 and 100

sum_even = 0
for i in range(1, 101):
    if i % 2 == 0:
        sum_even += i
print(f"1到100之间所有偶数的和是:{sum_even}")

This article is a reprint of the article Heng Xiaopai , and the copyright belongs to the original author. It is recommended to visit the original text. To reprint this article, please contact the original author.

Linus took matters into his own hands to prevent kernel developers from replacing tabs with spaces. His father is one of the few leaders who can write code, his second son is the director of the open source technology department, and his youngest son is a core contributor to open source. Huawei: It took 1 year to convert 5,000 commonly used mobile applications Comprehensive migration to Hongmeng Java is the language most prone to third-party vulnerabilities. Wang Chenglu, the father of Hongmeng: open source Hongmeng is the only architectural innovation in the field of basic software in China. Ma Huateng and Zhou Hongyi shake hands to "remove grudges." Former Microsoft developer: Windows 11 performance is "ridiculously bad " " Although what Laoxiangji is open source is not the code, the reasons behind it are very heartwarming. Meta Llama 3 is officially released. Google announces a large-scale restructuring
{{o.name}}
{{m.name}}

Guess you like

Origin my.oschina.net/u/6851747/blog/11049084