Control structures(Python)

Japanese version.

Python has various control structures that are used to control the flow of a program. Control structures are structures like conditional statements and loops that allow for flexible control of a program's execution. They form a core part of Python's syntax and are crucial in Python programming. Conditional statements and loops are necessary to extend a program's functionality and allow it to operate more flexibly. Using these control structures, a Python program can offer more advanced functionality and perform complex operations.

Conditional statements

Conditional statements are a fundamental feature of programming languages used to control the execution flow of a program. By using conditional statements, a program can execute different code blocks based on certain conditions. In Python, conditional statements are expressed using if statements, elif statements, and else statements. In this topic, we will provide an overview of conditional statements in Python and how to use them to write code.

Basic syntax.

Syntax of the if statement

Here's the syntax of the if statement in Python:

if condition1:
    # code to execute if condition1 is True

condition1 is an expression that returns a Boolean value (True or False). If condition1 is True, Python executes the statements in the if block.

Syntax of the if-else statement

Here's the syntax of the if-else statement in Python:

if condition1:
    # code to execute if condition1 is True

else:
    # code to execute if condition1 is False

condition1 is an expression that returns a Boolean value (True or False). If condition1 is True, Python executes the statements in the if block. If condition1 is False, Python executes the statements in the else block.

Syntax of the if-elif-else statement

Here's the syntax of the if-elif-else statement in Python:

if condition1:
    # code to execute if condition1 is True

elif condition2:
    # code to execute if condition2 is True and condition1 is False

else:
    # code to execute if both condition1 and condition2 are False

condition1 is an expression that returns a Boolean value (True or False). If condition1 is True, Python executes the statements in the if block. If condition1 is False, Python evaluates condition2. If condition2 is True, Python executes the statements in the elif block. If both condition1 and condition2 are False, Python executes the statements in the else block.

Example of conditional statements

Here's an example of conditional statements in Python:

x = 5
if x > 10:
    print("x is greater than 10.")

elif x > 5:
    print("x is greater than 5 and less than or equal to 10.")

else:
    print("x is less than or equal to 5.")

In this example, x is 5, so the else block is executed, resulting in the output "x is less than or equal to 5."

Notes on conditional statements

Here are a few things to keep in mind when using conditional statements in Python:

  • You don't necessarily have to use all three types of conditional statements in every situation. Use the ones that are necessary for your specific problem.
  • The conditions in if statements, elif statements, and else statements are evaluated sequentially from top to bottom. As soon as a condition is true, the corresponding block of code is executed, and the rest of the conditions are skipped.
  • You can use complex expressions or multiple conditions in your conditional statements.

Multiple conditions

Here's an example of using multiple conditions:

x = 10
y = 5

if x > 5 and y > 3:
    print("Both conditions are true.")

else:
    print("At least one of the conditions is false.")

In this example, there are two conditions being used. If both x > 5 and y > 3 are True, the statements in the if block are executed. Otherwise, the statements in the else block are executed. In this example, x is 10 and y is 5, so both conditions are True, resulting in the output "Both conditions are true."

You can also combine multiple conditions using the or operator. Here's an example of using the or operator:

x = 10
y = 5

if x > 5 or y > 10:
    print("At least one of the conditions is true.")

else:
    print("Both conditions are false.")

In this example, there are two conditions being used. If x > 5 or y > 10 is True, the statements in the if block are executed. Otherwise, the statements in the else block are executed. In this example, x is 10 and y is 5, so one of the conditions (x > 5) is True, resulting in the output "At least one of the conditions is true."

Nested conditional statements

Here's an example of nested conditional statements with an explanation of indentation in Python:

x = 10
y = 5

if x > 5:
    print("x is greater than 5.")

    if y > 3:
        print("y is greater than 3.")

    else:
        print("y is not greater than 3.")

else:
    print("x is not greater than 5.")

In this example, the first conditional statement checks whether x is greater than 5. If it is, the first print() statement is executed, followed by another conditional statement. This second conditional statement checks whether y is greater than 3. If it is, the second print() statement is executed, otherwise the third print() statement is executed. If x is not greater than 5 in the first conditional statement, the last print() statement is executed.

In Python, indentation is used to express nested conditional statements. Indentation is typically done using four spaces or one tab. Python uses indentation to identify blocks of code. That is, lines with the same indentation level belong to the same block, and lines with different indentation levels belong to different blocks. If the indentation is not correct, Python will raise an IndentationError.

One important thing to keep in mind is that since indentation has different depths, mixing spaces and tabs can cause errors when adjusting indentation. Therefore, it is recommended to use either spaces or tabs. Additionally, the Python style guide, PEP 8, recommends using four spaces for indentation.

Loops

In a program, the same process needs to be repeated many times. Python has control constructs for iterative processing, such as for and while statements. for statements can repeat a process for a specified number of times or elements, while statements repeat a process as long as the conditional expression is true, and while statements repeat a process as long as the conditional expression is true. while statement repeats the process as long as the conditional expression is true. Iteration can improve program efficiency by eliminating the need to manually perform the same process over and over again.

for statement

The for loop is a commonly used iteration method in Python used to repeat a set of statements for a range of values. It allows you to write code more concisely and efficiently.

Here's the basic syntax for a for loop in Python:

for variable in iterable:

    # code to execute

  • variable is the name of the variable used during the iteration.
  • iterable is the object to iterate over, such as a string, list, tuple, dictionary etc.

The for loop iterates over each item in the iterable. You can also use the range() function to specify a range of values.

Here's an example of using a for loop to iterate over values in a list:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

In this example, each item in the fruits list is assigned to the fruit variable in turn, and the print() function is used to display each value.

while statement

The while statement in Python repeatedly executes a series of statements as long as the specified condition is true. Here's a more detailed explanation of the while statement in Python:

Here's the syntax of the while statement in Python:

while condition:
    # statements to be repeated

condition is an expression that returns a Boolean value (True or False). Python executes the statements in the while block as long as condition is true.

Here's a simple example of the while statement in Python:

i = 0

while i < 10:
    print(i)
    i += 1

In this example, i starts at 0, and as long as it's less than 10, i is printed and incremented by 1.

The while statement executes repeatedly as long as the specified condition is true. If the condition is always true, the while statement may lead to an infinite loop.

If it falls into an infinite loop, use Ctrl + Z or the like to force termination.

break statement

break is a control flow statement in Python used to prematurely terminate a loop (such as a for loop or a while loop). When the break statement is executed, the current iteration of the loop is immediately stopped and the loop is exited.

Here's an example of using a for loop and the break statement to search for an element in a list:

fruits = ["apple", "banana", "cherry", "orange", "kiwi"]
search = "banana"

for fruit in fruits:

    if fruit == search:
        print(search + " found!")
        break

In this example, each element in the fruits list is assigned to the fruit variable in turn. An if statement checks whether fruit is equal to the value of the search variable. If fruit is equal to search, the break statement is executed, and the loop is exited. Otherwise, the next element is processed. If the value of search is not found in the fruits list, the for loop is executed to completion and nothing is printed.

The break statement can also be used with a while loop. Here's an example of using a while loop and the break statement to prompt the user to enter a positive number:

while True:
    num = int(input("Enter a number: "))

    if num > 0:
        print("Positive number entered.")
        break

    else:
        print("Please enter a positive number.")

In this example, the while loop runs indefinitely. The user is prompted to enter a number, and an if statement checks whether the entered number is positive. If the number is positive, the break statement is executed and the loop is exited. Otherwise, a message is displayed to the user to enter a positive number again.

continue statement

continue is a control flow statement in Python used to skip the current iteration of a loop (such as a for loop or a while loop) and move on to the next iteration.

Here's an example of using a for loop and the continue statement to skip a specific element in a list:

fruits = ["apple", "banana", "cherry", "orange", "kiwi"]

for fruit in fruits:
    if fruit == "banana":
        continue

    print(fruit)

In this example, each element in the fruits list is assigned to the fruit variable in turn. An if statement checks whether fruit is equal to "banana". If fruit is equal to "banana", the continue statement is executed, and the current iteration is skipped, moving on to the next iteration. Otherwise, the value of fruit is displayed.

The continue statement can also be used with a while loop. Here's an example of using a while loop and the continue statement to display only odd numbers from 1 to 10:

i = 0

while i < 10:
    i += 1
    if i % 2 == 0:
        continue

    print(i)

In this example, the i variable is initialized to 0, and the while loop is executed. The i variable is incremented by 1 on each iteration, and an if statement checks whether i is an even number. If i is even, the continue statement is executed, and the current iteration is skipped, moving on to the next iteration. If i is odd, its value is displayed. The loop is executed 10 times, and the while loop is exited.

else statement

In Python, you can use an else block with loop statements (such as for loops and while loops). The else block is executed if the loop completes normally.

Here's an example of using a for loop and the else block to search for an element in a list:

fruits = ["apple", "banana", "cherry", "orange", "kiwi"]
search = "banana"

for fruit in fruits:
    if fruit == search:
        print(search + " found!")
        break

else:
    print(search + " not found.")

In this example, each element in the fruits list is assigned to the fruit variable in turn. An if statement checks whether fruit is equal to the value of the search variable. If fruit is equal to search, the break statement is executed, and the loop is exited. Otherwise, the next element is processed. If the value of search is not found in the fruits list, the for loop is executed to completion, and the else block is executed, displaying a message indicating that the value of search was not found.

The else block can also be used with a while loop. Here's an example of using a while loop and the else block to display only even numbers from 1 to 10:

i = 0

while i < 10:
    i += 1
    if i % 2 == 1:
        continue

    print(i)

else:
    print("Loop completed.")

In this example, the i variable is initialized to 0, and the while loop is executed. The i variable is incremented by 1 on each iteration, and an if statement checks whether i is an odd number. If i is odd, the continue statement is executed, and the current iteration is skipped, moving on to the next iteration. If i is even, its value is displayed. The loop is executed 10 times, and the else block is executed, displaying a message indicating that the loop completed normally.

range function

In Python, you can use the range() function to iterate over a range of integers in a loop (such as a for loop or a while loop). The range() function creates an iterator that generates the specified range of integers.

The range() function takes three arguments:

  • start: the starting value of the range
  • stop: the stopping value of the range (this value is not included)
  • step: the interval between values in the range (default is 1)

Here's an example of using the range() function to display integers from 1 to 5:

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

In this example, the range() function creates an iterator that generates integers from 1 to 5. The for loop iterates over the iterator, assigning each value to the i variable in turn. The print() function displays the value of i.

You can also use the range() function to change the interval between values in the range. Here's an example of using the range() function to count down from 10 to 1 in steps of 2:

for i in range(10, 0, -2):
    print(i)

In this example, the range() function creates an iterator that generates integers from 10 to 1 in steps of -2. The for loop iterates over the iterator, assigning each value to the i variable in turn. The print() function displays the value of i.

enumerate function

In Python, if you need to get the index of elements during a loop (such as a for loop), you can use the enumerate() function. The enumerate() function generates an iterator that returns the index of each element along with the element itself.

The enumerate() function takes two arguments:

  • iterable: the iterable object to iterate over(e.g., a list, tuple, string, dictionary, etc.)
  • start: the starting value of the index (default is 0)

Here's an example of using the enumerate() function to display the elements and their indices in a list:

fruits = ["apple", "banana", "cherry"]

for i, fruit in enumerate(fruits):
    print(i, fruit)

In this example, the enumerate() function generates an iterator that returns the index and value of each element in the fruits list. The for loop iterates over the iterator, assigning each index and value to the i and fruit variables, respectively. The print() function displays the values of i and fruit.

You can also use the enumerate() function to start the index at a specific value. Here's an example of using the enumerate() function to display the elements of a list with indices starting at 1:

fruits = ["apple", "banana", "cherry"]

for i, fruit in enumerate(fruits, 1):
    print(i, fruit)

In this example, the enumerate() function generates an iterator that returns the index and value of each element in the fruits list, starting at 1. The for loop iterates over the iterator, assigning each index and value to the i and fruit variables, respectively. The print() function displays the values of i and fruit.

reversed function

In Python, if you need to iterate over a sequence (such as a list, tuple, or string) in reverse order, you can use the reversed() function. The reversed() function generates an iterator that iterates over the elements of the sequence in reverse order.

Here's an example of using the reversed() function to display a string in reverse order:

text = "Hello, World!"

for char in reversed(text):
    print(char)

In this example, the reversed() function generates an iterator that iterates over the characters of the text string in reverse order. The for loop iterates over the iterator, assigning each character to the char variable in turn. The print() function displays the value of char.

The reversed() function can also be used to iterate over a range() object in reverse order. Here's an example of using the reversed() function to count down from 10 to 1:

for i in reversed(range(1, 11)):
    print(i)

In this example, the range() function generates an iterator that generates integers from 1 to 10. The reversed() function generates an iterator that iterates over the integers in reverse order. The for loop iterates over the iterator, assigning each integer to the i variable in turn. The print() function displays the value of i.

Nested loops

In Python, you can nest loops (both for loops and while loops) inside one another to perform more complex operations. This structure is called nested of loops. By using nested loops, you can perform operations that require multiple levels of iteration.

Here's an example of using nested for loops to display a multiplication table:

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

    print()

In this example, the outer for loop iterates over the integers from 1 to 9. The inner for loop also iterates over the integers from 1 to 9. The print() function displays the result of i * j. The end="\t" argument specifies that the output should be separated by a tab character. The final print() function call is used to print a newline character after each inner loop is complete.

You can also nest while loops in a similar way.

Exception handling

In Python, exceptions are raised when unexpected errors occur during program execution. Exception handling is a mechanism used to catch these errors and allow the program to continue running. By using exception handling, you can deal with errors without causing your program to crash.

Python provides the try, except, else, and finally keywords for handling exceptions. The basic syntax for exception handling is as follows:

try:
    # Code that may raise an exception

except ExceptionType:
    # Code to execute if an exception of type ExceptionType is raised

else:
    # Code to execute if no exception is raised

finally:
    # Code that always executes, regardless of whether an exception is raised or not

The try block contains the code that may raise an exception. The except block specifies the code to execute if an exception is raised. The else block specifies the code to execute if no exception is raised. The finally block specifies code that will always execute, regardless of whether an exception is raised or not.

Here's an example of catching a ZeroDivisionError exception that occurs due to division by zero:

try:
    x = 1 / 0

except ZeroDivisionError:
    print("Division by zero error occurred.")

In this example, the try block performs a division by zero, which will raise a ZeroDivisionError exception. The except block catches the exception and prints an error message.

You can also catch multiple types of exceptions using multiple except blocks. Here's an example that catches both ValueError and TypeError exceptions:

try:
    x = int("foo")

except ValueError:
    print("Unable to convert string to integer.")

except TypeError:
    print("Invalid data type specified.")

In this example, the try block attempts to convert the string "foo" to an integer using the int() function. Since this is not possible, a ValueError exception is raised. If the int() function were called with a non-string data type, a TypeError exception would be raised instead. The except blocks catch the appropriate exception and print an error message.

You can also catch multiple exceptions in a single except block by specifying a tuple of exception types. Here's an example:

try:
    x = int("foo")

except (ValueError, TypeError):
    print("Unable to convert value to integer.")

In this example, a single except block catches both ValueError and TypeError exceptions by specifying a tuple of exception types.

Exception handling is a powerful tool for dealing with unexpected errors in your program without causing it to crash.

For those who want to learn Python efficiently.

The information on this site is now available in an easy-to-read e-book format for $3.00.

Or Kindle Unlimited (unlimited reading).

This textbook is used for new employees with no programming experience.

This book focuses on basic programming topics.

We do not cover topics such as object-oriented programming, statistical analysis using Python-specific libraries, machine learning, as these topics are difficult to understand from the standpoint of initial programming learning.

This book is especially recommended for those who have no experience with programming.

Links

Python Articles

Python