# Example of Conditional Statements
x = 10
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 trueLoops (
for,while): Loops allow the program to repeat a block of code multiple times.forloop: 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 itemwhileloop: 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:')
count = 0
while count < 3:
print(f'Count is {count}')
count += 1# 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
year = 2000
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
num = 5
factorial = 1
for i in range(1, num + 1):
factorial *= i
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
n = 10
a, b = 0, 1
print('Fibonacci sequence up to', n, ':')
while a < n:
print(a, end=', ')
a, b = b, a+b# Complex example of 'break'
# Find the first number in a list that is divisible by 7 and 5
numbers = list(range(1, 100))
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
numbers = list(range(1, 15))
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
input_list.append('new_element')
# Remove the first element
input_list.pop(0)
# Reverse the list
input_list.reverse()
return input_list
# Test the function
sample_list = [1, 2, 3, 4, 5]
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
input_dict['new_key'] = 'new_value'
# Remove a key-value pair
del input_dict['key1']
# Get value of a key with default
value = input_dict.get('non_existent_key', 'default_value')
return input_dict, value
# Test the function
sample_dict = {'key1': 'value1', 'key2': 'value2'}
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
squared_array = np.square(input_array)
# Calculate the mean
mean_value = np.mean(input_array)
# Reshape the array
reshaped_array = input_array.reshape(2, 2)
return squared_array, mean_value, reshaped_array
# Test the function
sample_array = np.array([1, 2, 3, 4])
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
input_series['d'] = 4
# Remove an element
input_series.drop('a', inplace=True)
# Calculate the sum
sum_value = input_series.sum()
return input_series, sum_value
# Test the function
sample_series = pd.Series({'a': 1, 'b': 2, 'c': 3})
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
input_df['column3'] = [7, 8, 9]
# Drop a column
input_df.drop('column1', axis=1, inplace=True)
# Calculate the mean of column2
mean_value = input_df['column2'].mean()
return input_df, mean_value
# Test the function
sample_df = pd.DataFrame({'column1': [1, 2, 3], 'column2': [4, 5, 6]})
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]
expressionis 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.itemis the current iteration/item.iterableis any object that can return its elements one at a time, such as a list, a tuple, a string, etc.conditionis 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
squares_with_comprehension = [x**2 for x in range(10) if x % 2 == 0]
# Without using list comprehension
squares_without_comprehension = []
for x in range(10):
if x % 2 == 0:
squares_without_comprehension.append(x**2)
squares_with_comprehension, squares_without_comprehension# Example 1: Get all vowels from a string
# Using list comprehension
input_string = 'Hello, World!'
vowels_with_comprehension = [char for char in input_string if char.lower() in 'aeiou']
# 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
numbers = [1, 3, 7, 9, 10, 12]
greater_than_five_with_comprehension = [num for num in numbers if num > 5]
# 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
items = ['a', 'b', 'c', 'd', 'e', 'f']
even_indices_with_comprehension = [items[i] for i in range(len(items)) if i % 2 == 0]
# 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_comprehensionExercises
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
forloop. - 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
whileloop. - Advanced Functions: Create a function that takes a pandas DataFrame and returns a new DataFrame with only the numeric columns, and each value squared.