Python Lesson 3: Functions

What are functions? In Python, functions are like mini programs that we can use within our main program. Functions are blocks of code which will only run when called.

Let's look at an example of a function- the print function, which looks like this:

print()

We can easily identify functions by the parenthesis we see next to them. We can use these parenthesis to define parameters for our function.

So, what does this function actually do? The print function will display any text on our screen that we ask it to. We can do this using the data types we've already learned about and placing them in the parenthesis.

Let's try using the print function. Open either the Python IDLE shell (by searching for IDLE on your PC) or Visual Studio Code. If you are using Visual Studio Code, you'll have to click File > New File > Python File to create a Python file. Now, type print() and hit Enter. You'll notice that nothing happens. This is because you need to set a parameter- in this case, we need to give it something to print.

If we use an integer by writing print(4) and run it, we'll see "4" on our screen. Likewise, if we use a float by writing print(4.3) we'll see "4.3" on our screen. For strings, we need to ensure we have quotation marks within the parenthesis, or else we'll get an error. So, while print(Hello) won't work, print("Hello") or print('Hello') will.


Lesson Recap:

  • The print function shows us text on the screen.
  • We can use the print function by typing print() in a Python document and running it.
  • We can place integers and floats in the print function to print numbers.
  • We can place text in the print function as long as it is surrounded by single or double quotation marks.

In the next lesson, we'll learn about variables.