# Example of Conditional Statements
= 10
x if x > 5:
print('x is greater than 5')
elif x == 5:
print('x is equal to 5')
else:
print('x is less than 5')
Class 4: Control Structures, functions and list comprehension
Control Structures in Python
Control structures in Python provide a way to direct the flow of the program’s execution. They allow the program to make decisions, repeat certain actions, or execute specific blocks of code based on conditions. The primary control structures in Python are:
Conditional Statements (
if
,elif
,else
): These statements allow the program to execute specific blocks of code based on whether a condition is true or false.if condition: # code to execute if condition is true elif another_condition: # code to execute if another_condition is true else: # code to execute if none of the above conditions are true
Loops (
for
,while
): Loops allow the program to repeat a block of code multiple times.for
loop: Iterates over a sequence (like a list or range) and executes the block of code for each item in the sequence.for item in sequence: # code to execute for each item
while
loop: Repeats a block of code as long as a condition is true.while condition: # code to execute while condition is true
Control Keywords (
break
,continue
,pass
):break
: Exits the current loop prematurely.continue
: Skips the rest of the current iteration and moves to the next iteration of the loop.pass
: A placeholder that does nothing; it’s used when a statement is syntactically required but no action is needed.
for item in sequence: if condition: break elif another_condition: continue else: pass
Understanding and effectively using these control structures is fundamental to writing efficient and organized Python code.
# Example of Loops
# for loop
print('Example of for loop:')
for i in range(3):
print(f'Iteration {i}')
# while loop
print('\nExample of while loop:')
= 0
count while count < 3:
print(f'Count is {count}')
+= 1 count
# Example of Control Keywords
# break
print('Example of break:')
for i in range(5):
if i == 3:
break
print(i)
# continue
print('\nExample of continue:')
for i in range(5):
if i == 3:
continue
print(i)
# pass
print('\nExample of pass:')
for i in range(5):
if i == 3:
pass
print(i)
# Complex example of 'if' statement
# Determine if a year is a leap year
= 2000
year if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f'{year} is a leap year.')
else:
print(f'{year} is not a leap year.')
# Complex example of 'for' loop
# Calculate the factorial of a number using a for loop
= 5
num = 1
factorial for i in range(1, num + 1):
*= i
factorial print(f'Factorial of {num} is {factorial}')
# Complex example of 'while' loop
# Generate the Fibonacci sequence up to a certain number using a while loop
= 10
n = 0, 1
a, b print('Fibonacci sequence up to', n, ':')
while a < n:
print(a, end=', ')
= b, a+b a, b
# Complex example of 'break'
# Find the first number in a list that is divisible by 7 and 5
= list(range(1, 100))
numbers for num in numbers:
if num % 7 == 0 and num % 5 == 0:
print(f'The first number divisible by 7 and 5 is: {num}')
break
# Complex example of 'continue'
# Print numbers from a list, but skip numbers that are divisible by 3
= list(range(1, 15))
numbers for num in numbers:
if num % 3 == 0:
continue
print(num, end=', ')
# Complex example of 'pass'
# Placeholder for future implementation of a function
def complex_function():
# TODO: Implement this function in the future
pass
print('Function defined, but not yet implemented.')
Functions in Python
In Python, a function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. They are defined using the def
keyword, followed by the function name and parentheses ()
.
Functions are essential in programming as they help you break down complex tasks into smaller, more manageable pieces. This not only makes the code more readable but also allows for code reuse.
Let’s dive into some examples with different data types.
Function with Lists
def list_operations(input_list):
"""Perform some basic operations on a list."""
# Append an element
'new_element')
input_list.append(# Remove the first element
0)
input_list.pop(# Reverse the list
input_list.reverse()return input_list
# Test the function
= [1, 2, 3, 4, 5]
sample_list list_operations(sample_list)
Function with Dictionaries
def dict_operations(input_dict):
"""Perform some basic operations on a dictionary."""
# Add a new key-value pair
'new_key'] = 'new_value'
input_dict[# Remove a key-value pair
del input_dict['key1']
# Get value of a key with default
= input_dict.get('non_existent_key', 'default_value')
value return input_dict, value
# Test the function
= {'key1': 'value1', 'key2': 'value2'}
sample_dict dict_operations(sample_dict)
Function with numpy Arrays
import numpy as np
def numpy_operations(input_array):
"""Perform some basic operations on a numpy array."""
# Square each element
= np.square(input_array)
squared_array # Calculate the mean
= np.mean(input_array)
mean_value # Reshape the array
= input_array.reshape(2, 2)
reshaped_array return squared_array, mean_value, reshaped_array
# Test the function
= np.array([1, 2, 3, 4])
sample_array numpy_operations(sample_array)
Function with pandas Series
import pandas as pd
def series_operations(input_series):
"""Perform some basic operations on a pandas Series."""
# Add a new element
'd'] = 4
input_series[# Remove an element
'a', inplace=True)
input_series.drop(# Calculate the sum
= input_series.sum()
sum_value return input_series, sum_value
# Test the function
= pd.Series({'a': 1, 'b': 2, 'c': 3})
sample_series series_operations(sample_series)
Function with pandas DataFrame
def dataframe_operations(input_df):
"""Perform some basic operations on a pandas DataFrame."""
# Add a new column
'column3'] = [7, 8, 9]
input_df[# Drop a column
'column1', axis=1, inplace=True)
input_df.drop(# Calculate the mean of column2
= input_df['column2'].mean()
mean_value return input_df, mean_value
# Test the function
= pd.DataFrame({'column1': [1, 2, 3], 'column2': [4, 5, 6]})
sample_df dataframe_operations(sample_df)
List Comprehension
List comprehension is a concise way to create lists in Python. It offers a shorter syntax when you want to create a new list based on the values of an existing list or iterable. The primary motivation behind using list comprehension is to make code more readable and expressive.
The basic syntax is:
[expression for item in iterable if condition]
expression
is the current item in the iteration, but it is also the outcome, which can be manipulated before it ends up like a list item in the new list.item
is the current iteration/item.iterable
is any object that can return its elements one at a time, such as a list, a tuple, a string, etc.condition
is like a filter that only accepts the items that evaluate asTrue
.
List comprehensions are related to control structures, particularly loops and conditionals. In essence, a list comprehension combines a for
loop and an if
statement to create a new list. The for
loop iterates over each element in the iterable, and the if
statement filters out the unwanted elements.
For example, if you want to create a list of squares for even numbers from 0 to 9, you can use a list comprehension with a conditional statement to filter out odd numbers.
# Using list comprehension to get squares of even numbers from 0 to 9
= [x**2 for x in range(10) if x % 2 == 0]
squares_with_comprehension
# Without using list comprehension
= []
squares_without_comprehension for x in range(10):
if x % 2 == 0:
**2)
squares_without_comprehension.append(x
squares_with_comprehension, squares_without_comprehension
# Example 1: Get all vowels from a string
# Using list comprehension
= 'Hello, World!'
input_string = [char for char in input_string if char.lower() in 'aeiou']
vowels_with_comprehension
# Without using list comprehension
= []
vowels_without_comprehension for char in input_string:
if char.lower() in 'aeiou':
vowels_without_comprehension.append(char)
vowels_with_comprehension, vowels_without_comprehension
# Example 2: Get numbers from a list that are greater than 5
# Using list comprehension
= [1, 3, 7, 9, 10, 12]
numbers = [num for num in numbers if num > 5]
greater_than_five_with_comprehension
# Without using list comprehension
= []
greater_than_five_without_comprehension for num in numbers:
if num > 5:
greater_than_five_without_comprehension.append(num)
greater_than_five_with_comprehension, greater_than_five_without_comprehension
# Example 3: Get even indices from a list
# Using list comprehension
= ['a', 'b', 'c', 'd', 'e', 'f']
items = [items[i] for i in range(len(items)) if i % 2 == 0]
even_indices_with_comprehension
# Without using list comprehension
= []
even_indices_without_comprehension for i in range(len(items)):
if i % 2 == 0:
even_indices_without_comprehension.append(items[i])
even_indices_with_comprehension, even_indices_without_comprehension
Exercises
To test your understanding of the concepts covered in this notebook, try the following exercises:
Easy
- Control Structures: Write a program that prints numbers from 1 to 10 using a
for
loop. - Functions: Create a function that takes a list of numbers and returns their average.
Medium
- List Comprehension: Use list comprehension to create a list of squares for numbers from 1 to 20 that are divisible by 3.
- Functions with Data Structures: Create a function that takes a dictionary and returns a list of keys whose values are strings.
Hard
- Complex Control Structures: Write a program that prints the Fibonacci sequence up to the 10th term using a
while
loop. - Advanced Functions: Create a function that takes a pandas DataFrame and returns a new DataFrame with only the numeric columns, and each value squared.