Skip to Content
Nextra 4.0 is released 🎉
ReferenceFunctionsFunctions

Functions

In this section you’ll learn how to define and call functions, pass them data with parameters and arguments, and get results back with return values.

What are functions?

A function is a reusable block of code that does one job. You give it a name, and whenever you need that job done, you call the function. Functions help you:

  • Organize your code
  • Make it more readable
  • Avoid repetition

Defining a function

You define a function using the def keyword, then the name you want for the function, then parentheses. When you define a function, you’re writing the code that will run later when you call it.

Here’s a simple function that greets a user:

def greet(): print("Hello, welcome to Python!")

We defined a function named greet that prints a welcome message when you call it.

Calling a function

To call a function, use its name followed by parentheses:

greet() # Output: Hello, welcome to Python!

When you call a function, the code inside it is executed. So calling greet() runs that code and prints Hello, welcome to Python! to the console.

Try it out

main.py
Output
Last updated on