Functions in Python

Functions in Python

Guide to functions for python beginners

def hello():
    print("hello world")

What's a function?

A function is simply a reusable block of code that you use to perform repetitive tasks.

Why use a function over just plain code?

  • Functions save you the stress of having to rethink how to write code that performs a specific function

  • It saves you a lot of time as you only have to call it once per request

  • they make your code neater


Now that we've understood the basics of what a function is let's move to making one

Defining your function

Using lower-case names

When defining a function you typically want to follow a few rules, for one you'd want it to be lowercase and spaces should be indicated with underscores, this is not required but it's a good convention to follow.

# proper way
def my_function():
    print("hello world")

# improper way
def My_Function():
    print("hello world")

while both functions will run it's recommended to use the first method for proper readability

Using relevant names

Just as with variables, functions should be named with relevant words to the tasks which they're to carry out


Writing Code!

This is where the fun begins, building your function. With all that we've learned above we are ready to create our first function.

we start our function by defining using the def keyword

def

now we name our function, and pick a name that relates to what you want it to perform, for this example, I'll be naming it hello since it's going to print "hello world" to the user

def hello():

noticed the brackets after the hello? that's where you store parameters for your function (in more complex functions). but for now, we want a very basic one so finish it off by entering a new line and inserting a tab or four spaces (based on your preference) and then a print statement to finalize the function

def hello():
    print("hello world")

hello()
# > hello world

once u call the function using hello() it should return hello world

Notes

In most cases, you may want to use a return statement instead of a print as print only send values to the terminal while return gives out a value that's useable anywhere in your code
Example:

def hello():
    return "hello world"

print(hello())
# > hello world

by using a print statement we sent the value obtained to the terminal.

And that's how u make your first function :)