Python Functions: Arguments, Return Values, and Scope
Introduction
Functions let you package a piece of logic under a name so you can reuse it instead of copying code. This tutorial covers defining functions, parameters and default values, returning results, and how Python decides which variables a function can see.
Prerequisites
- Python 3.8 or newer installed
- Basic Python syntax (variables, print, indentation)
Step-by-Step Guide
Step 1: Define and call a function
Use the def keyword, a name, parentheses for parameters, and an indented body. Call it by name with arguments.
def greet(name):
return "Hello, " + name
print(greet("Ava")) # Hello, AvaStep 2: Use default parameter values
Give a parameter a default so callers can leave it out. Parameters with defaults must come after those without.
def power(base, exponent=2):
return base ** exponent
print(power(5)) # 25
print(power(2, 3)) # 8Step 3: Return multiple values
A function can return several values separated by commas. Python packages them in a tuple, which you can unpack into separate variables.
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([4, 9, 1, 7])
print(low, high) # 1 9Step 4: Accept any number of arguments
Prefix a parameter with * to collect extra positional arguments into a tuple.
def total(*numbers):
return sum(numbers)
print(total(1, 2, 3, 4)) # 10Step 5: Understand variable scope
Variables created inside a function are local: they exist only while the function runs. Prefer returning values over modifying global variables.
def double(x):
result = x * 2 # result exists only inside this function
return result
print(double(4)) # 8
# print(result) # NameError: result is not defined hereFAQs
- What is the difference between a parameter and an argument?
- A parameter is the variable name in the function definition. An argument is the actual value you pass when calling the function.
- What does a function return if it has no return statement?
- It returns None, Python's value that represents 'nothing'.
Summary
Functions keep code reusable and readable. Use clear names, give optional parameters sensible defaults, return results instead of printing them inside the function, and keep variables local wherever possible.
Comments
Log in or create a free account to join the discussion.