Functions and Variables

The most essential stuff in python

Functions

How to make them and how helpful are they?

I call functions 'mini scripts' because they run ONLY if they are being called and they can be called how many times you want.

A good example of a prebuild function is the 'print' function , it will output to the console the string or the numbers you asked for. It can have an unlimited number of parameeters [we'll talk about that in the next lesson]

How Do I Make My Own Function in Python?

First of all , make a new python file to write all the stuff in it. We are gonna make a function that will say your name depending on how many times you called it.

Start by typing def say_name(): , then on the next line press TAB then write print("David") [If your name is David] and it should look like this:

Now that you defined your function , it's time to call it [just creating it doesn't mean it will run even tho' it will check for syntax error as any code you write]

Now that I made it , how do I use it?

After the function , without any spaces , type say_name()

If you don't put the parenthesis , you will call the object and not a function , so use

parenthesis

This is how it should look like

I will make screenshots when I think you might be confused on what the result should be.

Try to run the script and see what happens yourself before reading up. Done? The script will say "David" in the console or any name you put there. Now we are gonna use a variable instead of hardcoding it in the function.

Variables

What are them and how helpful they are?

You can imagine variables as a way to store values for later use instead of writting the answer real time. They are really helpful later on , since hardcodding everything it's gonna take A LOT of time.

The way you define a variable is really easy compared to other languages and you basicly give it a name , then an equal sign , then a value and depending on the value it will get a data type. Example name = "David"

If you don't put the " "

python will think that you try to make the variable called name to have the same value as variable called David

How do I include them in the function we declared before?

Before the function write name = "David" . If you run the script now you will see that ... well nothing is changed , but we missed 1 thing . We made a variable with your name , but we didn't make print to use it . Now replace the "David" from the print from our function we made , and put name instead. It should look like this:

Practice Makes Perfect

Your homework will be to make a function that will print out the title "Warcraft III" when the function is called.

Try changing the variable name in both places to match the context and use the example from before as much as possible [If you don't know how to do it , you can find my discord on part1 that shows the basics of python]

Last updated

Was this helpful?