Python Control Structures: Techniques for Implementing Complex Business Logic

Python Control Structures: Techniques for Implementing Complex Business Logic

Python is a powerful and easy-to-learn programming language, and control structures are an important component of programming that allow you to determine the execution path of your code based on conditions and loops. Mastering control structures in Python is crucial for clearly expressing complex business logic. This article will provide a detailed introduction to common control structures and help you understand their practical applications through code examples.

1. Conditional Statements

1.1 if Statement

<span>if</span> statements are used for conditional judgment, executing different code blocks based on given conditions. The basic syntax is as follows:

if condition:    # Executes when condition is Trueelif another_condition:    # Optional, executes when another_condition is Trueelse:    # Executes when none of the above conditions are met

Example

The following is a simple example to determine whether the user input number is positive, negative, or zero:

number = float(input("Please enter a number: "))if number > 0:    print("This is a positive number")elif number < 0:    print("This is a negative number")else:    print("This is zero")

1.2 Nested if Statements

In some cases, you may need to nest more judgments within a condition, which is called a nested<span>if</span>.

Example

The following code demonstrates how to use nested<span>if</span> to classify student grades:

score = float(input("Please enter the student's score: "))if score >= 60:    print("Pass")    if score >= 85:        print("Excellent")else:    print("Fail")

2. Loop Structures

Loops allow you to repeatedly execute a block of code until a specific condition is met. In Python, there are two main types of loops:<span>for</span> loops and <span>while</span> loops.

2.1 for Loop

Use the <span>for ... in ...:</span> format to iterate over iterable objects (such as lists, tuples, strings, etc.).

Example

The following example prints all elements in a list:

fruits = ["apple", "banana", "orange"]for fruit in fruits:    print(fruit)

2.2 while Loop

Use <span>while:</span> to repeatedly perform a specific operation while a condition is true.

Example

The following is a small program that calculates the factorial value, where the user inputs a non-negative integer and outputs the factorial of that number:

n = int(input("Please enter a non-negative integer: "))factorial = 1i = 1while i <= n:    factorial *= i    i += 1    print(f"The factorial of {n} is {factorial}")

3. Using break and continue Keywords

These two keywords can be used to prematurely end or skip the current iteration.

break Statement

Used to exit the current innermost loop.

Example

The following example demonstrates how to use <span>break</span> to terminate a search process:

numbers = [10, 20, -5, -20, -30]for num in numbers:   if num < 0:        break     print(num)

continue Statement

Used to skip the current iteration and continue to the next iteration.

Example

The following example demonstrates how to use <span>continue</span> to skip odd values:

for x in range(10):           if x % 2 == 0:                    continue           print(x)

Comprehensive Example: Shopping System Simulation

Finally, we will combine the knowledge from the previous sections to build a simple shopping system simulation. Suppose we have some products, allowing the user to choose the quantity to purchase while calculating the total price and providing feedback.

products = { 'apple': (5, 'Each apple costs 5 yuan'), 'banana': (3, 'Each banana costs 3 yuan'), }  total_cost = 0    print('Welcome to the shopping system')      # List available products    for product_name, (price, description) in products.items():         print(f'{product_name}: {description}')    while True:          chosen_product = input('Please choose a product to purchase (type "end" to checkout):')            if chosen_product == 'end':                   break                      elif chosen_product not in products:                  print('Product does not exist, please choose again')                    continue               quantity = int(input('Please enter quantity:'))         price = products[chosen_product][0]            total_cost += quantity * price                 print(f'Your total spending is {total_cost} yuan')

Conclusion

This article has provided a detailed introduction to commonly used control structures in Python, including conditional judgments and loops. At the same time, practical examples illustrate how these concepts are implemented in coding. This foundational knowledge will become an important tool for implementing complex business logic in future programming learning and practice. If you wish to explore related topics in depth, you can further read and explore based on your personal interests.

Leave a Comment