Python Mastery – From Basics to Brilliance / Functions

Defining and Calling Functions

πŸ”§ Defining and Calling Functions

A function is a reusable block of code that performs a specific task.

Instead of writing the same code multiple times, we can define a function once and call it whenever we need it.


πŸ“ Defining a Function

We use the def keyword to define a function.

Syntax

def function_name():
    # code to execute

Example

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

Here:

  • def β†’ Keyword used to define a function

  • greet β†’ Function name

  • () β†’ Parentheses for parameters

  • : β†’ Starts the function body

  • Indented code β†’ Function body

Defining a function does not execute it.


πŸ“ž Calling a Function

To execute a function, we need to call it using its name followed by ().

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

greet() #Hello, Python!

The function executes only when we call it.


πŸ” Calling a Function Multiple Times

Once a function is defined, we can call it as many times as needed.

def greet():
    print("Hello!")

greet()
greet()
greet()
Hello!
Hello!
Hello!

πŸ“¦ Function with Parameters

A function can accept data through parameters.

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

greet("Tisha") #Hello Tisha

Here:

  • name β†’ Parameter

  • "Tisha" β†’ Argument


⭐ Remember

def add():
    print(10 + 20)   # Define

add()                # Call

def creates the function; () calls the function.