Lesson 1 of 10
You have been calling functions since lesson 1.2 — print(), len(), input(), range(). Now
you'll write your own.
A function is a named block of code that runs only when you call it.
def greet():
print("Hello!")
print("Welcome to Python.")
greet()
greet()
Breaking that down:
defstarts the definition.greetis the name — same rules as variable names,snake_caseby convention.()holds the parameters (none yet).:and an indented body, exactly likeifandfor.
Defining a function does not run it. The body only executes when you write greet().
Why bother?
Suppose you print a separator line in three places:
print("-" * 20)
print("Section one")
print("-" * 20)
print("Section two")
print("-" * 20)
Now say you want = instead of -. You have to change three lines and hope you didn't miss
one. With a function, there is exactly one place to change:
def separator():
print("-" * 20)
separator()
print("Section one")
separator()
print("Section two")
separator()
That is the real point of functions: one idea lives in one place. Programmers call this DRY — Don't Repeat Yourself.
Order matters
Python reads top to bottom, so a function must be defined before you call it:
say_hi()
def say_hi():
print("Hi!")
That raises NameError: name 'say_hi' is not defined. Define your functions first, then call
them.
Calling from inside another function
Functions can call other functions. This is how programs get built out of small pieces:
def separator():
print("-" * 20)
def header():
separator()
print("MY PROGRAM")
separator()
header()
Try it yourself
Write a function called greet that prints two lines, then call it twice.
Checkpoint
def name():defines a function;name()calls it.- The body must be indented, and defining is not the same as running.
- Functions must be defined before they are called.
- Functions keep one idea in one place, so you change it once.
Questions about this lesson
Log in to ask a question.