Intro To Python Programming – Part 1: Variables

Hello and welcome to the next installment of the intro to Python programming series. Today I want to go through variables. It’s super easy so it shouldn’t take too long for you to get through. Things will start getting more interesting soon, I promise!

 

Variables

Variables are a core concept for programming in general. They’re present in every programming language and thankfully they’re easy to understand. A variable holds a value that can change. Its pretty much that simple. We create the variable by writing its name and then setting it equal to the desired value.

There are a few naming rules for defining variables in Python. If you break any of these rules, Python will complain and throw you an error:

  1. names can only contain: letters, underscores and numbers
  2. names cannot start with a number
  3. you cannot use spaces (use underscores instead)
  4. you cannot use python keywords
  5. please, for everyone’s sanity (and your own), use good variable names! They should be descriptive and not too long.

Now with that said see below for some examples:

Strings

Text variables are called strings, as they represent a string of characters. The value of a string must be enclosed in either single, or double quotes:

text_variable = "This is an example of a text variable!"

You can use the print() function to display a variable’s value:

text_variable = "This is an example of a text variable!"
print(text_variable)
>>> This is an example of a text variable!

We can also use the type() function to find what type of variable we are working with:

type(text_variable)
>>> <class 'str'>

We can add strings together by using the addition operator (+):

string_1 = "this is the first bit..."
string_2 = "and this is the second bit!"
string_3 = string_1 + string_2
print(string_3)
>>> this is the first bit...and this is the second bit!

Adding two strings together has the fancy name concatenation. It just means ‘linking things together’, but you’ll probably see it quite often.

 

A note on Whitespace

Whitespace is just a term for things like spaces, tabs  and new lines (There are others but those three are the common ones). Whitespace is not visible to the user, but changes the format of the displayed text.

To create a tab, we use the “\t” character combination:

print("tab\texample")
>>>> tab     example

To create a new line, we use the “\n”  character combination:

print("newline\nexample")
>>> newline
>>> example

 

Numbers

Numerical variables are created pretty much the same as string variables, but we don’t need to use the quotation marks:

my_number = 1
print(my_number)
>>> 1

Whole numbers are called integers. Numbers with a decimal point are called floats (or floating-point numbers). I’m not going to go into why their called floats here, I’ll probably do a dedicated post to floats and decimals at some point in the future to get into the details.

We can use mathematical operators on our numerical variables as follows:

Addition:

number_a = 5
number_b = 3
number_c = number_a + number_b
print(number_c)
>>> 8

Subtraction:

number_a = 5
number_b = 3
number_c = number_a - number_b
print(number_c)
>>> 2

Division:

number_a = 6
number_b = 3
number_c = number_a / number_b
print(number_c)
>>> 2

Multiplication:

number_a = 6
number_b = 3
number_c = number_a * number_b
print(number_c)
>>> 18

 

We can also use brackets to change the order of mathematical operation:

print(1 + 2 * 3)
>>> 7
print((1 + 2) * 3)
>>> 9

 

Sometimes Weird Things Happen When I Use Floats…

Occasionally, you’ll see something like this:

print(0.1 * 3)
>>> 0.30000000000000004

Don’t worry, mathematics is not broken. This happens because computers are based around the base-2 number system. I’ll spare you the boring details but it means that a computer can’t calculate the exact value of some mathematical operations, so it does it’s best and comes up with those really long decimal numbers.

(If you want a post on this stuff then leave a comment, I actually find it super interesting so I might make one anyway… Yes I know I’m weird).

 

Converting Variable Types

You can convert variables to new types. For example, what if I have the number 100 stored as a string and I want to add 10 to it?

string_100 = "100"
string_100 + 10
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
>>> TypeError: must be str, not int

That won’t work because you’re trying to add an integer to a string. So we need to convert string_100 to an integer:

int_100 = int(string_100)
int_100 + 10
>>> 110

I won’t go through each conversion between every type of variable here, but you can use str() to convert to string, float() to convert to floating-point and int() to convert to integer.

 

Lists

So what if we want to store a group of variables together? There are a few ways we can do that, the first one is by using a list. A list is just a number of things which get stored together. They are created by using the square brackets []:

my_list = [1, 2, 3, 4]

A list can be as long as you like, and can store any variables or objects, but it is good practice to only store related things together.

One of the most useful things about lists is that they are an iterable. An iterable is a fancy way of saying we can go through each element in the list and do something with it. This is best show in an example:

 

colors = ["red", "blue", "green"]

for color in colors:
    print("The color is: " + color)

>>> The color is: red
>>> The color is: blue
>>> The color is: green

I’ll go over loops properly in the next post, I don’t want this one to get too long.

We can also get individual items in a list by using indexing. Lists are 0-indexed, this means that when we go through the elements in a list, the first one is said to be at index 0, the second at index 1, third at index 2 etc. See the example below for a better idea of what I mean:

colors = ["red", "blue", "green"]

color[0]
>>> "red"

color[1]
>>> "blue"

color[2]
>>> "green"

 

We can also use negative indexing to ‘count back’ in the list too. so if we wanted to get the last element in a list:

colors = ["red", "blue", "green"]

colors[-1]
>>> "green"

Or the second to last etc:

colors = ["red", "blue", "green"]

colors[-1]
>>> "green"

colors[-2]
>>> "blue"

colors[-3]
>>> "red"

 

If we want to find the index (the position) of an element in a list, we can use the index() function (again, I’ve used the term function quite a lot this post, I will be covering them in detail in another post).

colors = ["red", "blue", "green"]

colors.index("blue")
>>> 1

The append() function can be used to add something to a list:

colors = ["red", "blue", "green"]
colors.append("black")
print(colors)
>>> ['red', 'blue', 'green', 'black']

We can add as many things as we want to list (or at least, as many things as the computer has enough memory for).

There are loads of really useful things we can do with lists, they’re probably worth a dedicated post (things like removing/popping, sorting, enumerating, list comprehensions etc). The only other thing I will put in about lists here is the len() function. When we use len() on a list, it returns the number of items in it. Really simple idea, very useful in practice.

colors = ["red", "blue", "green"]
len(colors)
>>> 3

 

Tuples

Tuples are very similar to lists however, they cannot be resized. This means you can’t add or remove items from a tuple once it’s been created. We can create a tuple in much the same way we did a list, only this time, we use the normal brackets () instead of the square ones.

colors = ("red", "blue", "green")

We can still index and iterate over tuples in the same way as lists, we just can’t change them.

 

Dictionaries (aka dicts)

Last on my list for today are dictionaries. They’re a bit more involved than the other variable types, and I was debating whether or not to include them in this post, but I figured I’ll give you a quick introduction to them now.

A dictionary (or dict for short), is a way of storing bits of related data. They’re really useful and really important for a lot of Python. I will be doing a dedicated post on these in the future because they’re so frequently used and can save you so much time and brainache!

Dicts work by storing data in what are known as key-value pairs. The best way to explain it is with an example:

my_dict = {"a_key": "a_value", "another_key": "another_value"}

Notice that each key-value pair is separated by a comma.

To get a piece of information, we can use something similar to the indexing notation we used on lists. The difference is, this time, we will use a key instead of an index:

my_dict = {"a_key": "a_value", "another_key": "another_value"}
print(my_dict["a_key"])
>>> "a_value"

We can store pretty much anything in these key-value pairs so dicts become really powerful when storing lots of related data. Here is an example of a dict that uses a few different types of data:

student_info = {
    "first_name": "Rich",
    "last_name": "Smith!",
    "test_scores": [1, 3, 5, 3, 7],
    "average_score": 3.8,
    "address": {
        "line_1": "1 Python Street",
        "line_2": "Pythonville",
        "line_3": "Python"
    }
}

Lets go through that example. Firstly, you can see I wrote the dict over a number of lines, each key-value pair on a separate line. This is perfectly valid, and way more readable than having it all on the same line. Second, you can see there are a few different types of data stored in it (strings, integers, floats, a list, and even another dict (storing a dict in a dict is called nesting, i.e. they are nested dictionaries. You can also do this with lists). All these different types of data are accessed in exactly the same way, we use the key of the key-value pair:

print(student_info["first_name"])
>>> "Rich"

print(student_info["scores"])
>>> [1, 3, 5, 3, 7]

If we wanted to get the first line of the students address, we just use two keys:

print(student_info["address"]["line_1"])
>>> "1 Python Street"

That looks a little more complicated, but just break down each step and you can see its actually pretty simple. First, we want to get the address dict stored in the student_info, so we use the “address” key to get it. Then we want the first line of the address, so we use the “line_1” key on the address dict we just got.

Again, there are loads of other things you can do with dicts. I don’t want to put any more in this post because its getting pretty long. I’ll do a post just on dicts in the near future which will go into much more detail.

 

Summary

So that was a brief overview to variables in Python. Hopefully it wasn’t too boring! If you have any questions please leave a comment and I’ll get back to you ASAP. The next few posts should be a bit more interesting. I think it’ll probably be on functions (especially as I’ve used the term and applied them in this post a fair bit). I’ll also try to write those posts on lists and dictionaries soon. There’s a lot of really cool stuff to learn there.

 

See you next time and thanks for reading!

 

Leave a Reply

Your email address will not be published. Required fields are marked *