0% found this document useful (0 votes)
5 views

python_Lec-3

The document provides an overview of Python functions, including defining functions, passing arguments, recursion, lambda functions, and classes/objects. It also covers inheritance and includes practical problems with solutions related to these concepts. Key examples demonstrate how to implement various functionalities in Python, such as calculating totals, recursive digit sums, and simulating a bank account.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

python_Lec-3

The document provides an overview of Python functions, including defining functions, passing arguments, recursion, lambda functions, and classes/objects. It also covers inheritance and includes practical problems with solutions related to these concepts. Key examples demonstrate how to implement various functionalities in Python, such as calculating totals, recursive digit sums, and simulating a bank account.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 33

Python Functions

def my_function():
print("Hello from a
function")

Calling a function: def my_function():


print("Hello from a
function")

my_function()
Functions: Arguments
Information can be passed into functions as def my_function(fname):
arguments. print(fname + " Refsnes")
Arguments are specified after the function
my_function("Emil")
name, inside the parentheses. You can add as
my_function("Tobias")
many arguments as you want, just separate my_function("Linus")
them with a comma.

def my_function(fname, lname):


print(fname + " " + lname)
By default, a function must be called with the
correct number of arguments. Meaning that if my_function("Emil", "Refsnes")
your function expects 2 arguments, you have
to call the function with 2 arguments, not
more, and not less def my_function(fname, lname):
print(fname + " " + lname)

my_function("Emil")
Functions: Arguments
If you do not know how many arguments that
will be passed into your function, add
a * before the parameter name in the
function definition.

This way the function will receive a tuple of


arguments, and can access the items
You can also send arguments with
accordingly.
the key = value syntax.
def my_function(*kids):
print("The youngest child is " +
This way the order of the arguments
kids[2]) does not matter.

my_function("Emil", "Tobias", "Linus")


def my_function(child3, child2, child1):
print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3


Functions: Arguments
The following example shows how to You can send any data types of argument to
use a default parameter value. a function (string, number, list, dictionary
etc.), and it will be treated as the same data
If we call the function without type inside the function.
argument, it uses the default value.
E.g. if you send a List as an argument, it will
def my_function(country
still be a List when it reaches the function
= "Norway"):
print("I am from " + country)
def my_function(food):
my_function("Sweden") for x in food:
my_function("India") print(x)
my_function()
my_function("Brazil")) fruits = ["apple", "banana", "cherry"]

my_function(fruits)
Functions: Arguments
To let a function return a value, use def my_function(x):
the return statement. return 5 * x

print(my_function(3))
print(my_function(5))
function definitions cannot be empty, but if you for print(my_function(9))
some reason have a function definition with no
content, put in the pass statement to avoid getting def myfunction():
an error. pass

You can specify that a function can have ONLY def my_function(x, /):
positional arguments, or ONLY keyword print(x)
arguments.
my_function(3)
To specify that a function can have only positional
arguments, add , / after the arguments
Functions: Arguments
To specify that a function can have only keyword def my_function(*, x):
arguments, add *, before the arguments: print(x)

my_function(x = 3)

def my_function(x):
Without the *, you are allowed to use positional print(x)
arguments even if the function expects keyword
arguments my_function(3)

You can combine the two argument types in the def my_function(a, b, /, *, c,
same function. d):
Any argument before the / , are positional-only, print(a + b + c + d)
and any argument after the *, are keyword-only.
my_function(5, 6, c = 7, d = 8)
Functions: Recursion
Python also accepts function recursion, which means a defined function can call itself.

Recursion is a common mathematical and programming concept. It means that a


function calls itself. This has the benefit of meaning that you can loop through data to
reach a result.

def tri_recursion(k):
if(k > 0): tri_recursion() is a function that we
result = k + tri_recursion(k - 1) have defined to call itself ("recurse").
print(result)
else: We use the k variable as the data,
result = 0 which decrements (-1) every time we
return result recurse. The recursion ends when the
condition is not greater than 0 (i.e.
print("Recursion Example Results:") when it is 0).
tri_recursion(6)

Go To next slide to understand deeply


Functions: Recursion
def tri_recursion(k): tri_recursion(6)
if(k > 0): → 6 + tri_recursion(5)
result = k + tri_recursion(k
→ 5 + tri_recursion(4)
- 1)
→ 4 + tri_recursion(3)
print(result)
else: → 3 + tri_recursion(2)
result = 0 → 2 + tri_recursion(1)
return result → 1 + tri_recursion(0)
→ returns 0
print("Recursion Example Results:") → 1 + 0 = 1 → print(1)
tri_recursion(6) → 2 + 1 = 3 → print(3)
Recursion Example Results: → 3 + 3 = 6 → print(6)
1 → 4 + 6 = 10 → print(10)
3 → 5 + 10 = 15 → print(15)
6 → 6 + 15 = 21 → print(21)
10
15
21
Python Lambda

A lambda function is a small anonymous function.


x = lambda a : a + 10
print(x(5))
A lambda function can take any number of
arguments but can only have one expression.

x = lambda a, b : a * b
print(x(5, 6))

x = lambda a, b, c : a + b +
c
print(x(5, 6, 2))
Python Lambda
The power of lambda is better shown when you def myfunc(n):
use them as an anonymous function inside return lambda a : a * n
another function.
def myfunc(n):
A lambda function can take any number of return lambda a : a * n
arguments but can only have one expression.
mydoubler = myfunc(2)

print(mydoubler(11))

x = lambda a, b, c : a + b +
c
print(x(5, 6, 2))
Python Arrays
Python does not
have built-in support
for Arrays, but
Python Lists can be
used instead.

however, to work
with arrays in Python
you will have to
import a library, like
the NumPy library.
Python Class/Objects

Create a Class class MyClass:


To create a class, use the keyword class: x = 5

Create Object
p1 = MyClass()
Now we can use the class named MyClass print(p1.x)
to create objects:

This example are classes and objects in their simplest form and are not useful in real life
applications.
Python Class/Objects
All classes have a function called __init__(), which is always executed when the
class is being initiated

Use the __init__() function to assign values to object properties, or other


operations that are necessary to do when the object is being created

class Person: The self parameter


def __init__(self, name, age): is a reference to
self.name = name the current
self.age = age
instance of the
p1 = Person("John", 36) class and is used
to access
print(p1.name) variables that
print(p1.age) belong to the
class.
Note: The __init__() function is called automatically every time the class is being used to
create a new object
Python Class/Objects
The __str__() function controls what should be returned when the class object is
represented as a string.

If the __str__() function is not set, the string representation of the object is
returned:

class Person:
class Person: def __init__(self, name, age):
def __init__(self, name, self.name = name
age): self.age = age
self.name = name
self.age = age def __str__(self):
return f"{self.name}
p1 = Person("John", 36) ({self.age})"

print(p1) p1 = Person("John", 36)

print(p1)
Python Objects/Methods
Objects can also contain methods. Methods Modify Object Properties
in objects are functions that belong to the
object. p1.age = 40
Delete Object Properties
Insert a function that prints a greeting, and
execute it on the p1 object: del p1.age
Delete Objects
class Person:
def __init__(self, name, age): del p1
self.name = name
self.age = age The pass Statement
class definitions cannot be
def myfunc(self): empty
print("Hello my name is " +
self.name)
class Person:
p1 = Person("John", 36) pass
p1.myfunc()
Python Inheritance

Create a Parent Class Create a Child Class

To create a class that inherits the


class Person: functionality from another class, send
def __init__(self, fname, lname): the parent class as a parameter when
self.firstname = fname creating the child class:
self.lastname = lname
class Student(Person):
def printname(self): pass
print(self.firstname, self.lastname)
Now the Student class has the same
x = Person("John", "Doe") properties and methods as the Person
x.printname() class.

x = Student("Mike", "Olsen")
x.printname()
Python Inheritance
Add the __init__() Function to child class Student(Person):
class def __init__(self, fname, lname):
#add properties etc.
Note: when you add the __init__() function,
the child class will no longer inherit the
parent's __init__() function. class Student(Person):
def __init__(self, fname, lname):
To keep the inheritance of the Person.__init__(self, fname,
parent's __init__() function, add a call to the lname)
parent's __init__() function:
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
Python also has a super() function that will
make the child class inherit all the methods
and properties from its parent: class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
Add Properties to child class
self.graduationyear = 2019
Python Inheritance
class Student(Person):
def __init__(self, fname, lname,
Add a year parameter, and pass the year):
correct year when creating objects: super().__init__(fname, lname)
self.graduationyear = year

x = Student("Mike", "Olsen", 2019)


Add Methods to child class

class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year

def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of",
self.graduationyear)
Note: If you add a method in the child class with the same name as a function in the parent
class, the inheritance of the parent method will be overridden.
Solve some real problem!
Part 1: Functions with Different Argument Styles
Problem 1: Grocery Bill Calculator
Write a function called calculate_total that takes:
•A required argument name (string)
•A required argument base_items (list of prices)
•An optional keyword-only argument discount (float, default 0.0)
•A variable number of additional item prices using *args

The function should:


•Add all item prices
•Apply the discount (as a percentage)
•Return the total cost

# Example: calculate_total("Alice", [10, 20], 10, 5, 5) → should apply 10% discount on total
Solve some real problem!

Part 2: Recursion
Problem 2: Recursive Digit Sum
Write a function recursive_digit_sum(n) that:
•Takes an integer n
•Recursively sums its digits until a single-digit number is obtained
•Returns that single-digit number

# Example: 987 → 9+8+7=24 → 2+4=6 → output: 6


Solve some real problem!
Part 3: Lambda Usage
Problem 3: Shortlist Scores You are given a list of student scores. Write a function that:
•Takes a list of tuples (name, score)
•Returns the top 3 names with the highest scores using sorted() and a lambda function

# Example: [("Ana", 80), ("Ben", 90), ("Cara", 85), ("Dan", 88)] → Output: ["Ben", "Dan", "Cara"]

Part 4: Classes and Objects


Problem 4: Bank Account Simulator Create a class BankAccount with:
•Attributes: name, balance
•Methods: deposit(amount), withdraw(amount), and show_balance()

Create an object and simulate a few deposits and withdrawals.

# Output should show balance after each operation


Solve some real problem!

Part 5: Class Inheritance


Problem 5: Animal Sounds Create a base class Animal with:
•Method: make_sound() (default returns “Some sound”)
Create derived classes:
•Dog that overrides make_sound() to return “Bark”
•Cat that returns “Meow”
Write a function that:
•Takes a list of Animal objects (some dogs, some cats)
•Calls make_sound() on each and prints the result
Solve some real problem!

✨ Bonus Challenge: Combine Concepts


Problem 6: Library System Build a mini library system:
•Base class: Book with title and author
•Subclass: BorrowedBook (add borrower name, due date)
•Use a function with default and keyword arguments to create books
•Use a lambda to filter books due within 3 days (simulate with dates)
•Demonstrate with a list of BorrowedBook objects
1 Solutions!!
def calculate_total(name, base_items, discount=0.0, *additional_items):
all_items = base_items + list(additional_items)
total = sum(all_items)
discounted_total = total - (discount / 100) * total
return f"{name}, your final bill after {discount}% discount is ${discounted_total:.2f}"

# Example usage:
print(calculate_total("Alice", [10, 20], 10, 5, 5)) # → $36.00
2 Solutions!!
def recursive_digit_sum(n):
if n < 10:
return n
digit_sum = sum(int(d) for d in str(n))
return recursive_digit_sum(digit_sum)
recursive_digit_sum(9875)
n = int(input("Enter number: "))
→ digit sum = 29
result = recursive_digit_sum(n) → recursive_digit_sum(29)
print(f"The result is {result}") → digit sum = 11
→ recursive_digit_sum(11)
→ digit sum = 2
→ recursive_digit_sum(2)
→ returns 2
← returns 2
← returns 2
← returns 2
← returns 2
3. Solutions!!
def top_scores(students):
top3 = sorted(students, key=lambda x: x[1], reverse=True)[:3]
return [name for name, score in top3]

# Example usage:
print(top_scores([("Ana", 80), ("Ben", 90), ("Cara", 85), ("Dan", 88)]))
# → ["Ben", "Dan", "Cara"]
4. Solutions!!
class BankAccount: # Example usage:
def __init__(self, name, balance=0): account = BankAccount("John", 100)
self.name = name account.deposit(50)
self.balance = balance account.withdraw(30)
account.withdraw(150)
def deposit(self, amount): account.show_balance()
self.balance += amount
print(f"{self.name} deposited ${amount}. New balance: ${self.balance}")

def withdraw(self, amount):


if amount > self.balance:
print(f"{self.name} attempted to withdraw ${amount} — Insufficient funds!")
else:
self.balance -= amount
print(f"{self.name} withdrew ${amount}. New balance: ${self.balance}")

def show_balance(self):
print(f"{self.name}'s current balance is ${self.balance}")
class Animal:

5. Solutions!! def make_sound(self):


return "Some sound"

class Dog(Animal):
def make_sound(self):
return "Bark"

class Cat(Animal):
def make_sound(self):
return "Meow"

def play_sounds(animals):
for animal in animals:
print(animal.make_sound())

# Example usage:
animals = [Dog(), Cat(), Animal(), Dog()]
play_sounds(animals)
6. Solutions!! # Create borrowed books
books = [
from datetime import datetime, timedelta create_borrowed_book("1984", "George Orwell", "Alice", 2),
create_borrowed_book("The Alchemist", "Paulo Coelho", "Bob", 5),
class Book: create_borrowed_book("Python Basics", "Zed Shaw", "Charlie", 1),
def __init__(self, title, author): ]
self.title = title
self.author = author # Filter books due in <= 3 days
due_soon = list(filter(lambda b: (b.due_date - datetime.now()).days <= 3,
class BorrowedBook(Book): books))
def __init__(self, title, author, borrower, due_date):
super().__init__(title, author) print("Books due soon:")
self.borrower = borrower for b in due_soon:
self.due_date = due_date print(b)

def __repr__(self):
return f"'{self.title}' borrowed by {self.borrower}, due {self.due_date.strftime('%Y-%m-%d')}"

# Function to create a book with defaults


def create_borrowed_book(title, author, borrower="Unknown", days_until_due=7):
due_date = datetime.now() + timedelta(days=days_until_due)
return BorrowedBook(title, author, borrower, due_date)
Problem 1 (Simplified): Grocery Bill Calculator
def calculate_total(name, base_items, discount=0, *extra_items):
# Combine base items and extra items into one list
all_items = base_items + list(extra_items)

# Calculate total price


total_price = 0
for price in all_items:
total_price += price

# Apply discount
final_price = total_price - (discount / 100) * total_price

# Show result
print(name + ", your total after discount is: $" + str(round(final_price,
2)))

# Example usage:
calculate_total("Alice", [10, 20], 10, 5, 5)
Problem 3 (Simplified): Top 3 Scores
def top_scores(students):
# Sort students by score using a simple function
def get_score(student):
return student[1]

students_sorted = sorted(students, key=get_score, reverse=True)

# Take top 3 names


top3 = students_sorted[:3]
top_names = []
for s in top3:
top_names.append(s[0])

return top_names

# Example usage:
students = [("Ana", 80), ("Ben", 90), ("Cara", 85), ("Dan", 88)]
print(top_scores(students))
Problem 6 (Simplified): Mini Library System
# We will use a simpler date method (number of days only)
class Book: books = [book1, book2, book3]
def __init__(self, title, author):
self.title = title # Show only books due in 3 or fewer days
self.author = author print("Books due soon:")
for book in books:
class BorrowedBook(Book): if book.days_until_due <= 3:
def __init__(self, title, author, borrower, days_until_due): book.display_info()
super().__init__(title, author)
self.borrower = borrower
self.days_until_due = days_until_due

def display_info(self):
print(self.title + " borrowed by " + self.borrower + ", due in " + str(self.days_until_due) + " days.")

# Create some borrowed books


book1 = BorrowedBook("1984", "George Orwell", "Alice", 2)
book2 = BorrowedBook("The Alchemist", "Paulo Coelho", "Bob", 5)
book3 = BorrowedBook("Python Basics", "Zed Shaw", "Charlie", 1)

You might also like