Python Flow Control and String Operations

Conditional Statements

if Statement

The syntax for an if statement is:


if condition:
    code_block

Execution flow: When the if condition evaluates to True, the code block is executed. If the condition is False, the code block is skipped, and the program continues execution.

Notes: 1. Each condition must be followed by a colon (:) to indicate the following statement block. 2. Use indentation to delineate code blocks. Statements with the same indentation level form a code block.

if-else Statement

The syntax for an if-else statement is:


if condition:
    code_block1
else:
    code_block2

Execution flow: If the condition is True, execute code_block1. Otherwise, execute code_block2.

Notes: 1. Each condition must be followed by a colon (:) to indicate the following statement block. 2. Use indentation to delineate code blocks. Statements with the same indentation level form a code block.

if-elif-else Statement

The syntax for an if-elif-else statement is:


if condition1:
    code_block1
elif condition2:
    code_block2
elif condition3:
    code_block3
...
else:
    code_blockn

Execution flow: If the if condition evaluates to True, execute code_block1. If not, evaluate elif condition2. If True, execute code_block2, and so on. If all conditions are False, execute code_blockn.

Notes: 1. Each condition must be followed by a colon (:) to indicate the following statement block. 2. Use indentation to delineate code blocks. Statements with the same indentation level form a code block.

Nested if Statements

Python, like C and Java, supports nested if statements, allowing if statements to be placed inside other if statements.

Loop Statements

while Statement

The while statement is typically used for conditional loops. Its syntax is:


while loop_condition:
    loop_body

Execution flow: When executing a while statement, if the loop condition is True, the statements in the loop body are executed. After completing the loop body, the loop condition is evaluated again. This process repeats until the loop condition becomes False, at which point the loop terminates, and execution continues with the code after the loop.

for...in Statement

The for statement is generally used for iteration, accessing each element of a target object sequentially, such as iterating through each character in a string.

The syntax for a for statement is:


for temporary_variable in target_object:
    loop_body

Example: Using a for...in loop to iterate through each character in a string:


for character in "python":
    print(character)

The for...in statement can be used with the range() function, which generates an iterable object of integers. The range() function has the format range([start,] stop[, step]):

  • start: Counting starts from start (default is 0)
  • stop: Counting ends at stop, which is not included
  • step: Sets the step size (default is 1)

Example:


for x in range(1, 6):
    print(x)

Nested Loops

Python, like C and Java, supports nested loops, allowing loops to be placed inside other loops.

Jump Statements

break Statement

The break statement terminates the entire loop. If a break statement is used within a loop, the program will exit the loop when it reaches the break statement. If the break statement is used within nested loops, the program will exit only the current loop level. The break statement is typically used with if statements to exit a loop when a condition is met.

Example: Using a for loop to iterate through the string "python", and exit the loop when encountering "o":


for char in "python":
    if(char == "o"):
        break
    print(char, end="")

continue Statement

The continue statement skips the current iteration and forces the next iteration of the loop to execute. It is typically used with if statements.

Example: Using a for loop to iterate through the string "python", and skip the current iteration when encountering "o":


for char in "python":
    if(char == "o"):
        continue
    print(char, end="")

Strings

String Introduction

A string is any content enclosed in single quotes, double quotes, or triple quotes. Single and double quotes are typically used for defining single-line strings, while triple quotes are used for multi-line strings.

Strings are immutable once created; any modification to a string creates a new string.

Notes: 1. If a string contains double quotes, use single or triple quotes to define the string. 2. If a string contains single quotes, use double or triple quotes to define the string. 3. If a string contains triple quotes, use single or double quotes to define the string. 4. You can use a backslash (\) before quotes in a string to treat the quote as a regular character rather than a special character.

Escape characters: When ordinary characters are combined with a backslash, they acquire new meanings. Escape characters are typically used to represent characters that cannot be displayed, such as spaces, carriage returns, etc.

Raw strings: By adding r or R before the opening quote, a string becomes a raw string. Raw strings ignore escape characters in the string. The r prefix makes Python ignore the special meaning of escape characters (\n, \r, \b) in the string and outputs the characters directly.

Example:


print(r'\n,\r,\b')

Without the r prefix:


print('\n,\r,\b')

String Formatting

String formatting converts specified strings into the desired format.

Python has three methods for string formatting: 1. Using % formatting 2. Using the format() method 3. Using f-string formatting In these methods, placeholders and actual data correspond sequentially for replacement.

Using % String Formatting

Syntax format:


string % actual_data

Explanation: 1. string: In this string, write format specifiers that will be replaced by actual data later. 2. actual_data: The actual data that will replace the format specifiers. 3. % represents the formatting operation, replacing format specifiers in the string with actual data.

Note: The data type of actual_data must match the data type represented by the format specifier; otherwise, an exception will occur.

Example 1:


value = 10
format_str = 'I am %d years old'
print(format_str % value)

Example 2: When using multiple format specifiers, the replacement data should be stored in a tuple:


name = 'John'
age = 25
address = 'New York, USA'
print("----------------")
print("Name: %s" % name)
print("Age: %d\nAddress: %s" % (age, address))
print("----------------")

Tags: python Flow Control Conditional Statements loops strings

Posted on Wed, 13 May 2026 18:30:03 +0000 by Liquidedust