Chapter 2: Conditional Statements and Loop Statements
Learning the syntax and usage of if/else conditional statements
In Python, if/else conditional statements are used to execute different code blocks based on conditions. The syntax format is as follows:
if condition1:
code_block1
elif condition2:
code_block2
else:
code_block3
if condition1:
code_block1
elif condition2:
code_block2
else:
code_block3
In this format, condition1 is an expression. If the value of the expression is True, code_block1 is executed. If the value of condition1 is False, condition2 is evaluated. If condition2 is True, code_block2 is executed; otherwise, code_block3 is executed. Multiple elif statements can be used to check multiple conditions.
Here's a simple example that outputs different grades based on user input:
score = input("Please enter the score: ")
score = int(score) # Convert the string to an integer
if score >= 90:
print("Excellent")
elif score >= 80:
print("Good")
elif score >= 60:
print("Pass")
else:
print("Fail")
score = input("Please enter the score: ")
score = int(score) # Convert the string to an integer
if score >= 90:
print("Excellent")
elif score >= 80:
print("Good")
elif score >= 60:
print("Pass")
else:
print("Fail")
In this example, the input function is used to get the user's score, which is then converted to an integer. The if/else conditional statements are used to determine the grade based on the score. If the score is greater than or equal to 90, "Excellent" is printed. If the score is greater than or equal to 80, "Good" is printed. If the score is greater than or equal to 60, "Pass" is printed. Otherwise, "Fail" is printed.
It's important to note that the conditions in if/else statements can be any expression that returns a Boolean value, such as comparison operations, logical operations, and bitwise operations. Additionally, the code blocks in if/else statements must have the same indentation, typically using four spaces.
In practical development, if/else conditional statements are often used to execute different code blocks based on various conditions, allowing for branching control in programs. It's important to carefully evaluate conditions in if/else statements to avoid unnecessary errors. Also, following Python's indentation rules helps maintain code readability and cleanliness.
Learning the syntax and usage of for/while loop statements
In Python, for/while loop statements are used to repeat the execution of a code block until a certain condition is met. The for loop is suitable for situations where the number of iterations is known, while the while loop is suitable for situations where the number of iterations is unknown. Let's explore the syntax and usage of these two loop statements:
- The for loop statement
The for loop statement is used to iterate over a sequence (such as a list, tuple, string, etc.) and execute a specified operation for each element. The syntax format is as follows:
for variable in sequence:
code_block
for variable in sequence:
code_block
In this format, the variable represents each element in the sequence, and the code_block represents the operation to be performed. Here's a simple example that outputs integers from 1 to 5:
for i in range(1, 6):
print(i)
for i in range(1, 6):
print(i)
In this example, the range function generates a sequence of integers from 1 to 5. The for loop statement iterates over each element, stores it in the variable i, and prints its value.
- The while loop statement
The while loop statement is used to repeatedly execute a code block until a certain condition is met. The syntax format is as follows:
while condition:
code_block
while condition:
code_block
In this format, the condition is evaluated, and if it's True, the code_block is executed. Here's a simple example that outputs integers from 1 to 5:
i = 1
while i <= 5:
print(i)
i += 1
i = 1
while i <= 5:
print(i)
i += 1
In this example, the variable i is initialized with a value of 1. The while loop statement checks if i is less than or equal to 5. If the condition is True, it prints the value of i and increments i by 1. This process continues until i becomes greater than 5, at which point the loop is exited.
It's important to note that the code blocks in for/while loop statements must have the same indentation, typically using four spaces. When writing loop statements, it's crucial to set the loop conditions correctly to avoid infinite loops. In practical development, for/while loop statements are often used for iterating over sequences, processing data, and other scenarios, significantly improving program efficiency and scalability.
Understanding the purpose of the break and continue statements
In Python, the break and continue keywords are commonly used in loop statements to control the flow of execution.
- The break statement
The break statement is used to terminate a loop prematurely, forcefully exiting the loop body. When a loop condition meets a certain condition, the break statement can be used to immediately exit the loop without executing the remainingcode. Here's an example that demonstrates the usage of the break statement:
for i in range(1, 6):
if i == 3:
break
print(i)
for i in range(1, 6):
if i == 3:
break
print(i)
In this example, the for loop iterates over the range from 1 to 6. When the value of i is equal to 3, the break statement is encountered, and the loop is terminated. As a result, only the values 1 and 2 are printed.
- The continue statement
The continue statement is used to skip the remaining code in the loop body and move to the next iteration. When a certain condition is met inside the loop, the continue statement allows you to skip the current iteration and proceed to the next one. Here's an example that demonstrates the usage of the continue statement:
for i in range(1, 6):
if i == 3:
continue
print(i)
for i in range(1, 6):
if i == 3:
continue
print(i)
In this example, the for loop iterates over the range from 1 to 6. When the value of i is equal to 3, the continue statement is encountered, and the remaining code in the loop body is skipped for that iteration. As a result, the value 3 is not printed, and the loop continues with the next iteration, printing the values 1, 2, 4, and 5.
The break and continue statements provide powerful control flow options within loop statements. They allow you to terminate loops early or skip specific iterations based on certain conditions, which can be useful in various scenarios and improve the efficiency of your code.