Class12 CS Working With Functions Notes
Class12 CS Working With Functions Notes
1. What is a Function?
- A function is a reusable block of code that performs a specific task.
- Helps reduce redundancy and makes code more readable.
2. Types of Functions
- Built-in Functions: Predefined (e.g., print(), len(), input(), type())
- User-defined Functions: Created by the programmer using def
3. Defining a Function
Syntax:
def function_name(parameters):
statements
return value
Example:
def greet(name):
print("Hello", name)
4. Calling a Function
- Just use the function name with arguments: greet("Haru")
6. Return Statement
- Used to return a value from a function
- Ends the execution of the function
Example:
def add(a, b):
return a + b
7. Default Parameters
- Parameters with default values
Example:
def greet(name="User"):
print("Hello", name)
Example:
def student(name, age): pass
student(age=17, name="Haru")
9. Variable Scope
- Local Scope: Defined inside function
- Global Scope: Defined outside function
global x
x=5
def show():
global x
x=x+1
10. Recursion
- Function that calls itself
- Must have a base condition to end recursion
Example:
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
Tips:
- Always trace recursive functions.
- Use return wisely.
- Know the difference between arguments and parameters.
- Use local/global properly.