Day 3: Python control structures: loops and conditionals
Conditional statements: if, elif, and else:
In Python, you can use conditional statements to make decisions based on conditions. In this guide, we will cover how to write if statements for decision-making based on conditions, use elif and else for multiple conditions and fallback actions, and write nested conditional statements for complex decision-making.
Writing if statements for decision-making based on conditions
An if statement is used to make a decision based on a condition. Here’s the basic syntax:
if condition: # code to execute if condition is True
Here’s an example:
x = 5
if x > 0:
print("x is positive")
In this example, the if statement checks whether x is greater than 0, and if it is, it executes the code block that prints “x is positive”.
Using elif and else for multiple conditions and fallback actions
You can use elif statements to check multiple conditions in sequence. Here’s the basic syntax:
if condition1: # code to execute if condition1 is True
elif condition2: # code to execute if condition2 is True
else: # code to execute if neither condition1 nor condition2 is True
Here’s an example:
x = 0
if x > 0:
print("x is positive")
elif x < 0:
print("x is negative")
else:
print("x is zero")
In this example, the if statement checks whether x is greater than 0, and if it is not, the elif statement checks whether x is less than 0. If neither condition is true, the else statement executes.
Nested conditional statements for complex decision-making
You can also use nested conditional statements to make complex decisions based on multiple conditions. Here’s an example:
x = 5
y = 10
if x > 0:
if y > 0:
print("x and y are both positive")
else: print("x is positive but y is not")
else: print("x is not positive")
In this example, the outer if statement checks whether x is greater than 0, and if it is, the inner if statement checks whether y is greater than 0. If both conditions are true, the code block that prints “x and y are both positive” is executed. If the outer if statement is true but the inner if statement is false, the code block that prints “x is positive but y is not” is executed. If the outer if statement is false, the else statement executes.
Congratulations! You now know how to write if statements for decision-making based on conditions, use elif and else for multiple conditions and fallback actions, and write nested conditional statements for complex decision-making. Happy coding!
Comparison operators and logical operators:
In Python, you can use comparison operators to compare values and logical operators to combine conditions. In this guide, we will cover the different comparison operators and logical operators, as well as short-circuit evaluation and operator precedence.
Comparison operators
Comparison operators are used to compare two values and return a boolean value (True or False). Here are the common comparison operators:
- ==: equality
- !=: inequality
- >: greater than
- <: less than
- >=: greater than or equal to
- <=: less than or equal to
Here are some examples:
x = 5
y = 10
print(x == y) # Output: False
print(x != y) # Output: True
print(x > y) # Output: False
print(x < y) # Output: True
print(x >= y) # Output: False
print(x <= y) # Output: True
Logical operators
Logical operators are used to combine conditions and return a boolean value (True or False). Here are the common logical operators:
- and: returns True if both conditions are True
- or: returns True if either condition is True
- not: returns the opposite boolean value
Here are some examples:
x = 5
y = 10
z = 15
print(x < y and y < z) # Output: True
print(x > y or y > z) # Output: False
print(not x < y) # Output: False
Short-circuit evaluation and operator precedence
In Python, logical operators are evaluated from left to right. Short-circuit evaluation is used to optimize the evaluation of logical operators. For example, if the left operand of an and operator is False, the right operand is not evaluated because the overall result will be False anyway.
Operator precedence determines the order in which operators are evaluated. For example, and has higher precedence than or, so and expressions are evaluated before or expressions. You can use parentheses to specify the order of evaluation. Here’s an example:
x = 5
y = 10
z = 15
print((x < y) and (y < z or x > z)) # Output: True
In this example, the parentheses specify that the or expression should be evaluated after the and expression.
Congratulations! You now know how to use comparison operators to compare values and logical operators to combine conditions, as well as short-circuit evaluation and operator precedence. Happy coding!
Loops: for loop and while loop:
In Python, you can use loops to repeat a block of code multiple times. There are two types of loops: for loops and while loops. In this guide, we will cover how to use for loops to iterate through sequences using the range() function, use while loops to repeat actions based on conditions, and write nested loops for multi-dimensional data or complex looping structures.
Iterating through sequences using the for loop and range() function
A for loop is used to iterate through a sequence of values. Here’s the basic syntax:
for variable in sequence: # code to execute for each value in sequence
Here’s an example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
In this example, the for loop iterates through the list of fruits and prints each fruit.
You can use the range() function to generate a sequence of numbers. Here’s an example:
for i in range(5):
print(i)
In this example, the for loop iterates through the sequence of numbers from 0 to 4 and prints each number.
Repeating actions based on conditions using the while loop
A while loop is used to repeat a block of code as long as a condition is true. Here’s the basic syntax:
while condition: # code to execute as long as condition is True
Here’s an example:
i = 0
while i < 5:
print(i)
i += 1
In this example, the while loop repeats as long as i is less than 5. The code block inside the loop prints the value of i and increments it by 1.
Nested loops for multi-dimensional data or complex looping structures
You can use nested loops to iterate through multi-dimensional data or to create complex looping structures. Here’s an example:
for i in range(3):
for j in range(3):
print(i, j)
In this example, the outer for loop iterates through the sequence of numbers from 0 to 2, and the inner for loop also iterates through the sequence of numbers from 0 to 2 for each value of i. The code block inside the nested loops prints the values of i and j.
Congratulations! You now know how to use for loops to iterate through sequences using the range() function, use while loops to repeat actions based on conditions, and write nested loops for multi-dimensional data or complex looping structures. Happy coding!
Loop control statements: break, continue, and else:
In Python, you can use loop control statements to change the behavior of loops. There are three loop control statements: break, continue, and else. In this guide, we will cover how to use break to exit a loop early when a certain condition is met, use continue to skip the remaining part of the loop iteration and move to the next iteration, and use else in loops to specify actions to be executed when the loop terminates normally.
Using break to exit a loop early when a certain condition is met
The break statement is used to exit a loop early when a certain condition is met. Here’s an example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
if fruit == "banana":
break
print(fruit)
In this example, the for loop iterates through the list of fruits and prints each fruit. When the loop reaches the value “banana”, the if statement is true and the break statement is executed, causing the loop to exit early.
Using continue to skip the remaining part of the loop iteration and move to the next iteration
The continue statement is used to skip the remaining part of the loop iteration and move to the next iteration. Here’s an example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
if fruit == "banana":
continue
print(fruit)
In this example, the for loop iterates through the list of fruits and prints each fruit except “banana”. When the loop reaches the value “banana”, the if statement is true and the remaining part of the loop iteration is skipped, causing the loop to move to the next iteration.
Using else in loops to specify actions to be executed when the loop terminates normally
The else statement can be used in loops to specify actions to be executed when the loop terminates normally. Here’s an example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
else:
print("No more fruits")
In this example, the for loop iterates through the list of fruits and prints each fruit. When the loop finishes iterating through all the fruits, the else statement is executed, causing the message “No more fruits” to be printed.
Congratulations! You now know how to use break to exit a loop early when a certain condition is met, use continue to skip the remaining part of the loop iteration and move to the next iteration, and use else in loops to specify actions to be executed when the loop terminates normally. Happy coding!