Python Guide #4: Functions
After this guide you will know what are functions and how to use them.
What is a function?
Functions are used to pack set of instructions into one command. They can either perform some task, or they may return some value based on parameters, or they can do multiple of those things at once.
How to declare and use functions in Python?
You already used a function if you went through the previous guides.
print() is a function, it takes one or more parameters and prints them onto the screen.
Imagine you would like to add user to a database. First, you would need to see if data provided by user fits the specified norms (phone number consists of integers for example). Then you would have to login into database, then you would like to send response to the user, that task succeeded or that it failed.
To make code more clear, tasks are divided into single functions, sometimes stored in a different file.
To make everything more visual, lets modify “Hello World!” program to use functions.
# Lets declare a function def hello_world(): print("Hello World!") # Function is declared, now we can # call it from anywhere in that script hello_world()
Once you execute this program, you will see that output is same as in previous tutorials.
Now example with function returning a value
def get_hello(): return "Hello World!" # Now if we call a function, it will return # Hello world message message = get_hello(): # message = "Hello World!" print(message)
Output will stay the same
Functions can also accept parameters, which will modify behaviour of a function
def hello(name): print("Hello", name) # Function above accepts one parameter, # then passes it to print() # When we will call hello() # it will display Hello and passed parameter hello("John")
Execute this program yourself and see what output will be