Python Class 12: Functions (Full Explanation + Practical Questions)
1. Types of Functions
Definition:
Python functions can be categorized as:
- Built-in functions: Already available in Python (e.g., len(), max(), input())
- Functions defined in module: Imported from Python libraries (e.g., [Link]())
- User-defined functions: Created using def keyword.
Code Examples:
print(len("Python"))
import math
print([Link](64))
def greet(): print("Hello, Python learner!")
Assessment Questions:
1. Use max() to find the highest of 3 numbers.
2. Import math module & calculate area of a circle.
3. Define a function that prints a quote.
2. Creating a User-defined Function
Definition:
A user-defined function is a block of code defined with def to perform a task.
Syntax:
def function_name(): # code
Code Example:
def display_message(): print("Welcome to Class 12 Python!")
display_message()
Assessment Questions:
1. Define student_intro() function to print name & class.
2. Print current time using datetime module.
3. Arguments and Parameters
Definition:
- Parameter: Variable in the function definition.
- Argument: Value passed when function is called.
Code Example:
def greet_user(name): print("Hello", name)
greet_user("Arjun")
Assessment Questions:
1. Accept two numbers and print sum.
2. Write circle_area(radius) to calculate area.
4. Default Parameters
Definition:
Parameters with default values used when no argument is passed.
Code Example:
def welcome(name="Guest"): print("Welcome", name)
welcome(), welcome("Riya")
Assessment Questions:
1. greet(name="Student") to test default value.
2. ticket(price, discount=10) to calculate final price.
5. Positional Parameters
Definition:
Arguments matched in order they appear.
Code Example:
def student_info(name, age): print(f"{name} is {age} years old.")
student_info("Riya", 17)
Assessment Questions:
1. book_details(title, author) function.
2. Function that takes 3 numbers and prints average.
6. Function Returning Value(s)
Definition:
Functions return a result using return keyword.
Code Example:
def add(a, b): return a + b
print("Sum is:", add(4, 6))
Assessment Questions:
1. multiply(x, y) that returns product.
2. max_of_three(a, b, c) to return max.
7. Flow of Execution
Definition:
Python executes code from top to bottom. Functions only run when called.
Code Example:
def step1(): print("Step 1")
def step2(): print("Step 2")
print("Start")
step1(), step2(), print("End")
Assessment Questions:
1. login(), verify(), welcome() in sequence.
2. Calculator calling functions for operations.
8. Scope of Variables
Definition:
- Local: Declared inside a function. Accessible only there.
- Global: Declared outside functions. Accessible everywhere.
Code Examples:
x = 50
def show(): print(x) # global scope
def show2(): x = 10; print(x) # local scope
Assessment Questions:
1. Use a global variable inside a function.
2. Declare a local variable and try printing outside.