Learn practical skills, build real-world projects, and advance your career

Creating and using functions

A function is a reusable set of instructions. A function takes one or more inputs, performs certain operations, and often returns an output. Python provides many in-built functions like print, and also allows you to define your own functions.

today = "Saturday"
print("Today is", today)
Today is Saturday

You can define a new function using the def keyword.

def say_hello():
    print('Hello there!')
    print('How are you?')

Note the round brackets or parantheses () and colon : after the function's name. Both are essential parts of the syntax for defining a function. The body of the function can contain one or more statements which are to be executed when the function is called. Simlar to conditional statements and loops, the statements must be indented by 4 spaces.

The statements inside a function's body are not executed when a function is defined. To execute the statements, we need to call or invoke the function.