Press ESC to close

Python Functions

  • What is a Function in Python?

    • A function is a reusable block of code that performs a specific task.
    • Define the function once.
    • Call it whenever you need it.
       
  • Syntax

def function_name():
   # Code to execute
  • def → Keyword used to define a function.
  • function_name → Name of the function.
  • () → Parentheses (can contain parameters).
  • : → Starts the function body.
  • Indented code → The statements that belong to the function.
def greet():
   print("Hello, Welcome to Python!")
   
greet()

Output

Hello, Welcome to Python!
  • Function with Parameters

    • A parameter is a variable that receives a value when the function is called.
def greet(name):
   print("Hello", name)
   
greet("Alice")
greet("Bob")

Output

Hello Alice
Hello Bob

Here:

  • name is the parameter.
  • "Alice" and "Bob" are the arguments.

Returning a Value

  • The return statement sends a value back to the caller.
def add(a, b):
   return a + b
   
result = add(5, 7)

print(result)

Output

12
  • Type Hints in function

    • Type hints tell Python (and other developers) what type of data a function expects and what type it returns.
       
  • Syntax

def function_name(parameter: data_type) -> return_type:
   ...
  • : → Specifies the parameter type.
  • -> → Specifies the return type.

Type Hints

Type HintExample
intage: int
floatprice: float
strname: str
boolis_active: bool
list[str]List of strings
list[int]List of integers
dict[str, int]Dictionary with string keys and integer values
tuple[int, int]Tuple of two integers
NoneFunction returns nothing


Real-Life Analogy

Think of a TV remote:

  • 📺 Press the Power button → TV turns on.
  • 🔊 Press the Volume Up button → Volume increases.
  • 🔇 Press the Mute button → TV is muted.

Each button performs a specific task. In Python, each function performs a specific task in the same way.

Related Posts

Python Class
Python Dict & Tuples
Python Data Types, Lists & For Loop
What is Jupyter Notebook?

Leave a comment

Your email address will not be published. Required fields are marked *

Your experience on this site will be improved by allowing cookies.