Python Snippets for Functions
1. Types of Functions
a. Built-in Functions
Python comes with many built-in functions that are always available for use. Examples include
‘print()’, ‘len()’, ‘max()’, etc.
PGM:
Using built-in functions
print() - Prints the specified message to the screen
print("Hello, World!")
Output: Hello, World!
len() - Returns the length of an object
my_list = [1, 2, 3, 4, 5]
print(len(my_list))
Output: 5
max() - Returns the largest item
numbers = [10, 20, 30, 40, 50]
print(max(numbers))
Output: 50
b. Functions Defined in Modules
These are functions that are available in Python modules. You need to import the module before
you can use these functions.
PGM:
Using functions from the math module
import math
sqrt() - Returns the square root of a number.
import math
print([Link](16))
Output: 4.0
ceil() - Returns the smallest integer greater than or equal to a number.
import math
print([Link](3.7))
Output: 4
floor() - Returns the largest integer less than or equal to a number.
import math
print([Link](3.7))
Output: 3
copysign() - Returns a float consisting of the value of the first parameter and the sign(+/-) of the
second parameter.
import math
print([Link](4, -1))
print([Link](-8, 97.21))
print([Link](-43, -76))
Output: -4.0
8.0
-43.0
c. User-Defined Functions
These are functions that you define yourself to perform specific tasks.
PGM:
# Defining and using a user-defined function
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
# Output: Hello, Alice!
greet("Bob")
# Output: Hello, Bob!
2. Creating a User-Defined Function
You can create your own functions using the ‘def’ keyword followed by the function name and
parentheses ().
PGM:
def add_numbers(a, b):
#This function takes two numbers and returns their sum.
result = a + b
return result
sum_result = add_numbers(5, 7)
print(sum_result)
Output: 12
Explanation:
- ‘def add_numbers(a, b):’ defines a function named ‘add_numbers’ that takes two parameters
‘a’ and ‘b’.
- Inside the function, it calculates the sum and stores it in ‘result’.
- The ‘return’ statement returns the value of ‘result’.
- We call the function with arguments ‘5’ and ‘7’ and print the result.
3. Arguments and Parameters
Parameters are the variables listed inside the parentheses in the function definition. Arguments
are the values passed to the function when it is called.
PGM:
def multiply(a, b): #This function multiplies two numbers.
return a * b
# a and b are parameters
product = multiply(4, 5) # 4 and 5 are arguments
print(product)
Output: 20
Explanation:
- ‘a’ and ‘b’ are parameters in the function definition.
- When calling ‘multiply(4, 5)’, ‘4’ and ‘5’ are arguments passed to the function.
4. Default Parameters
You can provide default values for parameters. This makes the parameter optional when calling
the function.
PGM:
def power(base, exponent=2):
# This function raises base to the power of exponent.
# If exponent is not provided, it defaults to 2.
return base exponent
print(power(5, 3)) # Output: 125
print(power(4)) # Output: 16 (since default exponent is 2)
Explanation:
- In ‘def power(base, exponent=2):’, ‘exponent’ has a default value of ‘2’.
- When calling ‘power(4)’, it uses the default exponent ‘2’.
- When calling ‘power(5, 3)’, it uses the provided exponent ‘3’.
5. Positional Parameters
Positional parameters are those that are not assigned a default value and must be provided in
the correct order.
PGM:
def describe_person(name, age, city):
# This function prints information about a person.
print(f"{name} is {age} years old and lives in {city}.")
describe_person("Alice", 30, "New York")
Output: Alice is 30 years old and lives in New York.
# Using incorrect order
describe_person(30, "Alice", "New York")
# Output: 30 is Alice years old and lives in New York.
Explanation:
- The order of arguments matters in positional parameters.
- Providing arguments in the wrong order leads to incorrect results.
Using Keyword Arguments to Avoid Order Issues:
describe_person(age=30, name="Alice", city="New York")
# Output: Alice is 30 years old and lives in New York.
Explanation:
- By specifying the parameter names, you can pass arguments in any order.
6. Function Returning Value(s)
Functions can return values using the ‘return’ statement. You can return multiple values as a
tuple.
PGM:
def get_statistics(numbers):
#This function returns the minimum, maximum, and average of a list of numbers.
minimum = min(numbers)
maximum = max(numbers)
average = sum(numbers) / len(numbers)
return minimum, maximum, average
nums = [10, 20, 30, 40, 50]
min_num, max_num, avg_num = get_statistics(nums)
print(f"Minimum: {min_num}") # Output: Minimum: 10
print(f"Maximum: {max_num}") # Output: Maximum: 50
print(f"Average: {avg_num}") # Output: Average: 30.0
Explanation:
- The function ‘get_statistics’ computes the minimum, maximum, and average of a list.
- It returns all three values, which are unpacked into ‘min_num’, ‘max_num’, and ‘avg_num’.
7. Flow of Execution
The flow of execution refers to the order in which statements are executed in a program.
PGM:
def step_one():
print("Step 1: Preheat the oven.")
def step_two():
print("Step 2: Mix ingredients.")
def step_three():
print("Step 3: Bake for 30 minutes.")
print("Recipe Instructions:")
step_one()
step_two()
step_three()
print("Recipe completed.")
Output:
Recipe Instructions:
Step 1: Preheat the oven.
Step 2: Mix ingredients.
Step 3: Bake for 30 minutes.
Recipe completed.
Explanation:
- The program starts executing from the top.
- Functions ‘step_one’, ‘step_two’, and ‘step_three’ are defined.
- When these functions are called, the execution jumps to the function's code, executes it, and
then returns back to the point after the function call.
8. Scope of a Variable
The scope of a variable determines where in the program the variable is accessible.
a. Local Scope - Variables defined inside a function are in the local scope and cannot be
accessed outside the function.
PGM:
def local_scope_example():
local_var = "I am local"
print(local_var) # Output: I am local
local_scope_example()
# print(local_var) # This would raise a NameError
Explanation:
- ‘local_var’ is defined inside the function and is only accessible within that function.
b. Global Scope - Variables defined outside all functions are in the global scope and can be
accessed anywhere in the program.
PGM:
global_var = "I am global"
def access_global():
print(global_var) # Output: I am global
access_global()
print(global_var) # Output: I am global
Explanation:
- ‘global_var’ is accessible both inside the function ‘access_global’ and outside it.
c. Modifying Global Variables Inside Functions - To modify a global variable inside a function,
you need to use the ‘global’ keyword.
PGM:
counter = 0
def increment():
global counter
counter += 1
print(f"Counter before increment: {counter}") # Output: Counter before increment: 0
increment()
print(f"Counter after increment: {counter}") # Output: Counter after increment: 1
Explanation:
- Using ‘global counter’ tells Python that we are referring to the global variable ‘counter’ inside
the function.
- Without the ‘global’ keyword, Python would treat ‘counter’ as a new local variable.
d. Enclosing Scope (Nonlocal Variables) - When dealing with nested functions, variables in the
enclosing function can be accessed using the ‘nonlocal’ keyword.
PGM:
def outer_function():
message = "Hello"
def inner_function():
nonlocal message
message = "Hi"
print("Inner message:", message) # Output: Inner message: Hi
inner_function()
print("Outer message:", message) # Output: Outer message: Hi
outer_function()
Explanation:
- The ‘nonlocal’ keyword is used in ‘inner_function’ to indicate that ‘message’ refers to the
variable in the enclosing ‘outer_function’.
- Changes made to ‘message’ inside ‘inner_function’ affect the variable in ‘outer_function’.
Python Exception Handling
Exception handling in Python allows you to manage errors that occur during program execution.
This prevents the program from crashing and lets you handle errors gracefully using ‘try’,
‘except’.
1. Introduction to Exceptions
An exception is an event that occurs during the execution of a program that disrupts the normal
flow of instructions. Python provides a way to handle such exceptions using the `try`, `except`,
and `finally` blocks.
2. Handling Exceptions using `try-except-finally`
The `try` block contains the code that might raise an exception, the `except` block handles the
exception, and the `finally` block executes code that runs no matter what, even if an exception
occurs.
Example:
def read_file(file_path):
try:
with open(file_path, 'r') as file:
data = [Link]()
print("File content:\n", data)
except FileNotFoundError:
# Handle the exception if the file is not found
print("Error: File not found.")
except PermissionError:
# Handle the exception if there are permission issues
print("Error: Permission denied.")
finally:
# This block always executes
print("Execution completed, whether the file was read or not.")
read_file('[Link]')
3. Using `raise` to Throw Exceptions
The `raise` keyword is used to manually throw an exception in your code when a certain
condition is met.
Example:
def check_age(age):
if age < 18:
raise ValueError("Age must be at least 18.")
print("Age is acceptable.")
try:
check_age(16)
except ValueError as e:
print(f"Error: {e}")
In this example, the `check_age` function raises a `ValueError` if the age is less than 18, which
is then caught and handled in the `except` block.
4. Using `assert` for Debugging
The `assert` statement is used to test a condition. If the condition is `False`, it raises an
`AssertionError`.
Example:
def calculate_average(numbers):
assert len(numbers) > 0, "List must not be empty."
return sum(numbers) / len(numbers)
try:
avg = calculate_average([])
except AssertionError as e:
print(f"Assertion Error: {e}")
Here, the `calculate_average` function uses `assert` to check that the list of numbers is not
empty before attempting to calculate the average.
Python Snippets for File Handling
1. Introduction to Files, Types of Files, Relative and Absolute Paths
Relative path
file_relative = open("[Link]", "w")
file_relative.write("This is a relative path example.")
file_relative.close()
Absolute path
file_absolute = open("C:/absolute/path/to/your/directory/[Link]", "w")
file_absolute.write("This is an absolute path example.")
file_absolute.close()
2. Text File Operations
a. Opening a Text File and Modes
- Open file in different modes
file_read = open("[Link]", "r")
file_write = open("[Link]", "w")
file_append = open("[Link]", "a")
- Open file using 'with' clause
with open("[Link]", "w") as file:
[Link]("Using with clause to open a file.")
b. Writing/Appending Data
Writing to a text file
with open("[Link]", "w") as file:
[Link]("Hello, World!\n")
[Link](["Line 2\n", "Line 3\n"])
Appending data
with open("[Link]", "a") as file:
[Link]("Appended line.\n")
c. Reading from a Text File
Reading entire content
with open("[Link]", "r") as file:
content = [Link]()
Reading one line
with open("[Link]", "r") as file:
first_line = [Link]()
Reading all lines as a list
with open("[Link]", "r") as file:
all_lines = [Link]()
d. Seek and Tell Methods
with open("[Link]", "r") as file:
print([Link]()) # Current position
[Link](5) # Move to 5th byte
print([Link]()) # Read from new position
3. Binary File Operations
a. Write/Create Operation in a Binary File
import pickle
# Data to write
data = {"name": "John", "age": 25}
# Writing/Creating a binary file
with open("[Link]", "wb") as file:
[Link](data, file)
b. Read Operation from a Binary File
import pickle
# Reading from a binary file
with open("[Link]", "rb") as file:
loaded_data = [Link](file)
print(loaded_data) # Output: {'name': 'John', 'age': 25}
c. Search Operation in a Binary File
To search for specific data in a binary file, you typically need to load the data and then check if
the desired item is present.
import pickle
# Function to search for a key in the binary file
def search_binary_file(filename, key):
with open(filename, "rb") as file:
data = [Link](file)
return [Link](key, "Key not found")
search_result = search_binary_file("[Link]", "name")
print(search_result) # Output: 'John'
d. Append Operation in a Binary File
import pickle
# Appending data to an existing binary file
new_data = {"city": "New York"}
with open("[Link]", "rb") as file:
data = [Link](file) # Load existing data
[Link](new_data) # Update the data
with open("[Link]", "wb") as file: # Rewrite the updated data
[Link](data, file)
# Verify the append operation
with open("[Link]", "rb") as file:
print([Link](file)) # Output: {'name': 'John', 'age': 25, 'city': 'New York'}
e. Update Operation in a Binary File
import pickle
# Function to update a value for a given key
def update_binary_file(filename, key, new_value):
with open(filename, "rb") as file:
data = [Link](file)
data[key] = new_value # Update the key with the new value
with open(filename, "wb") as file: # Rewrite the updated data
[Link](data, file)
update_binary_file("[Link]", "age", 30)
# Verify the update
with open("[Link]", "rb") as file:
print([Link](file)) # Output: {'name': 'John', 'age': 30, 'city': 'New York'}
4. CSV File Operations
a. Import the `csv` Module
import csv is a statement that brings in the built-in csv module. This module provides tools to
read and write data in CSV (Comma Separated Values) format.
b. Writing to a CSV File
i. Using `writer()` and `writerow()`
import csv
# Data to write
header = ["Name", "Age", "City"]
row1 = ["John", 25, "New York"]
row2 = ["Anna", 22, "London"]
# Writing to a CSV file
with open("[Link]", "w", newline=' ') as file:
writer = [Link](file)
# Writing a single row (header)
[Link](header)
# Writing multiple rows individually
[Link](row1)
[Link](row2)
ii. Using `writerows()`
import csv
# Data to write
rows = [
["Name", "Age", "City"],
["John", 25, "New York"],
["Anna", 22, "London"],
["Mike", 30, "Chicago"]
]
# Writing multiple rows at once
with open("[Link]", "w", newline='') as file:
writer = [Link](file)
[Link](rows)
c. Reading from a CSV File
i. Using `reader()`
import csv
# Reading from a CSV file
with open("[Link]", "r") as file:
reader = [Link](file)
# Iterating through the rows
for row in reader:
print(row)
Single program to Read and Write
import csv
# Writing to a CSV file
with open("[Link]", "w", newline='') as file:
writer = [Link](file)
[Link](["Name", "Age", "City"])
[Link]([["John", 25, "New York"], ["Anna", 22, "London"]])
# Reading from a CSV file
with open("[Link]", "r") as file:
reader = [Link](file)
for row in reader:
print(row)
d. Search Operation on a CSV File
import csv
# Function to search for a value in a specific column
def search_in_csv(filename, search_value, column_index):
with open(filename, "r") as file:
reader = [Link](file)
# Iterate over each row in the CSV file
for row in reader:
# Check if the search value matches the column value
if row[column_index] == search_value:
return row # Return the matching row
return "Value not found"
result = search_in_csv("[Link]", "Ram", 0) # Search for "Ram" in the first column (index 0)
print(result)
[Link]
Name,Age,City
Ram,25,Coimbatore
Raj,22,Palakkad
Revi,28,Kovilpatti
Output
['Ram','25','Coimbatore']