python_Lec-3
python_Lec-3
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.
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.
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.
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)
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 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
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)
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
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
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
# 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: [("Ana", 80), ("Ben", 90), ("Cara", 85), ("Dan", 88)] → Output: ["Ben", "Dan", "Cara"]
# 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 show_balance(self):
print(f"{self.name}'s current balance is ${self.balance}")
class Animal:
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')}"
# 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]
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.")