Learning how to define functions in Python 3 is one of the most essential and powerful skills at Progressive Robot — functions are reusable blocks of code that perform specific tasks, accept inputs (parameters), return outputs, and make your programs modular, readable, testable, and scalable for everything from automation scripts to web APIs, data pipelines, AI models, and enterprise applications.
In this up-to-date 2025–2026 Progressive Robot guide, you’ll master exactly how to define functions in Python 3: basic syntax, parameters (positional, keyword, defaults), *args & **kwargs, return statements, multiple returns, scope, __name__ == “__main__”, docstrings, type hints, and best practices. All examples are tested on Python 3.10–3.13.
Key Takeaways – How to Define Functions in Python 3
- Define functions in Python 3 with def function_name(parameters): — indented block contains the code.
- Parameters: positional, keyword, default values, *args (variable positional), **kwargs (variable keyword).
- Use return to output values — functions without return give None.
- Return multiple values easily with tuples: return a, b, c.
- Docstrings (triple quotes) document purpose, params, returns — used by help(), IDEs, Sphinx.
- Type hints (Python 3.5+): def func(x: int) -> str: — improves readability & tooling.
- __name__ == “__main__” runs code only when file executed directly — essential for reusable modules.
- Functions are first-class objects — pass as arguments, return from functions, store in variables.
Prerequisites
- Python 3.8+ installed (Progressive Robot recommends 3.12+)
- Basic Python knowledge (variables, print, indentation)
- Interactive shell (python3) or script file
1. Basic Syntax – How to Define Functions in Python 3
def greet():
"""Print a simple greeting."""
print("Hello from Progressive Robot!")
Call the function:
greet() # Hello from Progressive Robot!
2. Functions with Parameters
def greet(name: str):
"""Greet a user by name."""
print(f"Hello, {name}! Welcome to Progressive Robot.")
greet("Zain") # Hello, Zain! Welcome to Progressive Robot.
Multiple parameters:
def add(a: int, b: int) -> int:
"""Add two numbers and return result."""
return a + b
print(add(5, 8)) # 13
3. Default Parameters & Keyword Arguments
def register_user(name: str, age: int = 18, city: str = "Karachi"):
print(f"Registered: {name}, {age} years old from {city}")
register_user("Zain") # uses defaults
register_user("Alice", 25, "Manchester") # overrides
register_user(name="Bob", city="London") # keyword args (order doesn't matter)
4. Variable Arguments – *args & **kwargs
def log_message(level: str, *args, **kwargs):
"""Log message with variable args."""
print(f"[{level}]", *args, kwargs)
log_message("INFO", "User logged in", id=123, ip="192.168.1.1")
# [INFO] User logged in {'id': 123, 'ip': '192.168.1.1'}
5. Return Statements – Single & Multiple Values
def get_user_info():
return "Zain", 30, "Karachi" # returns tuple
name, age, city = get_user_info()
print(name, age, city) # Zain 30 Karachi
No return → None:
def say_hi():
print("Hi!")
result = say_hi() # Hi!
print(result) # None
6. Docstrings – Professional Documentation
def calculate_tax(income: float, rate: float = 0.2) -> float:
"""
Calculate tax on income.
Args:
income (float): Annual income
rate (float, optional): Tax rate. Defaults to 0.2 (20%).
Returns:
float: Tax amount
Example:
>>> calculate_tax(50000)
10000.0
"""
return income * rate
7. name == "main" – Run Code Only When Executed Directly
def main():
print("This runs only when file is executed directly")
if __name__ == "__main__":
main()
8. Best Practices & Modern Tips (2025–2026 – Progressive Robot Style)
- Use descriptive names: calculate_total_price > calc
- Add type hints: improves readability & IDE support
- Write docstrings (Google/Numpy style) — auto-generated docs
- Keep functions small & focused (single responsibility)
- Use default mutable arguments carefully: def func(items=None): items = items or []
- Prefer return over print() in reusable functions
- Use return early for guard clauses
How to Define Functions in Python 3 – FAQ (2025–2026)
- How do I define functions in Python 3?
Use def function_name(parameters): — basic syntax to define functions in Python 3. - How do I return multiple values from functions in Python 3?
Return tuple: return a, b, c — unpack with x, y, z = func(). - What is name == “main” used for in Python 3?
Runs code only when file executed directly — essential for reusable modules. - How do I add default parameters when defining functions in Python 3?
def func(x, y=10): — y defaults to 10. - How do I write docstrings when defining functions in Python 3?
Triple quotes right after def — standard for documentation.
Summary
You now know exactly how to define functions in Python 3: syntax, parameters, defaults, *args/**kwargs, return values, docstrings, type hints, __main__ guard, and Progressive Robot best practices.
Mastering how to define functions in Python 3 transforms simple scripts into reusable, modular, professional code — the backbone of every Python project, from automation to web services, data science, and AI at Progressive Robot.
Recommended Next Tutorials
- Python Return Statements & Multiple Returns
- Python *args & **kwargs – Variable Arguments
- Python Type Hints & Annotations (2025–2026)
- Build a CLI Calculator with Functions
- Python Functions Cheat Sheet