Python Variables

In the Python print lesson, we used the print function to print the “hello world” string. In Python, you can assign pretty much anything to a variable.

Strings

Here is a string:

>>> "Here is the output of my router"
'Here is the output of my router'

Maybe I have to use this string multiple times in my program. I could copy and paste it multiple times, but it’s easier to use a variable. For example:

>>> a = "Here is the output of my router"

We assign our string to the “a” variable. We can now use this variable:

>>> a
'Here is the output of my router'

Whenever I use the “a” variable, it shows my string. Great!

Numbers

We can also use this for numbers. Let’s assign a number to variable “x”:

>>> x = 10
>>> x
10

Let’s try one more:

>>> y = 5
>>> y
5

We now have a variable named “x” with number 10 and variable named “y” with number 5. You can now use these variables everywhere. Quick example:

>>> x + y
15

That’s how we do it.

Variables

You can even refer from one variable to another. Let’s take a look.

We already have the “x” variable:

>>> x
10

Let’s create a new variable named “z” which refers to variable “x”:

>>> z = x

Let’s take a closer look at variable “z”:

>>> z
10

What exactly is “z”? Is it a copy or shortcut to “x”? Let’s find out:

>>> x = 9
>>> z
10

I reassign the variable “x” to another number. This is no problem in Python. As you can see, “z” does not change. When you set the variable, Python copies the original value.

Functions

We can also assign a variable to a Python function. For example, the “input” function asks the user for an input. Here’s how it works:

>>> input()
My name is Rene

Once I type my string and hit enter, it returns the string to me:

'My name is Rene'

It might be a better idea to ask the user what kind of input you are looking for. We can add a string in the input function:

>>> input("What's your name admin? ")
What's your name admin? My name is Rene
'My name is Rene'

At least the user of our program now has an idea of what we are looking for.

Running the input function like this is pointless though. I type something, and Python returns it to me. However, when we assign the output of the input function to a variable, we can use it later in our program. Let’s go:

>>> admin_name = input("What's your name admin? ")
What's your name admin? My name is Rene

Python doesn’t return the output of the input function to me but stores it in the “admin_name” variable. We can now use this in our program whenever we want. For example, let’s print it:

>>> print(admin_name)
My name is Rene

This is how we use variables.

When you create variables, use names that have a meaning. Variabled named “x”, “y”, or “z” don’t tell me anything by looking at them. A variable with the name “admin_name” gives me a clue what is it about.

Ask a question or start a discussion by visiting our Community Forum