Python Functions Tutorial¶
1. Function Definition, Parameters, and Return Statements¶
- Functions are defined using the
def
keyword. - Parameters are inputs to functions.
return
sends back a result from the function.
In [ ]:
Copied!
def greet(name):
greeting_sentence = f"Hello, {name}!"
return greeting_sentence
greeting_sentence = greet("Alice")
print(greeting_sentence)
def greet(name):
greeting_sentence = f"Hello, {name}!"
return greeting_sentence
greeting_sentence = greet("Alice")
print(greeting_sentence)
Hello, Alice!
In [4]:
Copied!
def is_even(n):
if n % 2 == 0:
return True
else:
return False
number = 5
is_even(number)
def is_even(n):
if n % 2 == 0:
return True
else:
return False
number = 5
is_even(number)
Out[4]:
False
In [5]:
Copied!
def sqaure_cube(number_list):
print(number_list)
num_list = [1, 2, 6, 5, 8, 2]
sqaure_cube(num_list)
def sqaure_cube(number_list):
print(number_list)
num_list = [1, 2, 6, 5, 8, 2]
sqaure_cube(num_list)
[1, 2, 6, 5, 8, 2]
Exercise 1¶
Q1 : Write a function area_of_rectangle(length, width) that returns the area of a rectangle.¶
Q2 : Create a function is_even(number) that returns True if the number is even, otherwise False.¶
Q3 : Create a function that takes a list of number as parameter, and return the list with sqaure of even numbers and cube of odd numbers. The order of number should be preserved.¶
Input : [5, 3, 6, 7, 1, 2]
Output : [125, 27, 36, 343, 1, 4]
Q4 : Write a Python function that takes a list of words as input and returns a dictionary showing how many times each word appears in the list.¶
Input :
words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
Output :
{'apple': 3, 'banana': 2, 'orange': 1}
Q5 : Write a Python function that calculates the average grade for each student given a dictionary of their scores.¶
Hint : sum([1, 2, 3]) provides sum of a list
input :
grades = {
'Alice': [85, 90, 78],
'Bob': [70, 80, 65],
'Charlie': [100, 95, 90]
}
output :
{
'Alice': 84.33,
'Bob': 71.67,
'Charlie': 95.0
}
In [ ]:
Copied!
grades_dictionary = {
'Alice': [85, 90, 78],
'Bob': [70, 80, 65],
'Charlie': [100, 95, 90]
}
output_dictionary = {}
for grade in grades_dictionary.items():
student_name, students_grades = grade
student_average_grade = sum(students_grades) / len(students_grades)
output_dictionary[student_name] = student_average_grade
print(output_dictionary)
grades_dictionary = {
'Alice': [85, 90, 78],
'Bob': [70, 80, 65],
'Charlie': [100, 95, 90]
}
output_dictionary = {}
for grade in grades_dictionary.items():
student_name, students_grades = grade
student_average_grade = sum(students_grades) / len(students_grades)
output_dictionary[student_name] = student_average_grade
print(output_dictionary)
{'Alice': 84.33333333333333, 'Bob': 71.66666666666667, 'Charlie': 95.0}
In [11]:
Copied!
def averageGrades(grades_dictionary):
output_dictionary = {}
for grade in grades_dictionary.items():
student_name, students_grades = grade
student_average_grade = sum(students_grades) / len(students_grades)
output_dictionary[student_name] = student_average_grade
return output_dictionary
def averageGrades(grades_dictionary):
output_dictionary = {}
for grade in grades_dictionary.items():
student_name, students_grades = grade
student_average_grade = sum(students_grades) / len(students_grades)
output_dictionary[student_name] = student_average_grade
return output_dictionary
In [13]:
Copied!
grades_dictionary = {
'Alice': [85, 90, 78],
'Bob': [70, 80, 65],
'Charlie': [100, 95, 90]
}
average_grades_dictionary = averageGrades(grades_dictionary)
print(average_grades_dictionary)
grades_dictionary = {
'Alice': [85, 90, 78],
'Bob': [70, 80, 65],
'Charlie': [100, 95, 90]
}
average_grades_dictionary = averageGrades(grades_dictionary)
print(average_grades_dictionary)
{'Alice': 84.33333333333333, 'Bob': 71.66666666666667, 'Charlie': 95.0}
In [ ]:
Copied!
In [ ]:
Copied!
In [5]:
Copied!
def wordCounter(words):
output_dictionary = {}
for w in words:
if w not in output_dictionary.keys():
output_dictionary[w] = 1
else:
output_dictionary[w] = output_dictionary[w] + 1
return output_dictionary
def wordCounter(words):
output_dictionary = {}
for w in words:
if w not in output_dictionary.keys():
output_dictionary[w] = 1
else:
output_dictionary[w] = output_dictionary[w] + 1
return output_dictionary
In [6]:
Copied!
words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
counter_dictionary = wordCounter(words)
print(counter_dictionary)
words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
counter_dictionary = wordCounter(words)
print(counter_dictionary)
{'apple': 3, 'banana': 2, 'orange': 1}
2. Default Parameters, Keyword Arguments, and Docstrings¶
- Default parameters are used when an argument is not passed.
- Keyword arguments allow passing parameters by name.
- Docstrings are string literals used to describe functions.
In [ ]:
Copied!
'''
this is a
multiline
string
'''
'''
this is a
multiline
string
'''
In [ ]:
Copied!
def power(base, exponent=2):
'''
base is raised to the power of exponent
Input:
base :
exponent:
Output:
base ** exponent is the output of the function
'''
return base ** exponent
print(power(3))
power(2, 3)
outup_number = power(
base = 10,
exponent=2
)
print(outup_number)
def power(base, exponent=2):
'''
base is raised to the power of exponent
Input:
base :
exponent:
Output:
base ** exponent is the output of the function
'''
return base ** exponent
print(power(3))
power(2, 3)
outup_number = power(
base = 10,
exponent=2
)
print(outup_number)
9 100
In [28]:
Copied!
help(power)
help(power)
Help on function power in module __main__: power(base, exponent=2) base is raised to the power of exponent Input: base : exponent: Output: base ** exponent is the output of the function
In [ ]:
Copied!
print(power.__doc__)
print(power.__doc__)
In [3]:
Copied!
help(power)
help(power)
Help on function power in module __main__: power(base, exponent=2) Returns the base raised to the power of exponent.
In [30]:
Copied!
def greet(name, message = 'Welcome!'):
greeting_sentence = f'{message} {name}'
print(greeting_sentence)
greet('Alice')
greet('Charlie', message = 'Thank You!')
def greet(name, message = 'Welcome!'):
greeting_sentence = f'{message} {name}'
print(greeting_sentence)
greet('Alice')
greet('Charlie', message = 'Thank You!')
Welcome! Alice Thank You! Charlie
3. *args and **kwargs¶
*args
allows variable number of positional arguments.**kwargs
allows variable number of keyword arguments.
In [31]:
Copied!
def tempFunction1(*args):
print(args)
print(type(args))
tempFunction1(1, 2, 4, 5, 'Hello')
def tempFunction1(*args):
print(args)
print(type(args))
tempFunction1(1, 2, 4, 5, 'Hello')
(1, 2, 4, 5, 'Hello') <class 'tuple'>
In [8]:
Copied!
def tempFunction2(**kwargs):
print(kwargs)
print(kwargs['name'])
tempFunction2(name = 'nirajan', location = 'bkt')
def tempFunction2(**kwargs):
print(kwargs)
print(kwargs['name'])
tempFunction2(name = 'nirajan', location = 'bkt')
{'name': 'nirajan', 'location': 'bkt'} nirajan
In [4]:
Copied!
def show_args(*args, **kwargs):
print("Positional arguments:", args)
print("Keyword arguments:", kwargs)
show_args(1, 2, 3, name="Alice", age=25)
def show_args(*args, **kwargs):
print("Positional arguments:", args)
print("Keyword arguments:", kwargs)
show_args(1, 2, 3, name="Alice", age=25)
Positional arguments: (1, 2, 3) Keyword arguments: {'name': 'Alice', 'age': 25}
In [20]:
Copied!
def func3(a, *args, **kwargs):
print(a)
print(args)
print(kwargs)
func3(1, 'apple', 'mango', fruit = 'grapes', city = 'pokhara')
def func3(a, *args, **kwargs):
print(a)
print(args)
print(kwargs)
func3(1, 'apple', 'mango', fruit = 'grapes', city = 'pokhara')
1 ('apple', 'mango') {'fruit': 'grapes', 'city': 'pokhara'}
In [32]:
Copied!
def sum_all(*numbers):
print(sum(numbers))
sum_all(1, 2, 3, 5, 2, 3)
def sum_all(*numbers):
print(sum(numbers))
sum_all(1, 2, 3, 5, 2, 3)
16
Exercise¶
Q5 : Write a function sum_all(*numbers) that returns the sum of all arguments passed to it.¶
Q6 : Create a function print_student_details(**details) that prints each key-value pair passed as keyword arguments.¶
Hint: Use dict.items() function
Function call:
print_student_details(name="Sita", age=20, grade="A", address="Kathmandu")
Output:
name: Sita
age: 20
grade: A
address: Janakpur
4. Scope: Local, Global, and Nonlocal¶
- Local: Defined inside a function.
- Global: Defined at the top level.
In [39]:
Copied!
x = 10
x = 10
In [41]:
Copied!
def func2():
global x
print(x)
func2()
def func2():
global x
print(x)
func2()
10
In [38]:
Copied!
def func1():
x = 20
print('inside function : ', x)
func1()
print('outside function : ', x)
def func1():
x = 20
print('inside function : ', x)
func1()
print('outside function : ', x)
inside function : 20 outside function : 10
In [ ]:
Copied!
In [ ]:
Copied!
In [ ]:
Copied!
In [ ]:
Copied!
In [4]:
Copied!
x = 'this is a global variable'
def func1():
x = 'this is a local variable'
print(x) ## --> local variable
func1()
print(x) # --> global variable
x = 'this is a global variable'
def func1():
x = 'this is a local variable'
print(x) ## --> local variable
func1()
print(x) # --> global variable
this is a local variable this is a global variable
5. Methods vs. Functions¶
- Functions are defined using
def
and are independent. - Methods are functions associated with objects (e.g., strings, lists).
In [ ]:
Copied!
# Function
def add(a, b):
return a + b
# Method (associated with string object)
text = "hello"
print(text.upper())
print(add(5, 10))
# Function
def add(a, b):
return a + b
# Method (associated with string object)
text = "hello"
print(text.upper())
print(add(5, 10))
In [42]:
Copied!
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
intersection_list = []
for number in list1:
if number in list2:
intersection_list.append(number)
print(intersection_list)
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
intersection_list = []
for number in list1:
if number in list2:
intersection_list.append(number)
print(intersection_list)
[4, 5]
Problem Solving Exercise¶
Q7: Common Elements Between Two Lists¶
Write a function common_elements(list1, list2) that returns a list of elements common to both lists.
Q8: Second Largest Element¶
Write a function second_largest(lst) that returns the second largest number in a list.
Q9: Rotate List Elements¶
Write a function rotate_list(lst, k) that rotates the list k steps to the right.
Input:
lst = [1, 2, 3, 4, 5, 6, 7]
k = 3
Output:
[5, 6, 7, 1, 2, 3, 4]
In [ ]:
Copied!
lst = [1, 2, 3, 4, 5, 6, 7]
k = 3
lst = [1, 2, 3, 4, 5, 6, 7]
k = 3
Out[ ]:
['mango', 'apple']
In [ ]:
Copied!