Syllabus Lesson 19 of 239 · Functions
Functions

Defining a Function

A function is a named block of code you can run again and again. You define it once, then call it whenever you need it.

Define one with def, a name, parentheses, and a colon. The indented lines below are the function body:

def say_hello():
    print("Hello!")

Defining it does not run it. To actually run the body, you call the function by writing its name followed by parentheses:

say_hello()   # prints: Hello!
say_hello()   # prints it again

Most useful functions hand a value back with return. The moment return runs, the function stops and gives that value to whoever called it:

def lucky_number():
    return 7

result = lucky_number()
print(result)   # prints: 7

A function with no return hands back None automatically. return is how a function reports its answer.

Your turn

Define a function called greeting that takes no parameters and returns the string "Hello!". Then call it, store the result in a variable named message, and print(message).

Spotted a problem in this lesson? Report it

Code · runs in your browser
Output