Skip to content

Types#

When you create a variable, it stores a particular type of information. These can be a range of things:

  • Numbers (1, 12, 5678, 78.9)
  • Booleans (True, False)
  • Strings ("Hello, world!")
  • Lists ([1,2,3]) and Tuples ((1,2,3))
  • Dictionaries ({a: 1})
  • Sets (set([1,2,3]))

These different types are a powerful way of representing different types of information. They can even be nested and mixed with each other.

Let's look at each type in a bit more detail.

Numbers#

You store integers (1), floating-point numbers (1.2), and complex numbers ((1+2j)).

An integer is a number without a decimal place. So a rounded, single value, like 1, 10, or 5678. Floating point numbers do have a decimal place to represent precision, such as 1.2, 89.789756 or even 0.0. You can use negative numbers too, like -9 or -89.89.

Complex numbers are used in science, primarily, and you're not going to see them in action in a CloudOps or DevOps capacity (it's very unlikely, anyway.)

Doing math#

You can manipulate and operate on numbers using Python's numerical operations. This includes addition, subtraction, multiplication, division, etc.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
>>> 1 + 1  # You can add numbers together
2

>>> 38 - 10 # Subtract them from one another
28

>>> 5 * 5 # Multiply them
25

>>> 25 / 5 # Divide them
5.0

>>> 25 % 2 # This is a modulus, which gives you the remainder from a division
1

>>> 25 % 5 # Here the modulus has no remainder as 5 divides into 25 exactly 5 times
0

>>> 5 ** 5 # And you can raise numbers to powers: 5^5
3125

You can numbers stored in variables, too.

1
2
3
4
>>> mynumber = 10
>>> mypower = 3
>>> mynumber ** mypower
1000

You can use functions to manipulate numbers too:

1
2
3
4
>>> float(mynumber)
10.0
>>> int(float(mynumber))
10

Here I'm converting mynumber to a float, so it goes from 10 to 10.0, but then I'm converting it again in the second example from int to float to int again. A pointless exercise, but you get the idea.

You can also convert a string of numbers to an integer:

1
2
3
4
5
6
7
>>> yournumber = "33"
>>> yournumber
'33'
>>> int(yournumber)
33
>>> float(yournumber)
33.0

Booleans#

Booleans only represent two states: true or false. The correct syntax is:

  • True
  • False

Not true or false.

1
2
3
4
5
>>> mybool = True
>>> mybool
True
>>> mybool is True
True

They're pretty obvious. We can use them to perform tests or we can perform tests to get a Boolean:

1
2
3
4
5
6
>>> mybool = True # I create some truth
>>> mybool
True

>>> mybool == yourbool # But here we test for some truth
False

The returned False from mybool == yourbool means we can do flow control based on some truthfulness.

Strings#

We store textual information inside of strings: "Hello", for example. You're going to work with strings a lot in Python, especially as you learn to process JSON and YAML data from APIs and configuration files.

With Python strings you can use single quotes and double quotes, and they're used to achieve certain combinations of strings. Let's review some examples:

1
2
3
4
5
6
>>> mystring = "Hello"
>>> yourstring = "We'll be late to the party!"
>>> mystring
'Hello'
>>> yourstring
"We'll be late to the party!"

Notice that both mystring and yourstring were created using double quotes: "...". Let's try define yourstring using single quotes:

1
2
3
4
5
>>> yourstring = 'We'll be late to the party!'
  File "<stdin>", line 1
    yourstring = 'We'll be late to the party!'
                     ^
SyntaxError: invalid syntax

So the opening ' was closed by the next single quote that Python encountered, which was the apostrophe in We'll, so everything after that point, ll be late to the party!' basically became invalid Python. That's why we used double quotes originally: to enclose the '. The same applies the other way too:

1
2
3
4
5
>>> mystring = "Then Mike said, "Dude! How's that awesome Upload Academy course going?""
  File "<stdin>", line 1
    mystring = "Then Mike said, "Dude! How's that awesome Upload Academy course going?""
                                 ^
SyntaxError: invalid syntax

Again, Python hit the second " and consider the first ", making everything after that point invalid Python: Dude! How's that awesome Upload Academy course going?"" (he said it was awesome, by the way!)

To fix this, we can switch to enclosing that string in single quotes:

1
2
3
4
5
>>> mystring = 'Then Mike said, "Dude! How's that awesome Upload Academy course going?"'
  File "<stdin>", line 1
    mystring = 'Then Mike said, "Dude! How's that awesome Upload Academy course going?"'
                                           ^
SyntaxError: invalid syntax

Whoops! But now the apostrophe in the How's is closing the string early. To get around this, we use escaping. So, we'll need to tell Python to escape the ' so that Python doesn't treat it as part of the variable definition but instead, treats it as part of the string:

1
2
3
>>> mystring = 'Then Mike said, "Dude! How\'s that awesome Upload Academy course going?"'
>>> mystring
'Then Mike said, "Dude! How\'s that awesome Upload Academy course going?"'

This is one of those things that can catch you off guard, but now you'll be prepared.

There are loads of things you can do with strings, to strings, and to get a string back from Python, but you've learned all you really need at this point in time.

Lists#

In Python, we use lists to groups things into a single type. You can put anything into a list:

1
2
3
4
5
>>> mylist = [1, mystring]
>>> mylist
[1, 'Then Mike said, "Dude! How\'s that awesome Upload Academy course going?"']
>>> mylist
[1, 'Then Mike said, "Dude! How\'s that awesome Upload Academy course going?"', ['a', 'b', "'c'"]]

You can even nest lists as I have above in the last example.

To get access to a particular value inside of a list, you must index it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
>>> mylist[1]
'Then Mike said, "Dude! How\'s that awesome Upload Academy course going?"'
>>> mylist[2]
['a', 'b', "'c'"]
>>> mylist[2][1]
'b'
>>> mylist[1][4]
' '
>>> mylist[1][6]
'i'

We created a list using []s and we then used those same brackets to index the array. We were even able to index the list inside the list: mylist[2][1] = 'b'.

Python's lists are indexed starting at 0, not 1. So, if you want the first item you index 0.

You can index in reverse:

1
2
>>> mylist[-1]
['a', 'b', "'c'"]

The inner list was the last item in the list, so that's why -1 returned it: because it went from the back to the front of the list.

And you can use an index to edit the value inside of a list, at a particular point:

1
2
3
>>> listofnumbers[-1] = 999
>>> listofnumbers
[1, 2, 3, 4, 5, 6, 7, 8, 9, 999]

I replaced 0, at index -1, with 999.

Finally you can get a "slice" of a list by providing a range inside of it:

1
2
3
4
5
6
7
8
9
>>> listofnumbers = [1,2,3,4,5,6,7,8,9,0]
>>> listofnumbers[0]
1
>>> listofnumbers[-1]
0
>>> listofnumbers[0:5]
[1, 2, 3, 4, 5]
>>> listofnumbers[3:8]
[4, 5, 6, 7, 8]

If you need to know how many items are in a list, you use can the len() function on it.

1
2
3
4
>>> len(listofnumbers)
10
>>> len(listofnumbers[3:8])
5

Note that I was able to use my result from the indexing "slice" to then feed a value into len().

Like numbers, strings, and more to come, lists have a lot more going for them, but I'm trying to get you to a point you can read Python code, so that's enough about lists for the time being.

Tuples#

Tuples are like lists, but they're immutable. That means they cannot be updated or changed after you've created them. To make a change, you must make a new tuple.

These aren't the most common type you're going to be working with, so we'll cover this lightly.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
>>> mytuple = (1,2,3,4,5)
>>> mytuple
(1, 2, 3, 4, 5)
>>> len(mytuple)
5
>>> mytuple[1]
2
>>> mytuple[4]
5
>>> mytuple[1] = 44
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

After the tuple has been created, I am unable to edit it. It's static (immutable) going forward. This is useful for when you want to define a constant value that should only be used and never changed.

They're also very powerful and very memory efficient, but given your future career prospects, that's not something we need to talk about - that's for the software engineers to worry about at this point.

Dictionaries#

You'll work with dictionaries a lot. This is primarily because you'll be reading configuration files into a dictionary type, and processing JSON from APIs, which will also be as dictionary types.

What is a dictionary?

1
2
3
>>> mydictionary = {"name": "Mike", "age": 18, "happy?": "yep!"}
>>> mydictionary
{'name': 'Mike', 'age': 18, 'happy?': 'yep!'}

Think of a dictionary as a list, but instead of using numbers like 0 or -1, you use strings. To access my name in the dictionary I created above, you'd use mydictionary["name"] and you'd get back 'Mike':

1
2
>>> mydictionary["name"]
'Mike'

The structure is essentially {} combined with key: value pairs inside the (curly) braces:

1
2
3
4
5
{
  key: value,
  key: value,
  ...
}

The key can be (almost anything) such as a number, string or tuple (but not a list):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
>>> mydictionary[1] = "2"
>>> mydictionary
{'name': 'Mike', 'age': 18, 'happy?': 'yep!', 1: '2'}

>>> mydictionary[(1,2,3)] = ["1", "2", "3"]
>>> mydictionary[False] = True

>>> mydictionary[{"a": 1}] = "wat?"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'

You can see above, I was able to use a number, tuple and a bool as a key, but not another dictionary:

1
2
3
4
5
6
7
8
>>> mydictionary[1]
'2'
>>> mydictionary[False]
True
>>> mydictionary[(1,2,3)]
['1', '2', '3']
>>> mydictionary[(1,2,3)][0]
'1'

You can get as complex as you like or need with a dictionary:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
>>> superdictionary = {
...   1: {
...     "name": "Mike",
...     "age": 18,
...     (89,34): "x,y" # not sure why you'd want to do this
...   },
...   2: {},
...   True: "It's the truth",
...   False: 'It\'s a lie!'
... }

>>> superdictionary
{1: "It's the truth", 2: {}, False: "It's a lie!"}

>>> superdictionary[True]
"It's the truth"

Hang on, how can I reference superdictionary[True] and get the string, but the dictionary looks like this:

1
2
>>> superdictionary
{1: "It's the truth", 2: {}, False: "It's a lie!"}

There's no True key anymore and the 1 key isn't the (nested) dictionary we asked for, it's the string that was meant to be assigned to 1? Well True is equal to 1, and 1 is equal to True, so Python merged the keys. Because the True key came after the 1 key, its value was merged into 1... let's look at something and then step through this:

1
2
3
4
5
6
>>> True == 1
True
>>> 1 == True
True
>>> 2 == True
False

In the land of Python (and UNIX/Linux), 1 is true and 0 is false:

1
2
3
4
>>> 0 == True
False
>>> 0 == False
True

So this is what happened:

  1. We created a key called 1 and assigned it a value (the dictionary)
  2. Later, we defined a key called True (which is a bad idea anyway) and tried to assign it a string
  3. Because 1 == True, the True was basically like saying superdictionary[1] = "It's the truth"
  4. So the 1 key's value was replaced with the string and True was never added to the dictionary

So let's fix that:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
>>> superdictionary = {
...   1: {
...     "name": "Mike",
...     "age": 18,
...     (89,34): "x,y" # not sure why you'd want to do this
...   },
...   2: {},
...   "true": "It's the truth",
...   "false": 'It\'s a lie!'
... }

>>> superdictionary
{1: {'name': 'Mike', 'age': 18, (89, 34): 'x,y'}, 2: {}, 'true': "It's the truth", 'false': "It's a lie!"}

That's fixed it. So don't use True and False as keys just because you can.

Just like lists, strings, sets, etc., you can use len() too:

1
2
>>> len(superdictionary)
4

We get 4 because there are four keys: 1, 2, "true", and "false".