Python in Python is best learned by connecting the rule to an automation script. Start with the smallest function or script, observe the output, and then add one realistic constraint so the concept becomes practical.
The key habit for this lesson is to watch input value and returned object as it changes. That makes the topic easier to debug, easier to explain in interviews, and easier to use in real code without memorizing isolated syntax.
A function is a reusable block of code that performs a specific task. Functions help you avoid repetition, organize code, and make it easier to test and maintain.
# Define a function
def greet():
print("Hello, World!")
# Call the function
greet() # Hello, World!
# Function with parameters
def greet_user(name):
print(f"Hello, {name}!")
greet_user("Alice") # Hello, Alice!
greet_user("Bob") # Hello, Bob!
# Function with return value
def add(a, b):
return a + b
result = add(3, 5)
print(result) # 8
# Default parameters
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Alice") # Hello, Alice!
greet("Bob", "Hi") # Hi, Bob!
greet("Charlie", greeting="Hey") # Hey, Charlie!
# Keyword arguments - order doesn't matter
def describe(name, age, city):
print(f"{name}, {age}, from {city}")
describe(age=25, city="London", name="Alice")
# *args - variable number of positional arguments
def total(*numbers):
return sum(numbers)
print(total(1, 2, 3)) # 6
print(total(10, 20, 30, 40)) # 100
# **kwargs - variable number of keyword arguments
def show_info(**details):
for key, value in details.items():
print(f"{key}: {value}")
show_info(name="Alice", age=25, city="London")
# Combining all parameter types
def full_example(pos, /, normal, *, kw_only, **kwargs):
print(pos, normal, kw_only, kwargs)
# Return multiple values (as a tuple)
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([3, 1, 4, 1, 5, 9])
print(low, high) # 1 9
# Early return
def is_even(n):
if n % 2 == 0:
return True
return False
# Functions without return return None
def say_hi():
print("Hi!")
result = say_hi()
print(result) # None
# Return a function (higher-order function)
def multiplier(factor):
def multiply(x):
return x * factor
return multiply
double = multiplier(2)
triple = multiplier(3)
print(double(5)) # 10
print(triple(5)) # 15
Type hints (Python 3.5+) make your code more readable and help IDEs catch bugs. They're optional but highly recommended.
def add(a: int, b: int) -> int:
return a + b
def greet(name: str, times: int = 1) -> str:
return (f"Hello, {name}! " * times).strip()
def process(items: list[int]) -> dict[str, int]:
return {"sum": sum(items), "count": len(items)}
# Optional type (can be None)
from typing import Optional
def find_user(user_id: int) -> Optional[str]:
users = {1: "Alice", 2: "Bob"}
return users.get(user_id) # returns str or None
print(find_user(1)) # Alice
print(find_user(99)) # None
def calculate_area(radius: float) -> float:
"""
Calculate the area of a circle.
Args:
radius (float): The radius of the circle.
Returns:
float: The area of the circle.
Raises:
ValueError: If radius is negative.
Example:
>>> calculate_area(5)
78.53981633974483
"""
import math
if radius < 0:
raise ValueError("Radius cannot be negative")
return math.pi * radius ** 2
# Access the docstring
print(calculate_area.__doc__)
help(calculate_area)
A function that calls itself. Every recursive function needs a base case to stop.
# Factorial: n! = n * (n-1) * ... * 1
def factorial(n: int) -> int:
if n <= 1: # base case
return 1
return n * factorial(n - 1) # recursive call
print(factorial(5)) # 120
print(factorial(10)) # 3628800
# Fibonacci sequence
def fibonacci(n: int) -> int:
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
print([fibonacci(i) for i in range(10)])
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Use Python when the program needs a clear answer to a specific problem, not because the keyword looks familiar. In a real Python task, first name the input, then name the transformation, then name the output. This small discipline shows whether the topic is being used correctly or only copied from an example.
A reliable practice flow is: create the smallest working function or script, add one normal case, add one edge case such as missing, repeated, empty, or boundary input, and then confirm the result with traceback and printed inspection. If the result surprises you, reduce the code until the behavior is visible again.
The most common trap here is copying the syntax before understanding the behavior. Avoid it by writing one sentence before the code that explains why Python is the right choice. After the code runs, verify the lesson by doing this: change one input and explain the changed output.
Copying the syntax before understanding the behavior.
Write the expected behavior first, then make the example prove it.
Practicing only the perfect input.
Also test missing, repeated, empty, or boundary input before considering the lesson complete.
Looking only at the final output.
Trace input value and returned object through each important step.
*args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dictionary. You can use both: def func(*args, **kwargs). They allow functions to accept any number of arguments.
A decorator is a function that takes another function and extends its behavior. Applied with @decorator_name syntax. Common uses: @staticmethod, @classmethod, @property, @functools.lru_cache for memoization.
A function is defined at module level with def. A method is a function defined inside a class. Methods automatically receive the instance (self) or class (cls) as the first argument.
Explore 500+ free tutorials across 20+ languages and frameworks.