Lesson 2 · Python Foundation
Reusable blocks of code.
You've been using functions all month without building one. print(), len(), int(), input() — each is a named piece of work somebody else wrote.
Now you write your own:
def greet(name):
print("Hello,", name + "!")
greet("Ananya")
greet("Bilal")
def defines it. The name is yours. The brackets hold whatever information it needs. Write it once, call it as often as you like.
A function takes information in and can hand a result back:
def calculate_average(marks):
total = sum(marks)
return total / len(marks)
class_a = [85, 92, 78]
print(calculate_average(class_a))
marks is a parameter — information going inreturn sends a value back to whoever called itThe difference between print and return matters: print shows a value to a human; return hands it back to the program so it can be stored or used in further calculation. A function that prints when it should return can't be built on.
6 more parts in this lesson
Walkthroughs, code labs, mini-games and the checkpoint quiz unlock when you buy the course.