What is a Function in Python?
A function is a block of code designed to perform a particular task.
We use the def keyword to create a function.
Syntax
def function_name():
Example
def welcome():
print("Welcome to Python")
Calling the function:
welcome()
Output
Welcome to Python
Types of Functions in Python
- Function Without Parameters
These functions do not take any input values.
Example
def greet():
print("Hello, welcome to Python!")
greet()
Explanation
greet() function is created
No parameters are passed
The function simply prints a message
- Function With Parameters
Parameters allow us to send values into a function.
Example
def greet(name):
print("Hello", name)
greet("Vishwa")
Output
Hello Vishwa
Explanation
name is the parameter
"Vishwa" is the argument passed to the function
- Function With Return Value
Functions can return results using the return keyword.
Example
def add(a, b):
return a + b
result = add(5, 3)
print("Sum is:", result)
Output
Sum is: 8
Explanation
The function calculates the sum
return sends the result back to the caller
- Function With Default Parameter
Default parameters are used when no value is passed.
Example
def greet(name="Guest"):
print("Hello", name)
greet("Vishwa")
greet()
Output
Hello Vishwa
Hello Guest
Explanation
If no argument is passed, "Guest" becomes the default value
- Function With Variable Length Arguments
Sometimes we do not know how many inputs will be passed.
Python uses *args for this.
Example
def numbers(*args):
total = 0
for num in args:
total += num
print("Sum is:", total)
numbers(1, 2, 3, 4, 5)
Output
Sum is: 15
Explanation
*args stores all values as a tuple
The loop adds all numbers
Local Variable and Global Variable
Local Variable
A variable created inside a function is called a local variable.
Example
def sample():
x = 10
print(x)
sample()
x can only be used inside the function.
Global Variable
A variable created outside the function is called a global variable.
Example
x = 100
def sample():
print(x)
sample()
Explanation
Global variables can be accessed anywhere in the program
Real-Time Example: Student Mark Analysis
Functions can also be used in real-world problems like student record processing.
Top comments (0)