If you’ve never heard of a function, this lesson may be hard to understand but the function is one of the most fundamental building blocks of any programming language. This tutorial will teach you about some of the key ideas of functions in python.
A basic function
This part is defining the function. Lets try a concrete example:
Remember to indent with the tab key. If you run this code, nothing should happen. This is because we have defined the function but not called it. When we call it, the real magic happens:
If you did everything right, this should print hello earthling. If you have a question, feel free to comment below or contact me. What we just did was define a function and call it. When a function is called, the indented code under the function is run. When calling the function we put the function name followed by brackets.
You may be wondering what the brackets in the function are for. They are for receiving input. Look at the following:
—-print(“hello ” + name)
Now try the following:
hi(“your name here”)
It should print hello (your name). This function takes one input name. When putting the string which is your name in the brackets, you set name to your name. If we want to take multiple inputs, we can do the following:
def function(a, b):
function(what you want a to be, what you want b to be)
Try it yourself
Try to make a function that takes two inputs name and age. If age is greater than or equal to 18 print:
You need to be 18 to use this site (name)
Where name is the variable name. Try this in python. The code should look something like this:
Try checking different ages. If your wondering, you don’t need to be 18 to use this site!
What if you want to exit a function immediately? You can use return. Try the following:
—-if(age >= 18):
——–print(“you must be 18+ to view this content”)
Try implementing this in the age check function from earlier.
Try it yourself
Remember our first game? Try turning this into a function. When the game is done, make it so the player is asked:
Do you want to play again? y or n:
If the answer is y, run the function otherwise, return. The game should look like this.