Python for Data Science: Day 3
Control Flow
Welcome to Day 3 of our Python for data science challenge! Control flow is a fundamental concept in programming that allows you to make decisions and control the flow of execution in your code. Today, we will explore control flow structures in Python, empowering you to write efficient and dynamic programs. Let’s get started!
If Statements:
If statements in Python allow you to make decisions and execute specific blocks of code based on certain conditions. Here’s an easy-to-understand explanation with code examples:
The basic structure of an if statement is as follows:
if condition:
# Code to be executed if the condition is True
else:
# Code to be executed if the condition is False
Here’s an example:
age = 15
if age >= 18:
print("You are an adult.")
else:
print("You are not an adult yet.")
In this example, the condition age >= 18
is checked. If the condition is true (the age is greater than or equal to 18), it executes the code inside the first block, which prints "You are an adult." If the condition is false (the age is less than 18), it executes the code inside the else block, which prints "You are not an adult yet."
You can also use multiple conditions using the elif
(short for "else if") statement to check additional conditions. Here's an example:
age = 15
if age < 13:
print("You are a child.")
elif age < 18:
print("You are a teenager.")
else:
print("You are an adult.")
In this example, the first condition age < 13
is checked. If it's true, it executes the code inside the first block. If it's false, it checks the next condition age < 18
and executes the code inside the elif
block if true. If both conditions are false, it executes the code inside the else
block.
You can also use comparison operators (such as <
, >
, <=
, >=
, ==
, !=
) to create more complex conditions within the if statement.
Remember to indent the code blocks under each condition properly. Python uses indentation to determine the scope of the code.
Else and Elif Clauses:
In Python, the else
and elif
clauses are used in conjunction with the if
statement to handle different conditions and make decisions based on those conditions. Let's dive into their usage:
Else Clause:
The else
clause is used when you want to provide an alternative block of code to execute if the condition in the if
statement evaluates to false. Here's an example:
age = 15
if age >= 18:
print("You are an adult.")
else:
print("You are not an adult yet.")
In this example, if the condition age >= 18
is true, it executes the code inside the if
block, which prints "You are an adult." Otherwise, if the condition is false, it executes the code inside the else
block, which prints "You are not an adult yet."
Elif Clause:
The elif
clause (short for "else if") allows you to check additional conditions after the initial if
condition. It provides an alternative block of code to execute if the preceding condition(s) are false. Here's an example:
age = 15
if age < 13:
print("You are a child.")
elif age < 18:
print("You are a teenager.")
else:
print("You are an adult.")
In this example, it checks the conditions in order. If the first condition age < 13
is true, it executes the code inside the first block. If it's false, it moves to the next condition age < 18
. If this condition is true, it executes the code inside the elif
block. If both conditions are false, it executes the code inside the else
block.
The elif
the clause allows you to handle multiple conditions and specify different actions based on those conditions.
It’s important to note that the else
clause is optional, while the elif
clause can be used multiple times after the initial if
statement to check different conditions.
Loops:
Loops in Python allow you to repeat a block of code multiple times. There are two main types of loops in Python: the for
loop and the while
loop. Let's explore each one:
For Loop:
The for
loop is used to iterate over a sequence (such as a list, string, or range) and execute a block of code for each item in the sequence. Here's an example:
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
In this example, the for
the loop iterates over each item in the fruits
list and executes the code inside the loop for each fruit. It will print "apple", "banana", and "orange" on separate lines.
While Loop:
The while
loop is used to repeatedly execute a block of code as long as a certain condition is true. Here's an example:
count = 0
while count < 5:
print("Count:", count)
count += 1
In this example, the while
the loop continues executing the code inside the loop as long as the condition count < 5
is true. It will print the current value of count
and increment it by 1 in each iteration, until count
becomes 5, at which point the condition becomes false, and the loop exits.
Loops are powerful because they allow you to automate repetitive tasks and process data efficiently. You can combine loops with conditional statements (if
, elif
, else
) and use various control statements (break
, continue
) to customize the behaviour of the loops.
It’s important to ensure that you have proper indentation for the code inside the loop. In Python, indentation is used to define the scope of the loop and the code that belongs to it.
Loop Control Statements:
Loop control statements in Python allow you to modify the behaviour of loops. They provide additional control over how the loops are executed. There are two commonly used loop control statements: break
and continue
. Let's explore each one:
Break Statement:
The break
the statement is used to exit a loop prematurely. When the break
the statement is encountered within a loop, it immediately terminates the loop and continues with the next statement outside the loop. Here's an example:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 3:
break
print(num)
In this example, the for
loop iterates over the numbers
list. When the loop encounters the number 3, the break
the statement is executed, and the loop is immediately terminated. As a result, only the numbers 1 and 2 are printed, and the loop doesn't continue with the remaining numbers.
Continue Statement:
The continue
statement is used to skip the rest of the current iteration and move to the next iteration of the loop. When the continue
statement is encountered, it jumps to the next iteration without executing the remaining code within the loop for that particular iteration. Here's an example:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 3:
continue
print(num)
In this example, when the loop encounters the number 3, the continue
statement is executed. As a result, the code within the loop for that iteration (which is the print(num)
statement) is skipped. The loop continues with the next iteration, printing the remaining numbers 1, 2, 4, and 5.
These loop control statements, break
and continue
, provide flexibility and allow you to control the flow of the loop execution. They can be particularly useful in situations where you want to stop a loop prematurely or skip certain iterations based on specific conditions.
Practical Examples:
Here are some practical examples showcasing the usage of control flow structures in real-world scenarios:
Voting Eligibility:
Let’s create a program that determines if a person is eligible to vote based on their age. We’ll use a if
statement to check the condition and provide appropriate feedback.
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote yet.")
Temperature Converter:
We can create a program that converts temperature from Celsius to Fahrenheit or vice versa based on user input. We’ll use conditional statements (if
, elif
, else
) to handle different conversion options.
temperature = float(input("Enter the temperature: "))
unit = input("Enter the unit (C for Celsius, F for Fahrenheit): ")
if unit == "C":
fahrenheit = (temperature * 9/5) + 32
print("Temperature in Fahrenheit:", fahrenheit)
elif unit == "F":
celsius = (temperature - 32) * 5/9
print("Temperature in Celsius:", celsius)
else:
print("Invalid unit entered.")
Grade Calculator:
Let’s build a program that calculates the grade based on a student’s score. We’ll use if
, elif
, and else
statements to assign grades based on different score ranges.
score = int(input("Enter your score: "))
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print("Your grade is:", grade)
These examples demonstrate how control flow structures like if
, elif
, and else
can be used to solve real-world problems. By using these structures, we can make decisions, perform different actions, and create more interactive and dynamic programs.
Congratulations on completing Day 3 of our Python for data science challenge! Today, you explored control flow structures, including if statements, else and elif clauses, loops, and loop control statements. These tools empower you to make decisions, iterate efficiently, and create dynamic programs.
Control flow is a critical aspect of any Python program, enabling you to handle conditions, perform iterations, and control the overall flow of execution. Tomorrow, on Day 4, we will delve into functions and modules, further expanding your programming capabilities.