0% found this document useful (0 votes)
3 views16 pages

Python Functions

The document provides a comprehensive guide on Python functions, covering topics from defining functions to higher-order functions. It includes explanations, syntax, examples, and practice questions for each topic, ensuring a structured learning path. Key concepts include parameters, arguments, default values, and the use of lambda functions.

Uploaded by

sunshine19012004
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views16 pages

Python Functions

The document provides a comprehensive guide on Python functions, covering topics from defining functions to higher-order functions. It includes explanations, syntax, examples, and practice questions for each topic, ensuring a structured learning path. Key concepts include parameters, arguments, default values, and the use of lambda functions.

Uploaded by

sunshine19012004
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Functions

From basics to higher-order functions — with practice problems

Topics Covered Learning Order


Defining Functions 1. Defining Functions
Single & Multiple Parameters 2. Parameters (Single, Multiple)
Positional Arguments 3. Positional Arguments
Keyword Arguments 4. Keyword Arguments
Default Parameters 5. Default Parameters
*args & **kwargs 6. Arbitrary Parameters
Function References 7. Functional References
Lambda Functions 8. Lambda Functions
Higher-Order Functions 10. Higher-Order Functions

🔁 Learning Order Changed — The original list was reordered. Default parameters must
come before *args/**kwargs; lambda before higher-order functions (map/filter/reduce use
lambda heavily); recursion before higher-order functions for conceptual flow.
Section 1: Defining Functions
A function is a reusable block of code that performs a specific task. Instead of writing the same code
multiple times, you define it once and call it whenever you need it.
Functions make code cleaner, shorter, easier to debug, and easier to understand.

Syntax
def function_name(parameters):
# body of the function
return value # optional

Simple Example
def greet():
print("Hello, Student!")

greet() # Calling the function


# Output: Hello, Student!

💡 Key Rule — A function must be defined (with def) before it is called. Python reads
code top-to-bottom, so calling before defining causes a NameError.

The return Statement


return sends a value back to the caller. Without it, the function returns None by default.
def square(n):
return n * n

result = square(5)
print(result) # 25

✏️ Practice Questions — Section 1: Defining Functions


Q1. Write a function called say_hello() that prints 'Welcome to Python!'

Q2. Write a function called add(a, b) that returns the sum of two numbers.

Q3. What is the output of a function that has no return statement? Write a function to verify
this.

Q4. Write a function area_of_rectangle(length, width) that returns length * width. Call it with
values 6 and 4.

Q5. Explain in your own words: why do we use functions instead of writing code directly?
Section 2: Single & Multiple Parameters
Parameters are the variables listed inside the parentheses in the function definition. Arguments are the
actual values you pass when calling the function.

Single Parameter
def greet(name):
print("Hello, " + name + "!")

greet("Alice") # Hello, Alice!


greet("Bob") # Hello, Bob!

Multiple Parameters
You can define as many parameters as you need, separated by commas.
def add(a, b):
return a + b

def student_info(name, age, grade):


print(f"Name: {name}, Age: {age}, Grade: {grade}")

student_info("Alice", 20, "A")


# Name: Alice, Age: 20, Grade: A

💡 Parameter vs Argument — Parameter = variable in definition (name, age). Argument


= actual value passed (Alice, 20). They are often used interchangeably, but the distinction
matters.

✏️ Practice Questions — Section 2: Parameters


Q1. Write a function multiply(a, b, c) that returns the product of three numbers.

Q2. Create a function describe_pet(animal, name) that prints: 'My [animal] is named
[name].'

Q3. What happens if you call a function with fewer arguments than parameters? Try it and
note the error.

Q4. Write a function power(base, exponent) that returns base raised to exponent using the
** operator.

Q5. Create a function full_name(first, middle, last) that returns the full name as a single
string.
Section 3: Positional Arguments
When you call a function and pass values without specifying parameter names, Python assigns them in
order — left to right. These are called positional arguments.

Order Matters!
def describe(color, size, shape):
print(f"A {color} {size} {shape}")

describe("red", "large", "circle")


# A red large circle

describe("circle", "red", "large") # WRONG ORDER!


# A circle red large ← not what we wanted

⚠️ Warning — With positional arguments, order is everything. The first argument always
maps to the first parameter, the second to the second, and so on.

Practical Example
def divide(numerator, denominator):
return numerator / denominator

print(divide(10, 2)) # 5.0 (10 ÷ 2)


print(divide(2, 10)) # 0.2 (2 ÷ 10) ← different result!

✏️ Practice Questions — Section 3: Positional Arguments


Q1. Write a function intro(name, city, hobby) that prints a sentence about a person. Call it
in two different orders and observe the difference.

Q2. Create subtract(a, b) that returns a - b. What is the difference between subtract(10, 3)
and subtract(3, 10)?

Q3. What does 'positional' mean in 'positional arguments'? Write it in your own words.

Q4. Write a function bio(first_name, last_name, age) and call it correctly using positional
arguments.

Q5. Can you pass more positional arguments than there are parameters? What error do
you get?
Section 4: Keyword Arguments
Keyword arguments let you pass arguments by explicitly naming the parameter. This means ORDER
doesn't matter — Python matches by name instead of position.

Syntax
function_name(parameter_name=value)

Example
def describe(color, size, shape):
print(f"A {color} {size} {shape}")

describe(shape="circle", color="red", size="large")


# A red large circle ← correct even though order is different!

Mixing Positional and Keyword


You can mix both — but positional arguments MUST come before keyword arguments.
def register(name, age, country):
print(f"{name}, {age}, from {country}")

register("Alice", age=21, country="India") # ✅ valid


register(name="Alice", 21, "India") # ❌ SyntaxError!

Positional Arguments Keyword Arguments


Positional Keyword
Based on order Based on name
Can be confusing for many params Self-documenting and clear
f(10, 20, 30) f(a=10, b=20, c=30)

✏️ Practice Questions — Section 4: Keyword Arguments


Q1. Call the function send_email(to, subject, body) using keyword arguments in any order.

Q2. Write a function create_profile(username, email, age) and call it using keyword
arguments.

Q3. What is the error if you place a positional argument after a keyword argument? Test it.

Q4. Rewrite this call using keyword arguments: book_ticket('Alice', 'Delhi', 'Mumbai', 2)

Q5. Why are keyword arguments considered more readable? Write an example that
demonstrates this clearly.
Section 5: Default Parameters
Default parameters allow you to give a parameter a default value. If the caller does not provide an
argument for that parameter, the default is used automatically.

Syntax
def function_name(param=default_value):

Example
def greet(name, message='Hello'):
print(f"{message}, {name}!")

greet("Alice") # Hello, Alice! (default used)


greet("Bob", "Good morning") # Good morning, Bob! (override)

Real-World Example
def create_account(username, role='student', active=True):
print(f"User: {username}, Role: {role}, Active: {active}")

create_account("alice123")
# User: alice123, Role: student, Active: True

create_account("admin99", role="admin")
# User: admin99, Role: admin, Active: True

⚠️ Important Rule — Non-default parameters must come BEFORE default parameters.


def func(a=1, b) is a SyntaxError. Correct: def func(b, a=1)

💡 Common Use Case — Default parameters are perfect for optional settings — like
page size, currency, language, or country code — that have a common value but can be
overridden.

✏️ Practice Questions — Section 5: Default Parameters


Q1. Write a function power(base, exponent=2) that returns base^exponent. Test with one
and two arguments.

Q2. Create a function connect(host, port=3306, protocol='TCP') and call it with various
combinations.

Q3. What is the SyntaxError in: def func(name='Guest', age)? Fix it.
Q4. Write a function discount_price(price, discount=10) that returns the discounted price.
Test with and without the discount argument.

Q5. Why would you use a default parameter instead of just hardcoding a value inside the
function? Explain with an example.

Section 6: Arbitrary Parameters (*args, **kwargs)


Sometimes you don't know in advance how many arguments a function will receive. Python provides
two special syntaxes to handle this: *args for any number of positional arguments, and **kwargs for any
number of keyword arguments.

*args — Arbitrary Positional Arguments


*args collects all extra positional arguments into a tuple. You can use any name but * is what matters;
args is just convention.
def add_all(*args):
total = 0
for num in args:
total += num
return total

print(add_all(1, 2, 3)) # 6
print(add_all(10, 20, 30, 40)) # 100
print(add_all(5)) # 5

**kwargs — Arbitrary Keyword Arguments


**kwargs collects all extra keyword arguments into a dictionary. Use any name but ** is what matters;
kwargs is just convention.
def print_info(**kwargs):
for key, value in [Link]():
print(f"{key}: {value}")

print_info(name="Alice", age=21, city="Hyderabad")


# name: Alice
# age: 21
# city: Hyderabad

Combining All Parameter Types


The correct order when combining all types is: regular → *args → keyword-only → **kwargs
def full_example(a, b, *args, option='default', **kwargs):
print(a, b, args, option, kwargs)

full_example(1, 2, 3, 4, 5, option="custom", x=10, y=20)


# 1 2 (3, 4, 5) custom {'x': 10, 'y': 20}
Type Syntax Collects into Example Call
Regular param def f(a, b) Individual variables f(1, 2)
*args def f(*args) Tuple f(1, 2, 3, 4)
**kwargs def f(**kwargs) Dictionary f(x=1, y=2)
Combined def f(a, *args, **kwargs) All three f(1, 2, 3, x=4)

✏️ Practice Questions — Section 6: *args and **kwargs


Q1. Write a function multiply_all(*args) that returns the product of all numbers passed.

Q2. Create a function display_tags(**kwargs) that prints each keyword-value pair on its
own line.

Q3. Write a function describe_person(name, *hobbies) where name is a regular param and
hobbies are collected into a tuple.

Q4. What is the output of: def f(*args): print(type(args)) → f(1, 2, 3)? Explain why.

Q5. Write a function create_html_tag(tag, **attributes) that prints: <tag key='val' ...>.
Example: create_html_tag('a', href='[Link] target='_blank')

Q6. Write a function mixed(a, b, *args, **kwargs) and call it with at least 6 arguments. Print
each part.
Section 7: Functional References
In Python, functions are first-class objects. This means functions can be:
▸ Assigned to a variable
▸ Passed as an argument to another function
▸ Returned from another function
▸ Stored in a list, dict, or other data structure

Assigning a Function to a Variable


def greet(name):
return f"Hello, {name}!"

say_hello = greet # No () — we store the function itself, not its


result
print(say_hello("Alice")) # Hello, Alice!

Passing a Function as an Argument


def apply(func, value):
return func(value)

def double(x):
return x * 2

def square(x):
return x * x

print(apply(double, 5)) # 10
print(apply(square, 5)) # 25

Storing Functions in a Dictionary


def add(a, b): return a + b
def sub(a, b): return a - b
def mul(a, b): return a * b

operations = {
'+': add,
'-': sub,
'*': mul,
}

op = '+'
print(operations[op](10, 5)) # 15

💡 Why This Matters — Function references are the foundation for callbacks, event
handlers, decorators, and all higher-order functions you'll learn next.
✏️ Practice Questions — Section 7: Functional References
Q1. Assign the built-in function len to a variable called count. Use it to find the length of a
list.

Q2. Write a function run_twice(func, value) that calls func on value twice and returns the
final result.

Q3. Store the functions upper, lower, and title (string methods) in a dictionary. Let the user
choose which one to apply.

Q4. Write a function that returns another function. Example: make_multiplier(3) should
return a function that multiplies any number by 3.

Q5. Can you store the same function under multiple names in a dictionary? Test it and
explain what happens.
Section 8: Lambda Functions
A lambda is a small, anonymous (unnamed) function written in a single line. It's useful for short,
throwaway operations — especially when passing a function as an argument.

Syntax
lambda parameters: expression

Regular vs Lambda
Regular Function Lambda Equivalent
def square(x): square = lambda x: x * x
return x * x

square(5) # 25 square(5) # 25

Lambda with Multiple Parameters


add = lambda a, b: a + b
print(add(3, 4)) # 7

full_name = lambda first, last: first + ' ' + last


print(full_name("Ada", "Lovelace")) # Ada Lovelace

Lambda Used Inline (Most Common Usage)


Lambdas are most powerful when used directly inside function calls:
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
[Link](key=lambda x: x) # Sort ascending
print(numbers) # [1, 1, 2, 3, 4, 5, 6, 9]

students = [('Alice', 85), ('Bob', 92), ('Carol', 78)]


[Link](key=lambda s: s[1]) # Sort by score
print(students) # [('Carol', 78), ('Alice', 85), ('Bob', 92)]

⚠️ Lambda Limitations — Lambda can only have ONE expression (no statements, no
multiple lines, no assignments inside it). For anything complex, use a regular def function.
✏️ Practice Questions — Section 8: Lambda
Q1. Write a lambda function that takes a number and returns its cube.

Q2. Create a lambda that takes two numbers and returns the larger one using a conditional
expression (x if x > y else y).

Q3. Convert this regular function into a lambda: def even(n): return n % 2 == 0

Q4. Use a lambda with .sort() to sort this list of tuples by the second element:
[(1,'banana'),(2,'apple'),(3,'cherry')]

Q5. Can a lambda function call another function inside it? Write an example.

Q6. What are the three main limitations of lambda compared to def? List them.

Section 9: Higher-Order Functions


A higher-order function is any function that takes another function as an argument OR returns a
function. Python has four built-in higher-order functions you'll use constantly:
▸ map() — Apply a function to every element of an iterable
▸ filter() — Keep only elements where a function returns True
▸ reduce() — Combine all elements into a single value (from functools)
▸ sorted() — Sort any iterable using a custom key function

map() — Transform Every Element


map(function, iterable) applies function to each element and returns a map object (convert to list to see
it).
numbers = [1, 2, 3, 4, 5]

# Using a regular function


def double(x): return x * 2
result = list(map(double, numbers))
print(result) # [2, 4, 6, 8, 10]

# Using lambda (most common)


result = list(map(lambda x: x ** 2, numbers))
print(result) # [1, 4, 9, 16, 25]

# map with multiple iterables


a = [1, 2, 3]
b = [10, 20, 30]
result = list(map(lambda x, y: x + y, a, b))
print(result) # [11, 22, 33]
filter() — Keep What Passes the Test
filter(function, iterable) keeps only elements for which function returns True.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Keep only even numbers


evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4, 6, 8, 10]

# Keep only words longer than 4 characters


words = ['cat', 'elephant', 'dog', 'python', 'ant']
long_words = list(filter(lambda w: len(w) > 4, words))
print(long_words) # ['elephant', 'python']

reduce() — Combine into One Value


reduce(function, iterable) applies function cumulatively — the result of each step becomes the first
argument of the next step.
from functools import reduce

numbers = [1, 2, 3, 4, 5]

# Sum all numbers: ((((1+2)+3)+4)+5) = 15


total = reduce(lambda a, b: a + b, numbers)
print(total) # 15

# Find the maximum


maximum = reduce(lambda a, b: a if a > b else b, numbers)
print(maximum) # 5

# Flatten: combine strings


words = ['Hello', ' ', 'World', '!']
sentence = reduce(lambda a, b: a + b, words)
print(sentence) # Hello World!

sorted() — Sort with Custom Logic


sorted(iterable, key=function, reverse=False) returns a new sorted list. The key function determines
what value to sort by.
students = [
{'name': 'Alice', 'score': 85},
{'name': 'Bob', 'score': 92},
{'name': 'Carol', 'score': 78},
]

# Sort by score ascending


by_score = sorted(students, key=lambda s: s['score'])
# [Carol:78, Alice:85, Bob:92]

# Sort by score descending


top = sorted(students, key=lambda s: s['score'], reverse=True)
# [Bob:92, Alice:85, Carol:78]

# Sort strings by length


words = ['banana', 'fig', 'apple', 'kiwi']
print(sorted(words, key=len))
# ['fig', 'kiwi', 'apple', 'banana']

Function Purpose Returns Needs


import?
map(fn, iter) Apply fn to every element map object → use No
list()
filter(fn, iter) Keep elements where fn is filter object → use No
True list()
reduce(fn, iter) Combine all elements into Single value Yes (functools)
one
sorted(iter, Sort using custom key New sorted list No
key=fn)

✏️ Practice Questions — Section 9: Higher-Order Functions


Q1. Use map() to convert a list of temperatures in Celsius to Fahrenheit. Formula: F = (C ×
9/5) + 32

Q2. Use filter() to extract all words from a list that start with a capital letter.

Q3. Use reduce() to find the product of all numbers in a list: [1, 2, 3, 4, 5] → 120

Q4. Sort a list of tuples (name, age) by age in descending order using sorted() with a
lambda key.

Q5. Chain map() and filter(): from [1..10], first filter out odds, then square the remaining
evens.

Q6. Write your own version of map() called my_map(func, lst) using a regular loop. Verify it
gives the same results as the built-in.

Q7. Use reduce() to find the longest string in a list: ['cat', 'elephant', 'dog', 'rhinoceros']
Final Challenge: Mixed Concept Questions

These questions combine multiple topics from all sections.

Part A — Predict the Output

Read each code snippet carefully. Predict what will be printed WITHOUT running it first. Then verify.

1. What does this print?


def mystery(*args, **kwargs):
print(sum(args), list([Link]()))
mystery(1, 2, 3, a=4, b=5)

2. Trace the output:


def f(n):
if n == 0: return 0
return n + f(n - 1)
print(f(4))

3. What is result?
from functools import reduce
data = [2, 3, 4]
result = reduce(lambda a, b: a * b, list(map(lambda x: x + 1, data)))
print(result)

Part B — Build the Function

Write complete working Python code for each challenge below.

✏️ Mixed Concept Challenges


Q1. PARAMETERS + LAMBDA: Write a function apply_operation(a, b, op) where op is a
lambda. Call it with operations for add, subtract, and multiply.

Q2. *args + RECURSION: Write a recursive function that takes *args of numbers and
returns their sum WITHOUT using the built-in sum().

Q3. DEFAULT + KEYWORD + LAMBDA: Write a function make_greeting(name,


prefix='Hello', formatter=lambda x: x) that applies formatter to the final greeting string. Test
with [Link] as the formatter.

Q4. map() + filter() + lambda: Given a list of integers from 1 to 20, use filter() to keep
multiples of 3, then use map() to square them. Print the result.
Q5. FUNCTION REFERENCE + HIGHER ORDER: Create a list of lambda functions
[double, triple, quadruple]. Write a function apply_all(funcs, value) that applies each in
sequence and returns the final result.

Q6. RECURSION + DEFAULT PARAMETER: Write a recursive function flatten(lst,


depth=1) that flattens a nested list up to the given depth. Example: flatten([[1,[2]],3],
depth=2) → [1, 2, 3]

Q7. **kwargs + reduce(): Write a function weighted_average(**scores) where keys are


subjects and values are scores. Use reduce() to compute the average of all values.

Q8. FULL PIPELINE: Build a mini data pipeline. Start with a list of student dictionaries
[{name, score}]. Use filter() to keep scores >= 60, map() to add a 'grade' key ('Pass'), and
sorted() to sort by score descending. Print the final result.

Q9. LAMBDA + sorted() + FUNCTION REFERENCE: Store three sort strategies in a


dictionary: by_name, by_score, by_length. Let the user choose a strategy by name, then
apply it to sort a list of tuples.

Q10. ALL CONCEPTS: Write a function calculator(*args, operation='add', **options) that:


(a) uses *args to collect numbers, (b) uses a default 'add' operation, (c) supports
operations: 'add', 'multiply', 'max', 'min' using a dict of lambda functions, (d) if options
contains show_steps=True, prints each step of the calculation.

Complete Topic Reference


Topic Syntax Key Point
def / return def f(x): return x Foundation of all functions
Single param def f(a): One required argument
Multiple params def f(a, b, c): Order matters positionally
Positional args f(1, 2, 3) Matched left-to-right by position
Keyword args f(a=1, b=2) Matched by name, any order
Default params def f(a, b=10): Defaults at the end only
*args def f(*args): Collects extras into a tuple
**kwargs def f(**kwargs): Collects keyword extras into a dict
Func reference fn = other_fn Functions are objects — pass them around
Lambda lambda x: x*2 One-line anonymous function
map() map(fn, iter) Transform every element
filter() filter(fn, iter) Keep elements where fn is True
reduce() reduce(fn, iter) Combine all into one value
sorted() sorted(iter, Sort with custom key function
key=fn)

You might also like