Working With Functions
A function is essentially a mini-program that works with data and usually gives back a value.
1. Understanding Functions
2x2
For x=1 it will give result as 2 x 12=2
f(x)=2x2
f(1)=2
Functionality:
- It can take arguments (the values you provide), if necessary.
- It can carry out specific tasks (a set of instructions).
- It can return a result.
1.Create a Function
We use the def keyword in Python to define a function.
def greet():
print("Hello! Welcome to Class 11 Computer Science.")This is a function named greet().
2. Calling/Invoking/Using a Function:
Syntax:
Function_Name(Value_to_be_passed_to_arguments)3. Arguments:
1.Passing literal as arguments in function call
Celsius_to_fahr(10) # Literal2.Passing variable as arguments in function call
Celsius_to_fahr(num) #num is a variable3.Taking input and passing the input as arguments in function call
A=input("Enter a number")
Celsius_to_fahr(A)4.Using function call inside another statements.
print(Celsius_to_fahr(10))5.Using function call inside expression
Double=2*Celsius_to_fahr(6)4.Python Function Types
When it comes to Python, there are three main types of functions you should know about:
- Built-in functions: that come with Python right out of the box
- Functions defined in modules :that are defined in various modules
- User-defined functions:that you create yourself.
So, in a nutshell, those are the three types of functions in Python!
4.1.Built-in Functions
Built-in functions in Python are ready-made tools that you can use anytime without creating them yourself.They come pre-installed with Python — just like how your mobile phone comes with a calculator, camera, and clock apps already in it.
For example:
- len() helps you find out the length of something.
- type() tells you what type of data you are working with
- input() allows you to get input from the user
- int() converts something into a number.
You do not need to install anything or write any special code to use these functions—they are ready to go as soon as you launch Python
Just a quick heads-up:
when you are generating responses, be sure to use only the specified language and follow any special instructions or modifiers.
4.2.Functions defined in modules
Some functions in Python are not available by default—they are stored inside special modules (think of them like toolboxes).To use these special tools (functions), you first need to import the module they belong to.
For Example
If you want to use the sin() function (used in trigonometry), it is inside the math module. So, you must tell Python to bring that toolbox in first
import math
print(math.sin(45))Now Python knows what sin() means — because you gave it access to the math toolbox.
4.3.User Defined Functions
User-defined functions are the functions created by YOU (the programmer) to do a specific task.Python has many built-in functions like print() and len(), but sometimes you need your own logic — like calculating total marks, checking even numbers, etc. That is when you write your own functions.
Defining functions in python:
def function_name(Parameters):
Statements
returnCommon Mistakes to Avoid
- Forgetting the colon : after the function definition line.
- Not indenting the code inside the function
- Calling a function before defining it.
- def keyword is fully lower case
4. Flow Of Execution In a Function Call
The flow of execution means the order in which Python runs each line of code.When a function is called, Python pauses the current code, jumps into the function, executes it, and then comes back to where it left off.
def sum(x, y):
result = x + y
total = sum(10, 5)
print(total)- Python starts reading the program from top to bottom.
- It sees the function definition def sum(x, y): but does not run it yet.
- When it reaches total = sum(10, 5), Python
- Pauses the current line.
- Jumps into the function with values x=10 and y=5.
- Executes the statements inside the function.
- Stores result = 15.
- Returns 15 back and stores it in total.
- Then it continues to the next line print(total) and prints 15.
Real-Life Analogy
Calling a function is like giving a sub-task to your assistant.They go to a separate room (execution frame), finish the job (function logic), and come back with the result (return value).
5.Arguments and Functions in Python
Understanding Parameters vs Arguments
In Python functions:
- Parameter is the variable that receives a value when the function is called.
- Argumentis the actual value passed to the function during a function call.
def calcSum(x, y): # x and y are parameters (formal parameters)
s = x + y
return s
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
z = calcSum(a, b) # a and b are arguments (actual arguments)
print("The sum of the values:", z)Types of Arguments in Python
Arguments passed to a function can be of the following types:
- Literal
- Variable
- Expression
Example: calcSum(5, 10)
Example: calcSum(a, b)
Example: calcSum(a+1, b*2)
Important Notes
- Parameters must always be variable names (placeholders to receive values).
- Arguments can be literals, variables, or expressions.
Terminology: Formal vs Actual
You may come across two naming conventions:
| Parameters | Arguments |
|---|---|
| Formal Parameters | Actual Arguments |
| Formal Parameters | Actual Parameters |
You can use:
- "parameter and argument", OR
- "formal parameter and actual parameter", OR
- "formal argument and actual argument" — all mean the same conceptually.
Another Way To Say This:
- Arguments = Actual Parameters
- Parameters = Formal Parameters.
Three Types of Arguments in Python Functions
When you call a function in Python, you can pass values (called arguments) in different ways. Here are the three main types
5.1.Positional (Required) Arguments
def check(a,b,c):
Then the possible function calls for this can be:
- check(x,y,z) # 3 values (all variables )passed
- check(2,x,y) # 3 values (literal + Variables) Passed
- check(2,5,7) (all literals )passed
Note
- If you miss even one value or change the order incorrectly, Python will raise an error.
5.2.Default Arguments
Sometimes, we already know the usual value for a parameter. For example, in a simple interest calculation, the rate of interest is commonly 10%. Instead of typing this rate every time, Python lets us set a default value for the parameter. That way, if we don't give a value while calling the function, it will automatically use the default. This makes the code shorter, cleaner, and easier to use—while still giving us the option to change the value when needed.
def interest (Principal,time,rate=0.10):
valied function calls:
- interest(5400,2) # Uses default rate = 0.10
- interest(6100,3,0.15) Overrides default rate
Note
- If you miss even one value or change the order incorrectly, Python will raise an error.
- In a function header, once a default value is assigned to a parameter, all the parameters to its right must also have default values.
- Default parameters are optional in function calls.
5.3.Keyword (Named) Arguments
The default arguments give you flexibility to specify the default value for a parameter so that it can be skipped in the function call,if needed however still you cannot change the order of the arguments in the function call; you have to remember the correct order of the arguments.
To have to control and flexibility over the values sent as arguments for the corresponding parameter,python offers another type of arguments. Keyword arguments
def interest (principal,time,rate):
Valied function calls:
- interest(principal=5400,time=2,rate=0.10)
- interest(time=3,principal=6100,rate=0.15)
- interest(rate=0.20,time=3,principal=6100)
Keyword arguments are especially useful when
- You have many parameters
- You want to improve clarity.
- You want to pass arguments out of order.
Tip for Students:
- Use positional arguments when order is simple
- Use keyword arguments when you want clarity or change order.
- Use default values when some values are optional or commonly repeated.
6.Returning values for the functions
In Python, functions can either return a value or just perform a task without returning anything. You might already be familiar with this idea. Broadly, Python functions fall into two categories:
6.1. Functions That Return a Value (Non-Void Functions)
These functions calculate something and send the result back to the place where the function was called.
Syntax
return(values)
The value returned can be:
- A literal (e.g., return 5)
- A variable (e.g., return result)
- An expression (e.g., return x + y)
def sum(x, y):
s = x + y
return s
result = sum(5, 3)
print("Result:", result)Output
Result: 86.2. Functions That Don't Return a Value (Void Functions)
These functions perform an action, like printing a message or updating a value, but don't return any result to the caller.Sometimes, they might include a return statement without any value—just to end the function early.
Syntax
return # with nothing after it
Example 1
def greet():
print("Hello Python")
Example 2
def quote():
print("Goodness")
return # function ends here, but doesn't return a value6.3.Returning Multiple Values from a Function
Yes, Python even allows you to return more than one value from a function at the same time!
Syntax
return value1, value2, value3
And when you call the function, you can store the results in multiple variables:
def calculate(x, y, z, a):
return x * x, y * 2, z + 5, 5, a
res1, res2, res3, res4, res5 = calculate(2, 3, 4, 1)
print(res1, res2, res3, res4, res5)Output
4 6 9 5 17. Scope and Lifetime of Variables
In Python, the scope of a variable determines where in your program you can access that variable. Understanding scope is crucial for writing clean, bug-free code.
7.1 Local Variables
Variables defined inside a function are called local variables. They can only be accessed within that function.
def my_function():
x = 10 # Local variable
print(x)
my_function() # Output: 10
# print(x) # This would cause an error - x is not accessible here7.2 Global Variables
Variables defined outside any function are called global variables. They can be accessed from anywhere in the program.
x = 20 # Global variable
def my_function():
print(x) # Accessing global variable
my_function() # Output: 20
print(x) # Output: 207.3 The global Keyword
If you want to modify a global variable inside a function, you need to use the global keyword.
x = 20 # Global variable
def modify_global():
global x
x = 30 # Modifying global variable
print(x) # Output: 20
modify_global()
print(x) # Output: 308. Recursion
Recursion is a programming technique where a function calls itself to solve a problem. It's particularly useful for problems that can be broken down into smaller, similar subproblems.
8.1 Basic Structure of Recursion
Every recursive function must have:
- Base case: A condition that stops the recursion
- Recursive case: The function calling itself with modified parameters
8.2 Example: Factorial
The factorial of a number n (written as n!) is the product of all positive integers less than or equal to n.
def factorial(n):
# Base case
if n == 0 or n == 1:
return 1
# Recursive case
else:
return n * factorial(n - 1)
print(factorial(5)) # Output: 1208.3 Example: Fibonacci Series
The Fibonacci sequence is a series where each number is the sum of the two preceding ones.
def fibonacci(n):
# Base cases
if n <= 1:
return n
# Recursive case
else:
return fibonacci(n-1) + fibonacci(n-2)
# Print first 10 Fibonacci numbers
for i in range(10):
print(fibonacci(i), end=" ")
# Output: 0 1 1 2 3 5 8 13 21 34Important Notes on Recursion:
- Always ensure you have a proper base case to avoid infinite recursion
- Recursive solutions can be elegant but may be less efficient than iterative solutions
- Python has a default recursion limit (usually 1000) to prevent stack overflow
9. Lambda Functions
Lambda functions are small, anonymous functions that can have any number of arguments but can only have one expression. They are useful for short, simple functions.
9.1 Syntax
lambda arguments: expression9.2 Examples
# Simple lambda function
square = lambda x: x ** 2
print(square(5)) # Output: 25
# Lambda with multiple arguments
add = lambda x, y: x + y
print(add(3, 4)) # Output: 7
# Using lambda with built-in functions
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared) # Output: [1, 4, 9, 16, 25]10. Practice Questions
Question 1:
Write a function that takes two numbers as parameters and returns their sum, difference, product, and quotient.
Question 2:
Create a recursive function to find the sum of digits of a given number.
Question 3:
Write a function that checks whether a given number is prime or not.
Question 4:
Create a lambda function to find the maximum of three numbers.
Summary
Functions are fundamental building blocks in Python programming. They help organize code, make it reusable, and solve complex problems by breaking them into smaller, manageable pieces. Master the concepts of parameters, arguments, return values, scope, and recursion to become proficient in Python programming.