Skip to content

Basic Functions

  • Lesson
  • 2 min read
  • 2 of 4 in this chapter

Syntax

To define (write the commands you want a function to do when called) a function in Python, we must follow a certain format.

Python
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.

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

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:

Python
function_name()

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

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

say_something()

OUTPUT

Text
Hi, 2 + 3 equals 5.

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

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

say_something()
say_something()
say_something()

OUTPUT

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

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.