Skip to content

Session 3#

Functions in Python

Let’s explore functions in Python in detail, covering function calls, built-in functions, custom functions, and parameters and arguments.


1. Functions#

A function is a block of reusable code that performs a specific task. Functions allow you to avoid code repetition, improve readability, and make programs modular.


2. Function Calls#

A function must be called to execute the code inside it.

  • Built-in Functions are provided by Python (e.g., print(), len(), type()).
  • Custom Functions are user-defined.

Example: Calling a Built-in Function#

# Using the built-in print() function
print("Hello, World!")  # Outputs: Hello, World!

3. Built-in Functions#

Python includes many built-in functions for various purposes, like:

  • Input/Output: print(), input()
  • Data Conversion: int(), float(), str()
  • Mathematical: abs(), pow(), round(), max(), min()
  • Data Structures: len(), sum(), sorted(), zip()
  • Type Checking: type(), isinstance()

Examples:#

# Mathematical functions
print(abs(-10))  # 10
print(pow(2, 3))  # 8 (2^3)

# Data functions
numbers = [3, 5, 1, 4]
print(len(numbers))  # 4
print(max(numbers))  # 5
print(sorted(numbers))  # [1, 3, 4, 5]

4. Custom Functions#

You can define your own functions using the def keyword.

Syntax:#

def function_name(parameters):
    # Code block
    return value  # Optional

Example 1: A Simple Function#

def greet():
    print("Hello, there!")

# Calling the function
greet()  # Outputs: Hello, there!

Example 2: Function with a Return Value#

def square(num):
    return num * num

result = square(4)
print(result)  # Outputs: 16

5. Parameters and Arguments#

Parameters: Variables listed in the function definition.

Arguments: Values passed to a function during a call.

Types of Arguments:#

  1. Positional Arguments: Matched by position.
  2. Keyword Arguments: Matched by name.
  3. Default Arguments: Provide default values for parameters.
  4. Variable-Length Arguments: Accept a variable number of arguments.

Example 1: Positional Arguments#

def add(a, b):
    return a + b

print(add(3, 5))  # Outputs: 8

Example 2: Keyword Arguments#

def greet(name, message):
    print(f"{message}, {name}!")

greet(name="Alice", message="Good morning")  # Outputs: Good morning, Alice!

Example 3: Default Arguments#

def greet(name, message="Hello"):
    print(f"{message}, {name}!")

greet("Bob")  # Outputs: Hello, Bob!

Example 4: Variable-Length Arguments#

def total_sum(*numbers):
    return sum(numbers)

print(total_sum(1, 2, 3, 4))  # Outputs: 10

6. Scope of Variables#

  • Local Scope: Variables declared inside a function are local to that function.
  • Global Scope: Variables declared outside functions are accessible globally.

Example:#

x = 10  # Global variable

def test_scope():
    x = 5  # Local variable
    print("Inside function:", x)

test_scope()  # Outputs: Inside function: 5
print("Outside function:", x)  # Outputs: Outside function: 10

7. Lambda Functions#

A lambda function is a small anonymous function defined using the lambda keyword.

Syntax:#

lambda arguments: expression

Example:#

square = lambda x: x * x
print(square(6))  # Outputs: 36

8. Higher-Order Functions#

Functions that take other functions as arguments or return functions.

Examples:#

# Using a function as an argument
def apply_operation(x, func):
    return func(x)

result = apply_operation(5, lambda x: x ** 2)
print(result)  # Outputs: 25

Practice Problems#

  1. Factorial Calculator:

    Write a function to compute the factorial of a number.

  2. Temperature Conversion:

    Create a function that converts Celsius to Fahrenheit and vice versa.

  3. Custom Sorting:

    Write a function to sort a list of tuples by the second element.

  4. Area Calculator:

    Write functions to calculate the area of a rectangle, triangle, and circle.

  5. Palindrome Checker:

    Create a function to check if a string is a palindrome.

Let me know which one you want to start with, or if you'd like detailed implementation examples for any! 😊


Files#

Let’s explore file handling in Python in detail, including how to open, read, manipulate, and write files.


1. Files in Python#

Files allow you to store data persistently. Python provides built-in support for working with files using the open() function.


2. Opening Files#

To work with a file, you need to open it first using the open() function.

Syntax:#

file_object = open(file_path, mode)

File Modes:#

Mode Description
'r' Read-only mode (default). File must exist.
'w' Write mode. Creates or overwrites a file.
'a' Append mode. Adds content to the end of file.
'r+' Read and write mode. File must exist.
'b' Binary mode. Combine with other modes (rb).

Example:#

# Open a file for reading
file = open("example.txt", "r")
print(file)  # Outputs: <_io.TextIOWrapper ...>

# Close the file
file.close()

3. Reading Files#

You can read file content using various methods.

Methods to Read Files:#

Method Description
read() Reads the entire file as a string.
readline() Reads one line at a time.
readlines() Reads all lines as a list of strings.

Examples:#

a. Read the Entire File:

with open("example.txt", "r") as file:
    content = file.read()
    print(content)

b. Read Line by Line:

with open("example.txt", "r") as file:
    for line in file:
        print(line.strip())  # Removes extra newline characters

c. Read Lines into a List:

with open("example.txt", "r") as file:
    lines = file.readlines()
    print(lines)  # Outputs: ['Line 1\\n', 'Line 2\\n']

4. Operations on File Content#

Once the content is read, you can manipulate it as needed.

Example: Count Words in a File#

with open("example.txt", "r") as file:
    content = file.read()
    words = content.split()  # Split text into words
    print("Word count:", len(words))

Example: Find Specific Words#

with open("example.txt", "r") as file:
    content = file.read()
    if "Python" in content:
        print("The word 'Python' is present.")

Example: Replace Words in Content#

with open("example.txt", "r") as file:
    content = file.read()

# Replace 'old_word' with 'new_word'
new_content = content.replace("old_word", "new_word")

with open("example.txt", "w") as file:
    file.write(new_content)  # Overwrite the file with updated content

5. Writing to Files#

You can create a new file or overwrite an existing file using 'w' mode. Use 'a' mode to append content to a file.

Writing Content:#

with open("output.txt", "w") as file:
    file.write("This is the first line.\\n")
    file.write("This is the second line.\\n")

Appending Content:#

with open("output.txt", "a") as file:
    file.write("This line is appended.\\n")

6. File Context Manager (with Statement)#

The with statement automatically closes the file after the block is executed, reducing the risk of resource leaks.

Example:#

with open("example.txt", "r") as file:
    content = file.read()
    print(content)  # File is automatically closed after this block

7. Binary Files#

Binary files (e.g., images, videos) require binary mode ('b').

Example: Copying an Image#

with open("image.jpg", "rb") as source:
    content = source.read()

with open("copy.jpg", "wb") as target:
    target.write(content)

8. Exception Handling in File Operations#

Errors like missing files can occur, so use try and except for safer file handling.

Example:#

try:
    with open("nonexistent.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("File not found!")

Practice Problems#

  1. File Reader:

    Write a program that reads a file and counts the number of lines, words, and characters.

  2. Word Frequency:

    Create a program that reads a file and finds the frequency of each word.

  3. CSV File Writer:

    Write a program to create a .csv file and write data to it.

  4. File Search:

    Search for a specific string in a file and print the lines where it appears.

  5. File Copier:

    Copy the content of one file to another, line by line.

Let me know which example or problem you'd like to explore further! 😊