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 executedef→ 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 BobHere:
nameis the parameter."Alice"and"Bob"are the arguments.
Returning a Value
- The
returnstatement sends a value back to the caller.
def add(a, b):
return a + b
result = add(5, 7)
print(result)Output
12Type Hints in function
- Type hints tell Python (and other developers) what type of data a function expects and what type it returns.
- 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 Hint | Example |
|---|---|
int | age: int |
float | price: float |
str | name: str |
bool | is_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 |
None | Function 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.