DEV Community

vishwasenthil76
vishwasenthil76

Posted on

Functions in python

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")

Enter fullscreen mode Exit fullscreen mode

Calling the function:

welcome()

Output
Welcome to Python

Types of Functions in Python

  1. Function Without Parameters

These functions do not take any input values.

Example

def greet():
    print("Hello, welcome to Python!")

greet()
Enter fullscreen mode Exit fullscreen mode

Explanation
greet() function is created
No parameters are passed
The function simply prints a message

  1. Function With Parameters

Parameters allow us to send values into a function.

Example

def greet(name):
    print("Hello", name)

greet("Vishwa")

Enter fullscreen mode Exit fullscreen mode

Output
Hello Vishwa

Explanation
name is the parameter
"Vishwa" is the argument passed to the function

  1. 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)
Enter fullscreen mode Exit fullscreen mode

Output
Sum is: 8

Explanation
The function calculates the sum
return sends the result back to the caller

  1. Function With Default Parameter

Default parameters are used when no value is passed.

Example

def greet(name="Guest"):
    print("Hello", name)

greet("Vishwa")
greet()
Enter fullscreen mode Exit fullscreen mode

Output
Hello Vishwa
Hello Guest

Explanation
If no argument is passed, "Guest" becomes the default value

  1. 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)
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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)