Module Contents
1. Functions2. Parameters3. Return Values4. Scope5. Argument Patterns6. Best Practices7. Lambda8. Recursion9. WorkflowCoding PracticeTheory Q&A1. Introduction to Functions
A function is a reusable block of code designed to perform a specific task. Functions make programs easier to organize, test, reuse and maintain.
1.1 Why Functions?
- Avoid repeating the same code.
- Break large programs into smaller tasks.
- Improve readability and debugging.
- Reuse the same logic with different inputs.
1.2 Defining and Calling a Function
def greet():
print("Hello, Python!")
greet()
defstarts the definition.greetis the function name.- Parentheses hold parameters when needed.
- The indented block is the function body.
greet()calls the function.
1.3 Function Execution
def message():
print("Welcome")
print("Before")
message()
print("After")
Defining a function does not execute its body. The body runs when the function is called.
2. Parameters and Arguments
Parameters are variables in a function definition. Arguments are actual values supplied during the call.
2.1 One and Multiple Parameters
def greet(name):
print("Hello", name)
greet("Ravi")
def add(a, b):
return a + b
print(add(10, 20))
2.2 Positional Arguments
def student(name, age):
print(name, age)
student("Ravi", 22)
Arguments are matched according to their position.
2.3 Keyword Arguments
def student(name, age):
print(name, age)
student(age=22, name="Ravi")
2.4 Default Parameters
def greet(name="Student"):
print("Hello", name)
greet()
greet("Anu")
2.5 *args
def total(*numbers):
return sum(numbers)
print(total(10, 20, 30, 40))
*args collects extra positional arguments into a tuple.
2.6 **kwargs
def show_profile(**details):
for key, value in details.items():
print(key, value)
show_profile(name="Ravi", age=22, city="Hyderabad")
**kwargs collects extra keyword arguments into a dictionary.
3. Return Values
return sends a result back to the caller and immediately ends that function execution.
3.1 print() vs return
def add_print(a, b):
print(a + b)
def add_return(a, b):
return a + b
result = add_return(10, 20)
print(result)
print() displays information; return creates a reusable result.
3.2 Returning Multiple Values
def calculate(a, b):
return a + b, a - b, a * b
s, d, p = calculate(10, 5)
print(s, d, p)
Multiple returned values are commonly packed into a tuple.
3.3 Early Return
def check_age(age):
if age < 18:
return "Minor"
return "Adult"
print(check_age(20))
3.4 No Explicit Return
def hello():
print("Hello")
result = hello()
print(result) # None
4. Scope of Variables
Scope determines where a variable name can be accessed.
4.1 Local Variable
def show():
x = 10
print(x)
show()
# print(x) # NameError
4.2 Global Variable
x = 100
def show():
print(x)
show()
4.3 Local vs Global with Same Name
x = 100
def test():
x = 50
print("Inside:", x)
test()
print("Outside:", x)
The local variable shadows the global variable inside the function.
4.4 global Keyword
count = 0
def increment():
global count
count += 1
increment()
print(count)
4.5 LEGB Rule
Python generally searches for names in this order: Local → Enclosing → Global → Built-in.
4.6 nonlocal Keyword
def outer():
x = 10
def inner():
nonlocal x
x += 5
inner()
print(x)
outer()
5. Practical Argument Patterns
5.1 Passing a List
def total_marks(marks):
return sum(marks)
print(total_marks([80, 90, 85]))
5.2 Passing a Dictionary
def show_student(student):
print(student["name"])
print(student["marks"])
show_student({"name": "Ravi", "marks": 90})
5.3 Mutable Arguments
def add_item(items):
items.append("Python")
skills = ["SQL"]
add_item(skills)
print(skills)
Mutable objects such as lists can be changed by operations performed inside a function.
6. Function Design and Best Practices
6.1 One Main Responsibility
def calculate_average(marks):
return sum(marks) / len(marks)
Small focused functions are easier to test and reuse.
6.2 Docstrings
def square(number):
'''Return the square of a number.'''
return number * number
print(square.__doc__)
6.3 Type Hints
def add(a: int, b: int) -> int:
return a + b
Type hints document intended types; Python generally does not enforce them automatically at runtime.
6.4 Naming
Prefer descriptive lowercase names with underscores, such as calculate_total() and find_maximum().
7. Lambda Functions
A lambda is a small anonymous function used for short expressions.
7.1 Basic Lambda
square = lambda x: x * x
print(square(5))
7.2 Multiple Parameters
add = lambda a, b: a + b
print(add(10, 20))
7.3 Lambda with sorted()
students = [("Ravi", 80), ("Anu", 95), ("Kiran", 75)]
students.sort(key=lambda item: item[1])
print(students)
8. Recursion
Recursion occurs when a function calls itself. A recursive function needs a base case to stop.
8.1 Recursive Factorial
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5))
8.2 Why Base Cases Matter
Without a stopping condition, recursive calls can continue until Python reaches its recursion limit.
9. Practical Function Workflow
- Identify the task.
- Decide required inputs.
- Choose parameters.
- Write the logic.
- Decide whether to print or return.
- Call the function.
- Test normal and boundary cases.
9.1 Student Result Example
def result(marks):
average = sum(marks) / len(marks)
if average >= 40:
return "Pass"
return "Fail"
print(result([70, 65, 80]))
9.2 Common Mistakes
- Forgetting to call the function.
- Using print when a reusable result is required.
- Using local variables outside their scope.
- Passing the wrong number of required arguments.
- Putting a positional argument after a keyword argument.
- Forgetting the base case in recursion.
- Using complicated lambda expressions.
31 Coding Questions — Step-by-Step Solutions
Try each problem yourself first, then reveal the solution.
Define a function that prints Hello Python and call it.
- Identify the required inputs and output.
- Define the function using
def. - Write the required logic inside the indented body.
- Call the function and inspect the result.
def hello():
print("Hello Python")
hello()Create greet(name) that prints a greeting.
- Identify the required inputs and output.
- Define the function using
def. - Write the required logic inside the indented body.
- Call the function and inspect the result.
def greet(name):
print("Hello", name)
greet("Ravi")Return the sum of two numbers.
- Identify the required inputs and output.
- Define the function using
def. - Write the required logic inside the indented body.
- Call the function and inspect the result.
def add(a, b):
return a + b
print(add(10, 20))Return a - b.
- Identify the required inputs and output.
- Define the function using
def. - Write the required logic inside the indented body.
- Call the function and inspect the result.
def subtract(a, b):
return a - b
print(subtract(20, 8))Create a greeting function with a default name.
- Identify the required inputs and output.
- Define the function using
def. - Write the required logic inside the indented body.
- Call the function and inspect the result.
def greet(name="Student"):
print("Hello", name)
greet()
greet("Anu")Call a function with keyword arguments in a different order.
- Identify the required inputs and output.
- Define the function using
def. - Write the required logic inside the indented body.
- Call the function and inspect the result.
def student(name, age):
print(name, age)
student(age=22, name="Ravi")Return the average of a list of marks.
- Identify the required inputs and output.
- Define the function using
def. - Write the required logic inside the indented body.
- Call the function and inspect the result.
def average(marks):
return sum(marks) / len(marks)
print(average([80, 90, 70]))Return the largest of three numbers.
- Identify the required inputs and output.
- Define the function using
def. - Write the required logic inside the indented body.
- Call the function and inspect the result.
def maximum(a, b, c):
return max(a, b, c)
print(maximum(10, 45, 22))Return Even or Odd.
- Identify the required inputs and output.
- Define the function using
def. - Write the required logic inside the indented body.
- Call the function and inspect the result.
def even_odd(n):
if n % 2 == 0:
return "Even"
return "Odd"
print(even_odd(14))Classify a number.
- Identify the required inputs and output.
- Define the function using
def. - Write the required logic inside the indented body.
- Call the function and inspect the result.
def classify(n):
if n > 0:
return "Positive"
elif n < 0:
return "Negative"
return "Zero"
print(classify(-5))Return sum, difference and product.
- Identify the required inputs and output.
- Define the function using
def. - Write the required logic inside the indented body.
- Call the function and inspect the result.
def calculate(a, b):
return a + b, a - b, a * b
s, d, p = calculate(10, 5)
print(s, d, p)Return the length of a string.
- Identify the required inputs and output.
- Define the function using
def. - Write the required logic inside the indented body.
- Call the function and inspect the result.
def string_length(text):
return len(text)
print(string_length("Python"))Return the number of vowels.
- Identify the required inputs and output.
- Define the function using
def. - Write the required logic inside the indented body.
- Call the function and inspect the result.
def count_vowels(text):
count = 0
for ch in text.lower():
if ch in "aeiou":
count += 1
return count
print(count_vowels("Programming"))Return a reversed string.
- Identify the required inputs and output.
- Define the function using
def. - Write the required logic inside the indented body.
- Call the function and inspect the result.
def reverse_text(text):
return text[::-1]
print(reverse_text("Python"))Return the total of a list.
- Identify the required inputs and output.
- Define the function using
def. - Write the required logic inside the indented body.
- Call the function and inspect the result.
def total(values):
return sum(values)
print(total([10, 20, 30, 40]))Return only even numbers from a list.
- Identify the required inputs and output.
- Define the function using
def. - Write the required logic inside the indented body.
- Call the function and inspect the result.
def get_evens(numbers):
return [n for n in numbers if n % 2 == 0]
print(get_evens([1,2,3,4,5,6]))Add any number of numeric arguments.
- Identify the required inputs and output.
- Define the function using
def. - Write the required logic inside the indented body.
- Call the function and inspect the result.
def total(*numbers):
return sum(numbers)
print(total(10, 20, 30, 40))Print all key-value pairs supplied to a function.
- Identify the required inputs and output.
- Define the function using
def. - Write the required logic inside the indented body.
- Call the function and inspect the result.
def show_profile(**details):
for key, value in details.items():
print(key, value)
show_profile(name="Ravi", age=22, city="Hyderabad")Create and use a local variable.
- Identify the required inputs and output.
- Define the function using
def. - Write the required logic inside the indented body.
- Call the function and inspect the result.
def show():
message = "Local variable"
print(message)
show()Read a global variable inside a function.
- Identify the required inputs and output.
- Define the function using
def. - Write the required logic inside the indented body.
- Call the function and inspect the result.
x = 100
def show():
print(x)
show()Increment a global counter using global.
- Identify the required inputs and output.
- Define the function using
def. - Write the required logic inside the indented body.
- Call the function and inspect the result.
count = 0
def increment():
global count
count += 1
increment()
increment()
print(count)Create an outer function containing an inner function.
- Identify the required inputs and output.
- Define the function using
def. - Write the required logic inside the indented body.
- Call the function and inspect the result.
def outer():
def inner():
print("Inside inner")
inner()
outer()Modify an enclosing variable.
- Identify the required inputs and output.
- Define the function using
def. - Write the required logic inside the indented body.
- Call the function and inspect the result.
def outer():
x = 10
def inner():
nonlocal x
x += 5
inner()
print(x)
outer()Add and display a function docstring.
- Identify the required inputs and output.
- Define the function using
def. - Write the required logic inside the indented body.
- Call the function and inspect the result.
def square(n):
'''Return the square of n.'''
return n * n
print(square.__doc__)Write a typed function that adds two integers.
- Identify the required inputs and output.
- Define the function using
def. - Write the required logic inside the indented body.
- Call the function and inspect the result.
def add(a: int, b: int) -> int:
return a + b
print(add(5, 7))Use lambda to calculate a square.
- Identify the required inputs and output.
- Define the function using
def. - Write the required logic inside the indented body.
- Call the function and inspect the result.
square = lambda x: x * x
print(square(6))Use lambda to add two numbers.
- Identify the required inputs and output.
- Define the function using
def. - Write the required logic inside the indented body.
- Call the function and inspect the result.
add = lambda a, b: a + b
print(add(8, 12))Sort tuples by their second value.
- Identify the required inputs and output.
- Define the function using
def. - Write the required logic inside the indented body.
- Call the function and inspect the result.
students = [("Ravi", 80), ("Anu", 95), ("Kiran", 75)]
students.sort(key=lambda x: x[1])
print(students)Calculate factorial using recursion.
- Identify the required inputs and output.
- Define the function using
def. - Write the required logic inside the indented body.
- Call the function and inspect the result.
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5))Print n down to 1 using recursion.
- Identify the required inputs and output.
- Define the function using
def. - Write the required logic inside the indented body.
- Call the function and inspect the result.
def countdown(n):
if n == 0:
return
print(n)
countdown(n - 1)
countdown(5)Return Pass if average is at least 40, otherwise Fail.
- Identify the required inputs and output.
- Define the function using
def. - Write the required logic inside the indented body.
- Call the function and inspect the result.
def result(marks):
average = sum(marks) / len(marks)
if average >= 40:
return "Pass"
return "Fail"
print(result([70, 65, 80]))31 Theory Questions with Answers
Useful for revision, exams and Python interviews.