Lecture 6 – Functions in Python (def, parameters, return, scope)

Learn Python functions in Lecture 6 with simple explanations and practical examples. Understand def, parameters, arguments, return values, *args, **kwargs, and real Data Science use-cases. Includes MCQs and practice tasks.

What You Will Learn in This Lecture

By the end, you will understand:

What functions are
Why functions are used
def keyword
Parameters vs Arguments
Return values
Multiple return values
Default parameters
Keyword arguments
Variable-length arguments (*args, **kwargs)
Function scope (local vs global variables)
Real data science use-cases
MCQs + practice tasks

1) What Is a Function?

A function is a reusable block of code that performs a specific task.

Real-life examples of functions:

  • A washing machine → washes clothes
  • A calculator → adds numbers
  • A coffee machine → makes coffee

In Python, a function works the same way.

defining-functions

2) Creating a Function Using def

Basic structure:
def function_name():
    # code
Example 1 – Simple Function
def greet():
    print("Hello, welcome to ElecturesAI!")

Call it:

greet()
Example 2 – Function with 1 parameter
def welcome(name):
    print("Hello", name)

Call:

welcome("ElecturesAI")

3) Parameters vs Arguments

TermMeaning
ParameterVariable in function definition
ArgumentValue passed when calling function
Example:
def add(a, b):   # a and b are parameters
    return a + b

add(5, 7)        # 5 and 7 are arguments

4) return Statement (VERY IMPORTANT)

The return keyword gives back a value.

Example 1
def square(n):
    return n * n
Example 2 – Return multiple values
def operations(x, y):
    return x + y, x - y, x * y

a, b, c = operations(10, 5)
print(a, b, c)

5) Default Parameters

Used when you want optional arguments.

Example
def greet(name="Student"):
    print("Hello", name)

Call:

greet()
greet("Tahir")

Lecture 5 – Loops

6) Keyword Arguments

Call function using parameter names.

Example
def info(name, age):
    print(name, "is", age, "years old")

info(age=21, name="Sara")

7) *args Multiple Positional Arguments

Example
def total(*numbers):
    return sum(numbers)

print(total(2, 5, 7, 8))

8) **kwargs Multiple Keyword Arguments

Example
def student_info(**data):
    for key, value in data.items():
        print(key, ":", value)

student_info(name="Ali", age=21, grade="A")

9) Local vs Global Variables

Example
x = 10   # global

def test():
    x = 5   # local
    print("Inside:", x)

test()
print("Outside:", x)

10) Real Data Science Examples

Example 1 – Cleaning a dataset value
def clean(value):
    if value == "N/A":
        return None
    return int(value)

print(clean("90"))
print(clean("N/A"))
Example 2 – Calculate BMI
def bmi(weight, height):
    return weight / (height ** 2)

print(bmi(70, 1.75))

Example 3 – Normalize a value (min-max scaling)
def normalize(value, min_v, max_v):
    return (value - min_v) / (max_v - max_v)

print(normalize(45, 0, 100))
Example 4 – Predict category based on threshold
def classify(score):
    if score >= 90:
        return "Excellent"
    elif score >= 70:
        return "Good"
    else:
        return "Average"

print(classify(85))
Example 5 – Function returning dictionary
def record(name, marks):
    return {"name": name, "marks": marks}

student = record("Talha", 95)
print(student)

Quiz – Test Your Understanding
Instruction: First read the question and choose your answer. Then scroll down to see the correct answer

What keyword defines a function?

a) func
b) def
c) define
d) fn

Answer: b) def

Next Lecture – Lambda, Map, Filter, Reduce (Lecture 7)

What does this print?

def test(a):
    return a * 2

print(test(5))

Answer: 10

*args allows you to:

a) return multiple values
b) take multiple arguments
c) take multiple keyword arguments
d) repeat a loop

Answer: b) take multiple arguments

What is the output?

x = 10
def show():
    x = 7
    print(x)
show()
print(x)

Answer:

7
10

Practice Questions
Instruction for students: Read the question, open your Jupyter Notebook, and try to solve it yourself. After that, come back and check the answer.

Create a function to find the largest of 3 numbers.
def largest(a, b, c):
    return max(a, b, c)
Create a function that calculates the average of a list.
def average(nums):
    return sum(nums) / len(nums)

print(average([10, 20, 30]))
Create a function that counts vowels in a string.
def vowels(text):
    count = 0
    for ch in text:
        if ch.lower() in "aeiou":
            count += 1
    return count
Create a function that returns even numbers from a list.
def evens(nums):
    return [x for x in nums if x % 2 == 0]

print(evens([1,2,3,4,5,6]))
A function that converts Celsius → Fahrenheit.
def c_to_f(c):
    return (c * 9/5) + 32

Leave a Reply

Your email address will not be published. Required fields are marked *