Understanding Python Loop Statements

1. Basic Syntax of while Loop

2. Basic Example of while Loop

3. Nested Applications of while Loop

4. Nested Example of while Loop

5. Basic Syntax of for Loop

6. Nested Applications of for Loop

7. Loop Interruption: break and continue

8. Comprehensive Example

1. Basic Syntax of while Loop

while condition:

Actions to perform when the condition is met

1. The condition of while must evaluate to a boolean type, where true indicates to continue looping, and false indicates to end the loop.

2. A termination condition for the loop must be set, for example, using i += 1 in conjunction with i < 10 ensures it stops after 10 iterations; otherwise, it will loop indefinitely.

3. Indentation is required just like in if statements.

Practice output: Sum of numbers from 1 to 100

a += 1 means a = a + 1

sum = 0
i = 1
while i <= 100:
    sum += i
    i += 1
print(f"The sum from 1 to 10 is: {sum}")

2. Basic Example of while Loop

Guess a number between 1 – 100 randomly

Hints for too high or too low

Finally display how many attempts were made

# Get a random number between 1 - 100
import random
from itertools import count
num = random.randint(1, 100)
# Define a variable to record the total number of guesses
count = 0
# Use a boolean variable to mark whether to continue looping
flag = True
while flag:
    guess_num = int(input("Please enter your guessed number: "))
    count += 1
    if guess_num == num:
        print("Guessed correctly")
        # Set false to terminate the loop
        flag = False
    else:
        if guess_num > num:
            print("You guessed too high")
        else:
            print("You guessed too low")
print(f"You guessed a total of {count} times")

Comprehensive practice: Find the sum from 1 to 100

sum = 0
i = 1
while i <= 100:
    sum = sum + i
    i = i + 1
print(sum)

3. Nested Applications of while Loop

Similar to nested if statements, nested loop statements require attention to indentation.

Indentation determines the hierarchical relationship.

Be cautious with condition settings to avoid infinite loops (unless truly needed).

Summary:

1. Syntax format:

while condition1:
    # Actions when condition1 is met
    # Actions when condition1 is met
    ...
    while condition2:
        # Actions when condition2 is met
        # Actions when condition2 is met
        ...

2. Points to note for nested loops:

Control conditions carefully to avoid infinite loops.

Multiple levels of nesting primarily rely on indentation to determine hierarchy.

3. Challenges in using nested loops:

Controlling loop conditions becomes more complex with more levels, requiring care and patience.

4. Nested Example of while Loop

Supplementary Knowledge Point 1

By default, the print statement outputs content with an automatic newline. To output without a newline, use print(“hello”, end = “”).

print(“hello”, end = ” “)

Supplementary Knowledge Point 2

In strings, there are special symbols: \t, which is equivalent to pressing the tab key on the keyboard.

It can help align multi-line strings.

For example:

print("hello \tword")
print("itmss \tguan")

hello worditmss guan

99 Multiplication Table Inner and Outer Loop

i = 1
while i <= 9:
    j = 1
    while j <= i:
        print(f"{j} * {i} = {j * i}\t", end=' ')
        j += 1
    i += 1
    print()
5. Basic Syntax of for Loop
5.1 Basic Syntax

for is a polling mechanism that processes a batch of content one by one.

1. for temporary variable in dataset (sequence):

Code executed when the loop condition is satisfied

# Define string name
name = "itheima"
# for loop processing string
for x in name:
    print(x)

2. Points to note for for loops:Cannot define loop conditions, can only passively extract from the dataset.

Be aware that statements within the loop need to be indented.

3. Example: How many ‘a’s are in the file?

name = "ytheima is a brand of ircast"
zif = 0
for x in name:
    if x == "a":
        zif += 1
print(zif)
5.2 range Statement

Syntax 1:

range(num)

Gets a sequence of numbers starting from 0 to num (excluding num itself).

For example, range(5) yields: [0, 1, 2, 3, 4]

Syntax 2:

range(num1, num2)

Gets a sequence of numbers starting from num1 to num2 (excluding num2 itself).

Syntax 3:

range(num1, num2, step)

Obtains a sequence of numbers starting from num1 to num2 (excluding num2 itself).

The step between numbers is determined by step (default is 1).

For example, range(5, 10, 2) yields: [5, 7, 9]

Practice for loop to confirm how many even numbers are there from 1 to 99:

jishu = 0
for x in range(1, 100):
    if x % 2 == 0:
        jishu += 1
print(jishu)
5.3 Variable Scope
# Non-standard
for x in range(1, 4):
    print(i)
print(i)
# Standard
i = 0
for i in range(1, 4):
    print(i)
print(i)

Summary:

1. The scope of temporary variables in for loops is limited to within the loop.

2. This limitation is a programming convention, not a strict limitation.

It can still run without following it.

If you need to access the temporary variable, you can define it outside the loop beforehand.

6. Nested Applications of for Loop

6.1 Syntax of Nested for Loop:

1. for loop or while loop:

Actions to perform when the loop condition is satisfied 1

Actions to perform when the loop condition is satisfied 1

for or while loop:

Actions to perform when the loop condition is satisfied 1

Actions to perform when the loop condition is satisfied 1

Comprehensive practice: 99 Multiplication Table

for loop

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

while loop:

i = 1
while i <= 9:
    j = 1
    while j <= i:
        print(f"{j} * {i} = {j * i}\t", end=' ')
        j += 1
    i += 1
    print()

7. Loop Interruption: break and continue

continue:

The continue keyword is used to interrupt the current loop and directly enter the next iteration of the loop.

continue can be used in both for and while loops, with the same effect.

for i in range(1, 100):
    # statement 1
    continue
    # statement 2

The code above:

In the loop, encountering continue ends the current iteration and moves to the next one.

Thus, statement 2 will not be executed.

Application scenario:

In a loop, temporarily end the current iteration for some reason.

break:

The break keyword can also only control the loop statement it is in, terminating that loop.

Summary:

1. The role of continue is:

To interrupt the current execution of the loop and directly enter the next iteration.

2. The role of break is:

To directly end the current loop.

3. Points to note:

Both have the same effect in for or while loops.

In nested loops, they only affect the loop they are in and cannot affect the outer loop.

8. Comprehensive Example

Salary Distribution: Company balance 10,000 yuan, 20 people. Distribute salaries based on performance; if performance score is below 5, do not distribute. If balance is insufficient, do not distribute at all.

Note: Random numbers can be generated using: import random

num = random

money = 10000
for i in range(1, 21):
    import random
    score = random.randint(1, 10)
    if score < 5:
        print(f"Employee {i} performance score {score}, does not meet criteria, come back next month")
        continue
    if money >= 1000:
        money -= 1000
        print(f"Employee {i}, meets criteria, salary of 1000 distributed, company account balance: {money}")
    else:
        print(f"Insufficient balance, current balance: {money} yuan, not enough to distribute salary, stop distributing, come back next month")
        break

Leave a Comment