Register to get access to free programming courses with interactive exercises

Definition of functions Python Basics

It is easier to write and maintain programs when you define your functions. They allow you to combine compound operations into one. So in this lesson, we will learn how to create your functions.

How to define functions

Suppose we want to send emails on a website. This complicated process involves interaction with external systems. But you can hide its complexity behind a simple function you define:

# It is a hypothetical example
# Where does the function come from?
from emails import send

email = 'support@hexlet.io'
title = 'Help'
body = 'I wrote a success story, how can I get a discount?'

# There is one call with complex logic inside
send(email, title, body)

This call does a lot internally. It connects to the mail server, forms a valid request containing the message header and the body, sends everything out, and closes the connection.

Now, we will create our first function. Its task will be to display a greeting:

Hello, Hexlet!
# Defining a function does not invoke or execute it
# We just say this function exists now
def show_greeting():
  # Indent four spaces inside the body
  text = 'Hello, Hexlet!'
  print(text)

# You see the function call here
show_greeting()  # => 'Hello, Hexlet!'

Unlike ordinary data, functions perform actions. Therefore, we should specify their names through verbs: build something, draw this, open that.

The information indented below the function name is the body of the function. We can enter any code within the body. It resembles a small independent program with whatever instructions you put in.

We execute the body when we start the function. In this case, each function call launches the body of the other calls independently.

The body of the function can be empty. In that case, we use the keyword pass inside it:

# It is a minimal function definition
def noop():
  pass

noop()

The term "to create a function" has many synonyms. For example, you can implement or define it. Programmers often use these terms in the real world. By creating your function, you can easier make complex operations and development.


Recommended materials

  1. Naming in Programming

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

Bookmate
Health Samurai
Dualboot
ABBYY