Python tutorial – How to create basic functions

In Python, a function is a block of code that only runs when it is called later on in the code. Data can be passed into the functions too. One example of a function is print. It runs when it is called in the code, and the text you put inside the bracket is the data being passed into the function.

In this tutorial, I will be demonstrating how to create a basic function that squares a number. First of all, we must “declare” a function by using def:

def square(x):

square is the name of the function, and x represents the data that will be passed into the function.

We will then create a variable for the square number of x. Do this by doing:

answer = x * x

answer is the variable that will store the answer. x * x will multiply x by x, so squaring it.

We must then return the output so the program will read it when the function is called. Do this by adding:

return answer

Then cancel the extra tab and write:

number = int(input("Enter a number: "))
number_squared = square(number)

The first line asks the user to enter a number and then stores it in the number variable. int is used to tell Python it is a number. The second line passes the number into the square function as x and then stores it as the varable number_squared. The third line prints this.

The final code should look like this:

def square(x):
answer = x * x
return answer

number = int(input("Enter number: "))
number_squared = square(number)

The end result should look like this:

I hope that this tutorial helped you in some way. There are many other functions you can create, for example you could go further and cube the number, or create a function to work out the area of a rectangle or triangle. The possibilities are endless.

Go on, you know you want to! Leave a comment

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: