11Functions

Programs in Python often repeat the same set of actions defined in a block of code. Rather than rewrite the same block of code repeatedly in your program, create a function that you can use anywhere you need.

Create a Function

In Python, every function has a name, which is what you use to call it. Here's the syntax for defining a function:

“The syntax used for defining a function. All functions start with the keyword def followed by the name of the function and a pair of parentheses. The function body contains whatever actions you choose to have your function complete.”

All functions start with the keyword def followed by the name of the function and a pair of parentheses. Just below the function is the function body. The function body contains whatever actions you choose to have your function complete.

Here is an example of a hello_world function that prints the string "Hello World":

>>> def hello_world():
        print("Hello World") 

Call a Function

The function in the prior example won't do anything in your program until you call the function. Calling a function tells your code to run the code inside the function body. To call a function, use the function name and include the parentheses. The parentheses specifically say, “Treat the name as a function and call it.”

>>> hello_world()
Hello World
 

Notice how you don't need to include a print statement in the function call. Since the hello_world() function includes a print statement in the function body, the string inside the function prints whenever the function is called.

It's worth noting that a function can do more than print strings! Essentially, ...

Get Bite-Size Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.