Python loop statement practical exercises and detailed explanation of loop nesting

loop statement

A loop statement causes a specified block of code to be executed a specified number of times. In Python, common loop statements include while loops and for loops.

while loop

The basic syntax of a while loop is as follows:

while 条件表达式:
    代码块
else:
    代码块

Implementation process:

  1. The conditional expression after executing while, if the result is True, the loop body (code block) is executed;
  2. After the loop body is executed, the conditional expression is judged again;
  3. If the conditional expression is still True, the loop body continues to be executed, and so on, until the conditional expression is False;
  4. If the loop has a corresponding else statement, the code block after the else is executed.

Sample code:

Here is a sample code that uses a while loop to print numbers:

i = 0
while i < 10:
    i += 1
    print(i, "hello")
else:
    print("else中的代码块")

In the above example, we first initialize the variable ito 0 and then i < 10control the execution of the loop by using it as a conditional expression. In the loop body, we iincrement the value and print out the current value and "hello". When i10 is reached, the conditional expression becomes False and the loop terminates. Finally, since the loop has a corresponding else statement, the code block in else will be executed and "code block in else" will be printed.

Loops can be flexible depending on the conditional expression. By controlling the conditional expression and the code in the loop body, you can implement various loop logics. When writing a loop, be sure to pay attention to the termination condition of the loop to avoid an infinite loop. At the same time, using the characteristics of loops can simplify repeated operations and improve code efficiency.

Practical exercises

Exercise 1: Find the sum of all odd numbers within 100

Sample code:

# 初始化变量sum,用于存储奇数之和
sum = 0

# 使用循环遍历100以内的所有数
for i in range(1, 101):
    # 判断当前数是否为奇数
    if i % 2 != 0:
        # 是奇数,则累加到sum中
        sum += i

print("100以内所有的奇数之和为:", sum)

Exercise 2: Find the sum and number of all multiples of 7 within 100

Sample code:

# 初始化变量sum和count,用于存储倍数之和和个数
sum = 0
count = 0

# 使用循环遍历100以内的所有数
for i in range(1, 101):
    # 判断当前数是否为7的倍数
    if i % 7 == 0:
        # 是7的倍数,则累加到sum中,并增加count的值
        sum += i
        count += 1

print("100以内所有的7的倍数之和为:", sum)
print("100以内所有的7的倍数个数为:", count)

Exercise 3: Find the number of all daffodils within 1000

The narcissus number refers to an n-digit number (n≥3), the sum of the nth power of the digits in each digit is equal to itself (for example: 1 3 + 5 3 + 3**3 = 153).

Find the number of all daffodils within 1000.
Sample code:

# 使用循环遍历1000以内的所有数
for num in range(100, 1000):
    # 获取百位、十位、个位数字
    hundreds_digit = num // 100
    tens_digit = (num // 10) % 10
    ones_digit = num % 10
    
    # 判断当前数是否为水仙花数
    if num == hundreds_digit ** 3 + tens_digit ** 3 + ones_digit ** 3:
        print(num)

Exercise 4: Get any number entered by the user and determine whether it is a prime number

# 获取用户输入的数字
num = int(input("请输入一个数字:"))

# 定义变量is_prime,用于判断是否为质数,默认为True
is_prime = True

# 判断是否为质数
if num > 1:
    for i in range(2, num):
        if num % i == 0:
            is_prime = False
            break
else:
    is_prime = False

# 输出结果
if is_prime:
    print(num, "是质数")
else:
    print(num, "不是质数")

Nested loops

Exercise 1: Print the 99 multiplication table

# 使用两层循环实现乘法表的打印
for i in range(1, 10):  # 控制行数
    for j in range(1, i + 1):  # 控制列数
        print(j, "*", i, "=", i * j, end=" ")
    print()

Exercise 2: Find all prime numbers within 100

# 初始化变量count,用于计数质数的个数
count = 0

# 使用循环遍历100以内的所有数
for num in range(2, 101):
    # 判断是否为质数
    is_prime = True
    for i in range(2, int(num ** 0.5) + 1):
        if num % i == 0:
            is_prime = False
            break

    # 如果是质数,则打印输出并增加计数器的值
    if is_prime:
        print(num, end=" ")
        count += 1

# 输出质数的个数
print("\n100以内所有的质数个数为:", count)

Mini game "Tang Monk vs. Bone Demon"

1、身份选择
    ① 显示提示信息
        欢迎光临 xxx 游戏!
        请选择你的身份:
            1.xxx
            2.xxx
        请选择:x
    ② 根据用户选择来分配身份(显示不同的提示消息)  
        1.---
        2.---
        3.---  

2、游戏进行
    ① 显示玩家的基本信息(攻击力 生命值)
    ② 显示玩家可以进行的操作:
        1、练级
            - 提升玩家的攻击力和生命值
        2、打BOSS
            - 玩家对BOSS进行攻击,玩家要攻击BOSS,BOSS对玩家进行反击
            - 计算BOSS是否被玩家消灭,玩家是否被BOSS消灭
            - 游戏结束
        3、逃跑
            - 退出游戏,显示提示信息,游戏结束!

Sample code:

import random

# 显示身份选择提示信息
print("欢迎光临《唐僧大战白骨精》游戏!")
print("请选择你的身份:")
print("1. 唐僧")
print("2. 白骨精")

# 获取用户选择的身份
choice = input("请选择(输入数字序号):")

if choice == "1":
    # 唐僧身份
    print("你选择了唐僧身份,祝你成功取经!")
    
    # 初始化玩家的攻击力和生命值
    player_attack = 10
    player_hp = 100
    
    while True:
        # 显示玩家的基本信息
        print("【玩家信息】")
        print("攻击力:", player_attack)
        print("生命值:", player_hp)
        
        # 显示玩家可以进行的操作
        print("请选择你要进行的操作:")
        print("1. 练级")
        print("2. 打BOSS")
        print("3. 逃跑")
        
        # 获取用户选择的操作
        choice = input("请选择(输入数字序号):")
        
        if choice == "1":
            # 练级操作,提升玩家的攻击力和生命值
            player_attack += 5
            player_hp += 20
            print("恭喜你,成功练级!")
        elif choice == "2":
            # 打BOSS操作
            boss_attack = random.randint(10, 30)
            boss_hp = random.randint(100, 200)
            
            print("【BOSS信息】")
            print("攻击力:", boss_attack)
            print("生命值:", boss_hp)
            print("战斗开始!")
            
            while True:
                # 玩家攻击BOSS
                boss_hp -= player_attack
                print("你对BOSS造成了", player_attack, "点伤害")
                
                # 判断是否击败BOSS
                if boss_hp <= 0:
                    print("恭喜你,成功击败BOSS!")
                    break
                
                # BOSS反击玩家
                player_hp -= boss_attack
                print("BOSS对你造成了", boss_attack, "点伤害")
                
                # 判断是否被BOSS消灭
                if player_hp <= 0:
                    print("很遗憾,你被BOSS消灭了!")
                    break
        elif choice == "3":
            # 逃跑操作,退出游戏
            print("你选择了逃跑,游戏结束!")
            break
        else:
            print("无效操作,请重新选择!")

elif choice == "2":
    # 白骨精身份
    print("你选择了白骨精身份,准备吃唐僧肉!")
    
    # 初始化玩家的攻击力和生命值
    player_attack = 20
    player_hp = 80
    
    while True:
        # 显示玩家的基本信息
        print("【玩家信息】")
        print("攻击力:", player_attack)
        print("生命值:", player_hp)
        
        # 显示玩家可以进行的操作
        print("请选择你要进行的操作:")
        print("1. 练级")
        print("2. 打唐僧")
        print("3. 逃跑")
        
        # 获取用户选择的操作
        choice = input("请选择(输入数字序号):")
        
        if choice == "1":
            # 练级操作,提升玩家的攻击力和生命值
            player_attack += 10
            player_hp += 10
            print("恭喜你,成功练级!")
        elif choice == "2":
            # 打唐僧操作
            tangseng_attack = random.randint(5, 15)
            tangseng_hp = random.randint(50, 150)
            
            print("【唐僧信息】")
            print("攻击力:", tangseng_attack)
            print("生命值:", tangseng_hp)
            print("战斗开始!")
            
            while True:
                # 玩家攻击唐僧
                tangseng_hp -= player_attack
                print("你对唐僧造成了", player_attack, "点伤害")
                
                # 判断是否击败唐僧
                if tangseng_hp <= 0:
                    print("恭喜你,成功吃到了唐僧肉!")
                    break
                
                # 唐僧反击玩家
                player_hp -= tangseng_attack
                print("唐僧对你造成了", tangseng_attack, "点伤害")
                
                # 判断是否被唐僧消灭
                if player_hp <= 0:
                    print("很遗憾,你被唐僧打败了!")
                    break
        elif choice == "3":
            # 逃跑操作,退出游戏
            print("你选择了逃跑,游戏结束!")
            break
        else:
            print("无效操作,请重新选择!")

else:
    print("无效选择,游戏结束!")

Summarize

A loop statement is an important control structure in programming that allows a specified block of code to be executed multiple times. In Python, common loop statements include while loops and for loops.

while loop

  • The basic syntax of the while loop is:

    while 条件表达式:
        代码块
    else:
        代码块
    
  • Implementation process:

    1. The conditional expression after executing while, if the result is True, the loop body (code block) is executed;
    2. After the loop body is executed, the conditional expression is judged again;
    3. If the conditional expression is still True, the loop body continues to be executed, and so on, until the conditional expression is False;
    4. If the loop has a corresponding else statement, the code block after the else is executed.
  • Notes on looping:

    • Avoid infinite loops: Make sure there is code inside the loop that can change the conditional expression, otherwise it will fall into an infinite loop.
    • Initialization and update expressions: You need to initialize variables outside the loop and update the variables inside the loop body to control the execution of the loop.
    • Utilize the break statement: You can use the break statement inside the loop to terminate the loop early.
  • Sample code:

    i = 0
    while i < 10:
        i += 1
        print(i, "hello")
    else:
        print("else中的代码块")
    

    In the above example, we use a while loop to print the numbers 1 to 10 and output "hello" after each number. When i reaches 10, the conditional expression i < 10 is False and the loop terminates. Finally, since the loop has a corresponding else statement, the code block in the else will be executed.

  • Flexibility of while loop: Different loop logic can be implemented by controlling the conditional expression and the code in the loop body. Utilizing the characteristics of loops can simplify repeated operations and improve code efficiency.

Loop is one of the commonly used control structures in programming. Mastering the use of loop statements can make the code more flexible and efficient. But also pay attention to the termination condition of the loop and avoid the situation of infinite loop, so as to ensure the correct execution of the program.


python learning column recommendations

Basic knowledge of python (0 basic introduction)

[Python Basics] 0.print() function
[Python Basics] 1. Data type, data application, data conversion
[Python Basics] 2.if conditional judgment and condition nesting
[Python Basics] 3.input() Functions
[Python Basics] 4. Lists and dictionaries
[Python Basics] 5. for loops and while loops
[Python Basics] 6. Boolean values ​​and four statements (break, continue, pass, else)
[Python Basics] 7. Practical operation - use Python to realize the "word PK" game (1)
[python basic knowledge] 7. Practical operation - use Python to realize the "word PK" game (2)
[python basic knowledge] 8. Programming thinking: how to Problem Solving - Thinking
[Python Basics] 9. Definition and Calling of Functions
[Python Basics] 10. Writing Programs with Functions - Practical Operations
[Python Basics] 10. Using Python to Realize the Rock-Paper-Scissors Game - Function Realization Operation
[Python Basics] 11. How to debug - Common Error Causes and Troubleshooting Ideas - Thinking
[Python Basics] 12. Classes and Objects (1)
[Python Basics] 12. Classes and Objects (2)
[Python Basics Knowledge] 13. Classes and objects (3)
[Python basics] 13. Classes and objects (4)
[Python basics] 14. Building a library management system (classes and objects)
[Python basics] 15. Coding basic knowledge
[Python Basics] 16. File reading and writing basics and operations
[Python Basics] 16. Python implementation of "Ancient Poetry Writing Questions" (file reading, writing and coding - practical articles)
[Python Basics] 17. The concept of modules and How to introduce
[python basics] 18. Practical operation - use python to automatically send mass emails
[python basics] 19. Product thinking and the use of flow charts - thinking
[python basics] 20. Python implementation of "what to eat for lunch" ( Product Thinking - Practical Operation)
[Python Basics] 21. The correct way to open efficiently and lazy - Graduation
[python file processing] CSV file reading, processing, writing
[python file processing] Excel automatic processing (using openpyxl)
[python file processing]-excel format processing

Guess you like

Origin blog.csdn.net/qq_41308872/article/details/132732131