Functions
A function is a named block of code that does one job. You write it once and then run it as many times as you like by calling its name. You have already used functions that come with Python, such as print(), len() and round(). In this lesson you will write your own.
Functions make programs shorter, easier to read and easier to fix. If the GST rate changes, you change one function instead of twenty copies of the same calculation.
Defining and calling a function
You create a function with the def keyword, a name, a pair of brackets and a colon. The indented lines below it form the body of the function.
def welcome():
print("Namaste! Welcome to Kochi Cricket Academy.")
print("Practice starts at 6 am sharp.")
welcome()
welcome()Namaste! Welcome to Kochi Cricket Academy. Practice starts at 6 am sharp. Namaste! Welcome to Kochi Cricket Academy. Practice starts at 6 am sharp.
Writing def welcome(): only defines the function. Nothing is printed at that moment. The body runs when you call the function by writing its name followed by brackets: welcome(). Here we call it twice, so the two lines print twice.
Function names follow the same rules as variable names: lowercase words joined with underscores, such as send_reminder or total_marks. Choose a verb that says what the function does.
Parameters and arguments
Most functions need some input. You list parameters inside the brackets of the definition. When you call the function, the values you pass are called arguments. Each argument is stored in the matching parameter, in order.
def greet(name, city):
print(f"Hello {name} from {city}!")
greet("Meera", "Kochi")
greet("Farhan", "Lucknow")Hello Meera from Kochi! Hello Farhan from Lucknow!
Inside the function, name and city behave like normal variables. They exist only while the function runs. Python has many more ways to pass arguments, such as default values and keyword arguments; you will learn them in Function Arguments.
Returning a value
A function can send a result back to the code that called it with the return statement. The call then becomes that value, so you can store it, print it or use it in another calculation.
def price_with_gst(price, rate):
tax = price * rate / 100
return price + tax
headphones = price_with_gst(1299, 18)
print(headphones)
print(f"Bill for two: ₹{headphones * 2:,.2f}")1532.82 Bill for two: ₹3,065.64
return also ends the function at once. Any lines after a return that runs are skipped. This lets you leave early as soon as you know the answer:
def grade(marks):
if marks >= 90:
return "A"
if marks >= 75:
return "B"
if marks >= 40:
return "C"
return "Fail"
for student, marks in [("Aarav", 93), ("Priya", 78), ("Rohan", 35)]:
print(student, grade(marks))Aarav A Priya B Rohan Fail
A function without a return statement, or with a bare return, gives back the special value None, which means "nothing".
Returning more than one value
Sometimes you need two answers. Write them after return separated by a comma. Python packs them into a tuple, and the caller can unpack them into separate variables (see Tuples).
def lowest_and_highest(scores):
return min(scores), max(scores)
low, high = lowest_and_highest([62, 88, 45, 91, 70])
print("Lowest:", low)
print("Highest:", high)Lowest: 45 Highest: 91
Docstrings: explain your function
A docstring is a string in triple quotes placed on the first line of the function body. It describes what the function does, what it needs and what it returns. Editors show it when you hover over the function name, and help() displays it.
def km_to_miles(km):
"""Convert a distance in kilometres to miles.
Returns the distance as a float.
"""
return km * 0.621371
print(round(km_to_miles(42.195), 2))
print(km_to_miles.__doc__.splitlines()[0])26.22 Convert a distance in kilometres to miles.
Every function stores its docstring in a special attribute called __doc__, which the second print() reads. The first line of a docstring should be one short sentence. You will see more about docstrings in Testing & Best Practices.
Common mistakes
- Printing instead of returning. A function that only prints gives back
None, so you cannot use its result later. Compare the two versions below. - Forgetting the brackets.
welcomewithout()does not call the function.print(welcome)shows something like<function welcome at 0x...>instead of running it. - Calling before defining. Python runs a file from top to bottom. If the call comes before the
defline, you getNameError: name 'welcome' is not defined. - Wrong number of arguments. Calling
greet("Meera")when the function needs two values raises aTypeErrorthat names the missing argument.
Here is the print-instead-of-return mistake in action:
def add_marks(a, b):
print(a + b)
total = add_marks(45, 38)
print("Total is", total)83 Total is None
The function printed 83 but returned nothing, so total is None. Change print(a + b) to return a + b and the last line prints Total is 83.
Key points
- Define a function with
def name(parameters):and an indented body; call it withname(arguments). - Parameters are the names in the definition; arguments are the values you pass when calling.
returnsends a value back and ends the function; without it the function returnsNone.- Return several values separated by commas and unpack them at the call.
- Add a docstring as the first line of the body to explain what the function does.
- Prefer returning values over printing inside the function, so the result can be reused.
Exercise
A cinema in Jaipur charges by age: children under 5 watch free, ages 5 to 17 pay ₹150, people aged 60 or more pay ₹120, and everyone else pays ₹250. Write a function ticket_price(age) that returns the price as a number. Add a docstring. Then use a loop to print the price for the ages 3, 12, 30 and 65.
Show solution
def ticket_price(age):
"""Return the ticket price in rupees for a viewer of the given age."""
if age < 5:
return 0
if age < 18:
return 150
if age >= 60:
return 120
return 250
for age in [3, 12, 30, 65]:
print(f"Age {age}: ₹{ticket_price(age)}")Age 3: ₹0 Age 12: ₹150 Age 30: ₹250 Age 65: ₹120
Each return ends the function as soon as the right price is found, so the checks never overlap. The function returns numbers rather than printing, so the loop decides how to display them.
Quick Quiz
1. What does a function return if it has no return statement?
Without return, a Python function gives back None when its body finishes.
2. In def greet(name): and the call greet("Isha"), what is "Isha"?
The value passed in a call is an argument; name in the definition is the parameter.
3. What happens to lines that come after a return statement that runs?
return exits the function immediately, so later lines in the body do not run.
4. What does return a, b give back?
Values separated by commas are packed into a tuple, which the caller can unpack.
Learn Python with a mentor
Free lessons get you started. Our Python Programming training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
