Python

Basic Functions

Writing functions in Python

Syntax

To define (i.e. write the commands you want a function to do when called) a function in Python, we must follow a certain format. That is as follows:

def function_name():
	# Your commands go here …

Replace ‘function_name’ with whatever name you want to give the function. We’ll go over what the parentheses do later. Make sure that you leave an indent between the function name line and the lines with your code. Without the ‘tab’ indent, Python will not understand what you are asking it to do. Here’s an example:

def say_something():
	sum = 2 + 3
	print("Hi, 2 + 3 equals " + str(sum))

NOTE: Even after you have defined a function, the code will not run until it is actually ‘called' or run.

Calling Functions

To actually ‘call’ a function, is to make it run the commands we assigned to it. In Python, to do this, we simply write:

function_name()

So, with our example, the file would look something like this:

def say_something():
	sum = 2 + 3
	print("Hi, 2 + 3 equals " + str(sum))

say_something()

Output:

Hi, 2 + 3 equals 5.

And, if I wanted to repeat code multiple times, I could do that too, in just a few lines…

def say_something():
	sum = 2 + 3
	print("Hi, I am moving forward " + str(sum) + " units.")

say_something()
say_something()
say_something()

Output:

Hi, I am moving forward 5 units.
Hi, I am moving forward 5 units.
Hi, I am moving forward 5 units.    

NOTE: I know that functions seem pretty pointless and an extra hassle right now. But trust me, with complex code, functions become extremely useful.

Also, the str() is used to change data from an integer or float type to a string data type. This basically converts the data to text that we can use in strings, print statements, etc.

chevron_up