Variables & Types, What You Need to Know — Python 101

Jacob Talks Tech
12 min readNov 14, 2022

Let’s dive into booleans, strings, integers, floats, dictionaries, sets, lists, and more!

Variables are a key part of any language, and each variable holds data of a certain type. In this article we will cover all of the basic variable types in Python and highlight some key operations.

There is so much detail out there, which you can dive into in the full Python documentation, but I think that to get started quickly, it is better to read a shorter summary that will give you the key bits first. I highly recommend having a Python IDE open so you can run these code snippets yourself.

Now lets dive in!

Types

Python is not a statically typed language. Python has types, but you do not have to declare types and you can change the type of a variable implicitly by reassigning to a value of a new type.

Boolean

The simplest kind of variable — a boolean variable is simply a True or False, yes or no, 1 or 0. It is sometimes called a flag.

Lets define a Boolean:

is_cool = True

Here we define a new variable called is_cool and we assign it the value True. Note that the capitalization of the T in True is necessary for Python to know you mean the truth value True, not some variable that you have named true that doesn't exist.

Uses

Boolean values can be used in if statements:

is_cool = True 
if is_cool:
print('Wow this is cool. ')
else:
print("This isn't very cool...")

You can see that depending on the value in the Boolean variable, a different sentence will be printed.

You can also use them in loop conditions:

import time 
running = True
start_time = time.time()
while running:
current_time = time.time()
if current_time - start_time <5:
print(f'We are still running at time = {current_time}...')
time.sleep(1)
else:
running = False
print('Ending the loop!')

Here we can see that the loop ends when the boolean variable running becomes False.

Operations

Booleans work very well with logical operators. You can use booleans with logical operators like: and, or, not to create complex conditions.

For example, can you predict what the output of this program will be?

owns_coat = True 
lost_coat = False
raining = False
cold_outside = True
print((raining or cold_outside) and owns_coat and not lost_coat)

If you guessed True, you are correct! We are using several logical operators, and brackets are used to make sure that the right order of operations is used.

You can check out more on booleans on the official documentation.

String

A string is a data type that is for text. For example, we can define a new string variable like my_string = "Hello World!".

Note that strings can be defined with single quotes, or double quotes. It usually does not matter, except when you have quotes in the string you want to store like if you want to store the string "Can't" you need to use double quotes so the single quote in the word doesn't end the string early.

Uses

Strings are used everywhere, often for storing text to be used to interact with a user, or for storing information.

For example, you might want to record a user’s name in a program:

greeting = "Welcome! " 
print(greeting)
name = input("What is your name? ")
print(f"Nice to meet you, {name}.")

Here we define a greeting string which will be printed, and then we get the user’s name. In order to get their name, we pass a string which will be shown to the user to tell them what to input. We then store their input in a string variable called name which we then print inside another string. Here is what the conversation looks like when you run it and type your name:

Operations

Strings have a lot of different methods and operations available, for example you can concatenate (add end to end) two strings together with "Hello " + "World" returns Hello World.

You can convert a string to lowercase with my_string.lower() .

Often you want to split an input sentence into a list of individual words, you can do this with the my_string.split(separator) method, where for example the line "Hello I like dogs".split(' ') would split that string by the spaces and result in the list ['Hello', 'I', 'like', 'dogs'].

Another very common thing to do with strings is string formatting. String formatting is when you want to insert values into strings. Like in the example above where we printed the string “Nice to meet you, “ with the user’s name inserted at the end. You can do this with the syntax f"Hey my favourite colour is {fav_color}". In this line, you are putting an f immediately in front of the string to indicate that Python should look for any matching curly braces in the string to insert variables into. You are then putting the variable you want to insert, in this case a string variable holding the user's favourite colour, in a pair of curly braces. Assuming the user's favourite colour is blue, this would return the string "Hey my favourite colour is blue".

You can check out more string methods in this list by W3Schools.

Integer

Integer variables contain whole numbers, positive and negative. For example, we can define a new integer num_eggs = 12

Uses

There are all kinds of uses for integers, and one common use is for counts of things. For example, you might count the number of times that someone has tried a password and compare it to a limit.

max_tries = 3 
current_tries = 0
password = "Apples"
while current_tries < max_tries:
current_tries = current_tries + 1
user_input = input('Please input the password: ')
if password == user_input:
print('Access Granted!')
break
else:
print('That is incorrect. ')

In the code above you can see how we instantiate (define for the first time) several variables before the loop, and then we start a loop on a condition comparing two integers. Inside the loop, we increment the number of tries, until the integer is large enough for the loop to end.

Or alternatively, if the correct password is given we would break out of the loop before hitting the limit.

Operations

Integers can be used in all of the normal mathematical operations you would expect:

height = 10 
width = 5
print(height * width)
print(height + width)
print(height - width)
print(height // width)

You can also apply these operations during assignment. For example if you want to increment a variable by 1 you could write my_variable = my_variable + 1 or you could write my_variable +=1 which is a short form that will allow you to increment by a number and reassign to itself. You can do this with other operators like my_variable *=3 to triple the value of the variable.

You can also use modulo operator, to return the remainder after integer division. For example 15 % 11 == 4 because 15 divided by 11 is 1 with 4 remainder. This is convenient in cases like recording the time, as when you hit 60 minutes it goes to the next hour and the minutes reset to zero.

Check out this documentation for numeric types which goes over all operators.

Floats

Floats are short for floating point, meaning numbers with decimal places. You can store numbers like 3.34, or -0.0056 in these variables. You can define a float variable like my_float = 3.14.

The operations and uses of floats are very similar to integers, so I won’t go into too many examples.

Lists

Lists are simple yet very versatile in Python. A list is an ordered collection of things. You can have any types of values in a list, and a list can contain items of different types.

You can instantiate an empty list like my_list = [] or you can instantiate a new list with items already in it grocery_list = ["apples", "mangoes", "carrots"].

Special Notes

Lists in Python are ordered, and so you can refer to items in the list by their positions in the list. We call these the indices of items, or the index of any specific item. For example, if I have the grocery list like in the example above, I could access “apples” by the term grocery_list[0]. This uses the square brackets to indicate that you want to get an item(s) from the list and will provide an index to do so.

Lists in Python are Zero indexed. This means that list indices start at 0, and so if you try to use the first index like grocery_list[1], you will actually get the second item.

A common error when working with list indices, is that if you try to specify an index but the list is actually shorter than your index, you will get an index out of range error, because the list doesn’t have anything at that position.

Uses

There are many uses of a list, but a common theme is to accumulate results. For example if you want to collect a list of names from a user:

users = [] 
for i in range(3):
user = input("What is the name of the user you want to add? ")
print(f'Adding {user} to the list...')
users.append(user)
print("Our users are: ")
print(users)

Operations

A commonly used list method, is the .append(item) method. You can see an example of this in the previous example. This method will add an item to the list you use to call it.

Similarly there is a method called .insert(position, item) which will allow you to insert an item in any place in the list. Remember that lists are zero indexed, so my_list.insert(0, item) will insert an item to the front of the list.

You can re-assign items in a list my setting the value of a list at an index. For example, to reassign the second item in grocery_list to be “eggs” you can use grocery_list[1] = "eggs".

Another common method of lists is my_list.pop(index) which will remove an item from the list at the specified position. If you do not specify an index, it will remove the item from the end. It will return the item that it pops.

There are plenty more list operations and methods, check out the documentation to see all of the available methods for lists.

Set

A set is similar to a list, except that it has no order, and does not keep duplicates.

You instantiate an empty set like this favourite_colours = set(), or you can instantiate a set with items like this favourite_colours = {"blue", "red", "orange"}.

Uses

Sets are used when you want to keep track of a set of things, and it doesn’t matter what order they are in it just matters if the thing is in the set or not. Is is faster to check if something is in a set than checking if something is in a list.

For example, you might have a number of tasks, and you want to keep track of if they are done or not so you don’t do them twice:

tasks = ['do_homework', 'make_website', 'call_friend', 'make_website', 'walk_dog'] 
completed_tasks = set()
for task in tasks:
if task not in completed_tasks:
print(f"Performing task: {task}")
completed_tasks.add(task)
else:
print(f"Skipping task: {task} because it is already done.")
print(completed_tasks)

We can see how this skips the task that was already completed:

Operations

The primary operations for a set are adding an item, removing an item, and checking if an item is in a set.

You can add items by using the method my_set.add(item) and you can remove items from a set my using the method my_set.pop(item) to remove and return an item from a set.

You can check if something is in a set by using Python’s remarkably close to English syntax: item in my_set which will return True or False depending on if item is in the set. Or like in my example above you can add in a not operator to get item not in my_set which returns the opposite.

Check out more on sets on the official documentation.

Dictionaries

Dictionaries are similar to sets, except instead of being just an unordered set of values, they are composed of an unordered set of key-value pairs. So you have a set of keys where each key maps to a value. Conceptually, this allows us to create mappings. For example you could use a dictionary to map foods to prices.

You can define an empty dictionary simply with a pair of curly braces my_dictionary = {} or you can define it with some key-value pairs like my_dictionary = {"apple": 3, "eggs": 6, "bananas": 2}.

You can also add key-value pairs to a dictionary after it has been created using the operation: my_dictionary['bread'] = 4.

Dictionaries work a lot like sets in the way they are designed, so they are fast at checking if something is in a dictionary, and looking up a value given a key. For example, if I want to quickly check the price of eggs I can print(my_dictionary['eggs']) and this will find 'eggs' in our dictionary and return the value associated with it, 6.

Uses

Dictionaries are very versatile, but there are two common ways to use them. The first is making a mapping, and the second is to store information about something.

Let us consider the mapping problem of nicknames. We know everyone’s names and nicknames in advance, and when someone introduces them self as their name, you actually want to refer to them by their nickname.

names_to_nicknames = {'Jacob': 'Jake', 'Emily':'Em', 'Alexander': 'Alex'} 
user_name = input('What is your name? ')
if user_name in names_to_nicknames:
nickname = names_to_nicknames[user_name]
print(f'Hey {nickname}, good to see you again!')
else:
print('Hey stranger! Nice to meet you. ')

Here we have used a dictionary to solve the mapping problem from names to nicknames.

The second common use of a dictionary is for storing information about things. For example you might want to store records about houses. A reasonable way to store the information for one house is a dictionary, and you can put one of these dictionaries in a list for each house:

houses = [] 
house1 = {'Address':'100 Birch Street', 'City': 'Atlantis', 'Value':300000, 'Year Built': 1905}
house2 = {'Address':'742 Evergreen Terrace', 'City': 'Springfield', 'Value':425000, 'Year Built': 1987}
houses.append(house1)
houses.append(house2)
print(f"The price of house1 is {houses[0]['Value']}")
print(f"The address of house2 is {houses[1]['Address']}")

Here we can see that once we assemble this list of dictionaries, we can get the information from it in a sensible way.

Operations

I mentioned how to create dictionaries above, but the other common operations are adding a key-value pair, removing a key-value pair, and modifying a value for a key.

The way to add a new key-value is actually the same as they way to modify a key-value pair. You can use my_dictionary['new_key'] = 'new_value' and if 'new_key' existed in my_dictionary, then the value will be replaces with new_value. If it did not exist, it will be added.

Removing a key-value pair is done by the my_dictionary.pop('key') and this will return the value for the key that you popped and remove the key-value from the dictionary.

You can read more on dictionaries at the official documentation.

Conclusion

If you made it this far, congrats!! This is a very information-dense article, but if you understood the concepts explained in this article you are well on your way to being able to write your own programs in Python. This series has more content coming soon, so if you found this helpful feel free to subscribe :)

Originally published at https://www.jacobtalkstech.com on November 14, 2022. Check out my website here for more content!

--

--