Speed Run Functions and Classes

Video Tutorial

Functions in Python are reusable blocks of code that perform specific tasks, enhancing modularity and readability.

Functions and classes are fundamental building blocks in Python for creating reusable and modular code.

Functions

Functions are reusable blocks of code that perform specific tasks.

Defining a Function: Use the def keyword.

def greet():
    print("Hello, world!")
greet()  # Output: "Hello, world!"

Functions with Parameters: Pass data into functions using parameters.

def greet(name):
    print(f"Hello, {name}!")
greet("Alice")  # Output: "Hello, Alice!"

Returning Values: Use return to output a value from a function.

def add(a, b):
    return a + b
result = add(3, 5)
print(result)  # Output: 8

Default Parameters: Assign default values to parameters.

def greet(name="world"):
    print(f"Hello, {name}!")
greet()         # Output: "Hello, world!"
greet("Bob")    # Output: "Hello, Bob!"

Variable Number of Arguments: Use *args and **kwargs for flexible arguments.

def add(*args):
    return sum(args)
print(add(1, 2, 3))  # Output: 6

def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")
print_info(name="Alice", age=30)

Classes

Classes are blueprints for creating objects (instances), encapsulating data and functions together.

Defining a Class: Use the class keyword.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        print(f"Hello, my name is {self.name}.")

person1 = Person("Alice", 30)
person1.greet()  # Output: "Hello, my name is Alice."

Class Components:

  • Constructor (__init__): Initializes new objects.
  • Instance Variables: Data unique to each instance (self.name, self.age).
  • Methods: Functions defined within a class (greet).

Inheritance: Classes can inherit from other classes.

class Employee(Person):
    def __init__(self, name, age, employee_id):
        super().__init__(name, age)
        self.employee_id = employee_id

    def display_id(self):
        print(f"My employee ID is {self.employee_id}.")

employee1 = Employee("Bob", 25, "E123")
employee1.greet()         # Output: "Hello, my name is Bob."
employee1.display_id()    # Output: "My employee ID is E123."

Encapsulation: Use underscores to indicate private variables (convention).

class BankAccount:
    def __init__(self, balance):
        self._balance = balance  # Protected attribute

    def deposit(self, amount):
        self._balance += amount

    def get_balance(self):
        return self._balance

account = BankAccount(1000)
account.deposit(500)
print(account.get_balance())  # Output: 1500

Quiz

Question 1

What will be the output of the following code snippet?

def func(a, b=2, c=3):
    return a + b * c

result = func(1, c=4)
print(result)




Question 2

Given the following class definition, what will be the output?

class Counter:
    count = 0

    def __init__(self):
        Counter.count += 1

c1 = Counter()
c2 = Counter()
print(Counter.count)




Question 3

Which of the following statements is true about methods in Python classes?





Question 4

What is the output of the following code snippet involving closures?

def outer():
    x = "local"
    def inner():
        nonlocal x
        x = "nonlocal"
    inner()
    print("x =", x)

outer()




Code Editor