Functions in Python
A function is a reusable block of code with a name. You define it once and call it whenever you need it. Here's the simplest possible function and how to use it:
# Define a function with 'def'
def greet(name):
return f"Hello, {name}!"
# Call it by writing its name with arguments
message = greet("Asha")
print(message) # Hello, Asha!
Functions keep your code organised and save you from repeating yourself. Let's break them down.
Defining a function
Use the def keyword, a name, parentheses for parameters, and a colon. The body is indented:
def say_hello():
# This runs every time you call say_hello()
print("Welcome to Python!")
say_hello() # call it
say_hello() # call it again — no need to rewrite the code
Parameters and arguments
Parameters are the names inside the parentheses when you define the function. Arguments are the actual values you pass when you call it:
# 'a' and 'b' are parameters
def add(a, b):
return a + b
# 4 and 7 are arguments
result = add(4, 7)
print(result) # 11
Returning values
The return keyword sends a value back to wherever the function was called. A function without return gives back None by default:
def square(n):
return n * n # send the result back
print(square(5)) # 25
def show(msg):
print(msg) # no return -> gives back None
value = show("hi")
print(value) # None
Once a return runs, the function stops immediately — any code after it is skipped.
Want to learn this properly?
Join the waitlist for our courses — beginner-friendly, project-first classes in Jalgaon.
Browse coursesDefault arguments
You can give a parameter a default value, used when the caller doesn't supply one:
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Ravi")) # Hello, Ravi!
print(greet("Ravi", "Welcome")) # Welcome, Ravi!
Default arguments must come after non-default ones in the definition.
Keyword arguments
You can pass arguments by name, which makes calls clearer and lets you reorder them:
def book_ticket(name, seats, city):
print(f"{seats} seat(s) booked for {name} to {city}")
# Pass by name in any order
book_ticket(seats=2, city="Pune", name="Meena")
A complete example
# Calculate the final price after a discount
def final_price(price, discount_percent=0):
"""Return price after applying a percentage discount."""
discount = price * discount_percent / 100
return price - discount
# Without a discount
print(final_price(1000)) # 1000.0
# With a 15% discount
print(final_price(1000, 15)) # 850.0
That triple-quoted line is a docstring — a short description of what the function does. It's good practice to add one.
Common mistakes
- Forgetting to call the function: Writing
greetinstead ofgreet("Asha")doesn't run it — it just refers to the function object. - Confusing print and return:
print()shows something on screen;returnsends a value back so other code can use it. If youprintinstead ofreturn, you can't reuse the result. - Putting default arguments before required ones:
def f(a=1, b)is aSyntaxError. Defaults go last. - Using a mutable default like
[]:def f(items=[])reuses the same list across calls, causing surprising bugs. Usedef f(items=None)and create the list inside the function. - Indentation errors in the body: Every line inside the function must be indented under the
defline.
FAQ
Can a function return more than one value?
Yes — return them separated by commas, and Python packs them into a tuple: return a, b. You can unpack with x, y = my_func().
What is a parameter's scope? Variables created inside a function are local — they only exist while the function runs and can't be seen from outside.
How many arguments can a function take?
As many as you like. You can even accept a variable number with *args and **kwargs, which you'll meet as you progress.
Once you're comfortable with functions, explore the shorter Lambda Functions in Python and the powerful idea of Recursion in Python. See all topics on the Python learning hub.
Want to learn this properly? Join the waitlist for our Python course — taught in Jalgaon, beginner-friendly.
Want to learn this properly?
Join the waitlist for our courses — beginner-friendly, project-first classes in Jalgaon.
Browse coursesInstructor, Infoplanet
Kedar Kabra teaches Python at Infoplanet, helping beginners become confident programmers through hands-on, project-first practice.
Related guides
Dictionaries in Python
Understand Python dictionaries — storing data as key-value pairs — including adding, accessing, updating, looping, and safely reading values with .get().
Exception Handling in Python
Handle errors gracefully in Python with try, except, else, and finally — so your program responds to problems instead of crashing.
File Handling in Python
Read from and write to files in Python using with open() — covering file modes, reading line by line, appending, and safe file handling.
