What is a Function ?
A function is a block of code that performs a specific task and can be reused multiple times in a program.
Without functions, programmers would need to write the same code again and again, which makes programs longer and harder to manage.
Example without function:
print("Hello Aman")
print("Hello Rahul")
print("Hello Priya")Using function:
def greet(name):
print("Hello", name)
greet("Aman")
greet("Rahul")
greet("Priya")Defining Functions
In Python, functions are defined using the def keyword.
Basic Syntax
def function_name():
# code blockExample: Simple Function , greet( ) will be called by and the value will be printed.
def greet(): # function definiton
print("Welcome to Python Programming")
greet() # function callOutput:
Welcome to Python ProgrammingKey Points While Defining Functions
- Use
defkeyword - Function name should be meaningful
- Parentheses
()are required - Colon
:is used after function declaration - Proper indentation is mandatory
Function Naming Rules
- Must start with a letter or underscore
- Cannot use keywords like
if,for,while - Should follow lowercase naming convention
- Use descriptive names like
calculate_sum()
Parameters and Arguments
Functions can take input values called parameters. These inputs help functions perform operations dynamically.
Arguments are the values you pass into a function call when you call it.
Function with Parameters
def greet(name): # name is parameter
print("Hello", name)
greet("Aman") # value Aman will be passed to parameter nameOutput:
Hello AmanMultiple Parameters
def add(a, b):
print(a + b)
add(5, 3)8Positional Arguments
In this values are passed in correct order of parameters.
def student(name, age):
print(name, age)
student("Aman", 20) # name , age : Aman , 20Aman 20Keyword Arguments
Arguments are passed using parameter names.
def student(name, age):
print(name, age)
student(age=20, name="Aman")Aman 20Default Arguments
Default values are assigned if no value is provided.
def greet(name="Guest"): # default value Guest
print("Hello", name)
greet()
greet("Rahul")Hello Guest
Hello RahulVariable-Length Arguments
It is used when number of inputs is unknown while writing function definition.
def add(*numbers):
print(sum(numbers))
add(1, 2, 3, 4)Return Values in Functions
Functions can return calculated values using the return keyword.
Example:
def add(a, b):
return a + b
result = add(10, 5) # get the calculated value in result variable
print(result)Output:
15Returning Multiple Values
def operations(a, b):
return a + b, a - b
x, y = operations(10, 5)
print(x, y)Built-in Functions
Built-in functions are pre-defined functions available in Python.
Examples:
print("Hello")
print(len("Python")) # we can directly use functions in print( )
print(type(10))
print(max(5, 10, 20))Hello
6
<class 'int'>
20These functions are ready to use without defining them.
Common Built-in Functions
| Function | Description |
|---|---|
print() | Displays output |
len() | Returns length of data value |
type() | Returns data type of value or variable |
sum() | Adds given values |
max() | Finds maximum number |
User-Defined Functions
User-defined functions are created by programmers to perform specific tasks.
Example: calculate the square of the value provided
def square(x):
return x * x
print(square(4))Output:
16Scope of Variables
Variables inside functions have limited scope.
Local Variable
def test():
x = 10
print(x)
test() # x will be printed
print(x) # error because x is not defined or defined in a function definition10
NameError: name 'x' is not definedGlobal Variable
x = 5
def show():
print(x) # value of x will be printed because it is defined outside function
show()5Recursive Functions
A function that calls itself is called recursion.
def factorial(n):
if n == 1:
return 1
return n * factorial(n-1)
print(factorial(5))120Practical Examples
Example 1: Even or Odd
def check_even(num):
if num % 2 == 0:
return "Even"
return "Odd"
print(check_even(7))OddExample 2: Calculator
def calculator(a, b):
return a + b, a - b, a * b
print(calculator(10, 5))(15, 5, 50)Example 3: Find Maximum
def find_max(a, b):
if a > b:
return a
return b
print(find_max(10, 20))20🎉 Great progress! Back to Learning Path ⬆