Intermediate · Functions · topic 18 of 50 · 20 min
Defining and calling functions
Explanation
Why functions?
You have already used functions that Python gives you: print(), len() and sum(). A function is a named block of code that does one job. You can also make your own. Then you write the steps once and use them again and again just by calling the name.
Defining a function
Defining a function means writing it. Start with the word def, then the function name, round brackets and a colon. The lines below it, indented by 4 spaces, are the body: the steps the function runs. Defining a function does not run it. Calling a function means running it: you write its name with brackets.
def greet():
print("Namaste!")
print("Welcome to the class.")
greet()
greet()Inputs: parameters
def greet(name):
print("Namaste,", name)
greet("Asha")
greet("Ravi")return: giving a value back
return ends the function and hands a value back to the code that called it. You can store that value in a variable, print it, or use it in a calculation.
def with_gst(price):
return price + price * 18 / 100
bill = with_gst(200) + with_gst(100)
print(bill)return versus print
def show_total(a, b):
print(a + b)
result = show_total(2, 3)
print(result)return also stops the function at once. Any lines after a return that runs are skipped.
def result(marks):
if marks >= 40:
return "Pass"
return "Fail"
print(result(75))
print(result(30))Docstrings: explaining your function
def area(length, width):
"""Return the area of a rectangle in square metres."""
return length * width
print(area(5, 4))
print(area.__doc__)Watch the lesson
Defining and calling functions · 1/7
In this lesson you will write your own functions, named blocks of code that do one job.
Prefer a video by a teacher? Find free videos on “python functions def return tutorial for beginners” on YouTube ↗
In real life: A hostel mess bill
The hostel warden works out the mess bill for every student each month: days eaten times the daily rate, plus extras like eggs or juice. Instead of writing the same sum 200 times, she writes one function and calls it for each student. If the rate changes, she fixes one line.
def mess_bill(days, rate, extras=0):
"""Return a student's monthly mess bill in rupees."""
return days * rate + extras
print("Asha:", mess_bill(30, 90))
print("Ravi:", mess_bill(26, 90, 150))
print("Meena:", mess_bill(28, 90, 60))Practice (0/3 done)
Write a function square(n) that returns n multiplied by itself. Example: square(7) returns 49.
This with_gst(price) function prints the answer but does not return it, so the rest of the program cannot use it. Fix it so that it RETURNS the price plus 18% GST, rounded to 2 decimal places.
Write a function grade(marks) that returns "A" for 90 or more, "B" for 75 to 89, "C" for 40 to 74, and "F" below 40.
Quick quiz
Read more (free)
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.