Pragmatic Python II

The Building Blocks of Python

Shuvo Saha
intelligentmachines
12 min readAug 31, 2020

--

This is part 2 of the series. To go back to part 1, click here.

It’s finally time to write code. Instead of writing them on your computer, we can let some websites handle the setup for us and get straight to coding. To write code online, I recommend Repl.it or Codechef. For this part of the tutorial, we’ll use Repl.it.

Open up Repl.it and create a Python IDE (that’s Integrated Development Environment, go ahead and impress your CS friends).

Note: I urge you to copy every piece of code I write. Don’t copy and paste it — get in the habit of typing it out. I cannot stress how important this is.

Click on “Start Coding” and then create a new Python repl

Why Python?

Why not Cobra? What about Viper? Why snakes? It’s because Python’s creator liked Monty Python sketches and was reading about them when developing the language. I can’t believe you thought I’d explain why we’re using Python in part 2 of a Python tutorial.

How Python?

Python and most other programming languages are read top to bottom; just like the English language.

You’ll notice that I’ve said script over 50 times in Part 1. What is a Python script anyway? Python scripts are files ending in .py and usually contain a full set of instructions and run sequentially from top to bottom to perform a task. Repl.it and other IDEs run these Python scripts and give you the output.

You thought these joke explanations would go away, didn’t you? Javascript is completely unrelated to Java. It’s like a guy thinking you know Swahili because you know Bengali.

Parallels

Most programming languages are similar, with certain quirks. Once you’re confident in Python, you’ll see that transitioning to another language will be much easier. You’ll notice that syntax (set of rules that govern whether the statements you type are considered correct) is the only thing that changes from one programming language to another. To illustrate, in Python, a variable (a store of value) would be defined as such:

a = 5

Here, Python creates a new variable called “a” and then assigns the value “5” to it. In JavaScript, the same operation would be done like so:

var a = 5;

In C, the same operation would be:

int a = 3;

I think we all understand why I prefer Python 😅. Note that there are certain differences in the way some languages handle certain things, for example, Assembly is extremely different from the mainstream languages. Nevertheless, the concepts in the next section apply to most languages.

Building Blocks

The fundamental concepts of Python consist of, but are not limited to, the following 4 categories:

Stores of value

To perform operations, we need some way to store values and select values. Value can be stored in Python in many ways.

To store values, we usually use variables. In Repl.it, type in the following:

a = 5510
b = "tennis"

This creates two variables: a and b and assigns a value of 5510 to a and a value of “tennis” to b. Assignments are done using the = symbol. This looks a bit strange because we’re usually taught to say this means equal to and how can a be equal to 5510?

We’re telling Python that from now on if I mention a it’ll be equal to 5510 and if I mention b, it’ll be equal to “tennis”.

Let’s ask Python to show us the values of a and b. To show values, we use the print statement. Note that this statement only prints out the value to the terminal (this is where the coder sees the output) and does nothing else. Even without a print statement, a and b will contain these values and we can do whatever we want to them.

a = 5510
b = "tennis"
print(a)
print(b)

The empty line isn’t necessary since Python avoids empty lines, but it makes our code look cleaner so you can put in as many as you please. If you click “Run” on your Repl.it window, you’ll see it’ll print out the following:

That’s strange. 5510 is alright but where are the quotes around tennis? In Python, text is just a datatype, known as a string (str). Strings require quotes to be valid. You could even turn numbers to the String datatype but they’d lose the ability to behave like numbers. This means that you can’t add them, multiply them, and so on.

For numbers, we have two useful datatypes: int or Integer and float. The only difference is that Integers are whole numbers and Floats have a decimal point in them i.e. 5 is an int while 5.9, 5.522, and 5.0 are all floats. The full list of default datatypes is given below but note that some of these are for niche uses.

Source: W3Schools.com

The next useful datatype would be sequences and maps. These are very similar in that they store collections of values. One of the most useful sequences would be a list. An example of a list that contains strings would be:

groceries = ["mangoes", "oranges", "milk", "eggs"]

To make lists, we:

  • Declare a name for the list.
  • Use the =symbol to assign a value (just like before).
  • Add [] to define the members of the list. Square brackets are necessary.
  • Use ,inside the[]to separate the list members.

Lists can contain any combinations of datatypes: strs, ints, floats, even other lists. We can also add values to lists after making them but we’ll leave that for later in the tutorial.

Another useful datatype is a tuple. A tuple is similar to a list but unlike it, we can’t change values after we’ve made the tuple. In other words, lists are mutable and tuples are immutable. Tuples are made just like lists but with different brackets:

groceries_essential =("eggs", "milk", "water 1 Litre")

What if we want our grocery list to also contain the price of each item? Dictionaries are so-called because they allow us to make key : value pairs similar to how a dictionary allows us to look at definitions (value) for words (keys). Let’s make a dictionary with one price value.

groceries_with_prices = {"eggs":0.5, "milk":0.75, "water":0.1}

How do we even look at the prices then? Maybe we should use the print statement like before.

groceries_with_prices = {"eggs":0.5, "milk":0.75, "water":0.1}
print(groceries_with_prices)
The Output

You’ll notice that running this just prints out the whole dictionary. If you were to print lists or tuples, the same would happen.

To access tuples or lists, we need to use square brackets again.

groceries = ["mangoes", "oranges", "milk", "eggs"]
groceries_essential =("eggs", "milk" "water 1 litre")
print(groceries[0])
print(groceries_essential[0])

This outputs mangoes and eggs but why? The 0 in square brackets references the first member of the list or tuple. Consequently, a 1 would refer to the second member and so on. In Python, indexes start from 0.

We can also make slices instead of just 1 value. The following code outputs everything from index 0 up to index 2 exclusive. So we only get the first (index 0) and second items (index 1). The output should be [‘mangoes’, ‘oranges’].

groceries = ["mangoes", "oranges", "milk", "eggs"]
print(groceries[0:2])

We can access individual values with dictionaries but this time we need the key. Dictionaries drop the numbered indices and use keys instead.

groceries_with_prices = {"eggs":0.5, "milk":0.75, "water":0.1}
print(groceries_with_prices["eggs"])

This is similar to before but this time we used “eggs” as an indexer (here it’s a key). This is because we specifically set "eggs", "milk" and "water" as keys. Referencing them gives us their value.

Square brackets were used to refer to lists (list_names = [“martha”, “batman”, “superman”]), so why is this also used to take members out of lists and dictionaries?

If a square bracket with a number or string inside is attached to the end of a variable, it picks out a value with the same index from that variable. So, if list = ["shuvo", "saha", "hi"], then list[1] would be "saha".

The final datatype I’ll talk about is a boolean or bool. Booleans represent one of two values: True and False.

my_bool = Truemy_other_bool = False

This is useful for logical statements; to compare stuff and whatnot. We’ll dive into bools later on in the tutorial.

That was a lot of words. Now it’s time for memes.

If you don’t get this, you’re expelled from this course. Hint: it’s got something to do with strings.

Operators

Operators perform operations on variables and values. The = used for assignment is an operator. Some useful operators include arithmetic operators:

a = 5+2
b = 5-2
c = 5*5
d = 5/5
e = 5**2
print(a, b, c, d, e)

Running this should make it clear that asterisks are used for multiplication, forward slashes are used for division and double asterisks are used for exponentials. You’ll also notice I can print all of these at once using a comma between the variables.

Other useful operators include comparison and logical operators. Comparisons will usually output a boolean. Let’s look at some of these in action.

a = 5
b = 8
c = 9
print(b > 5)
print(a == 5)
print(b < 10)
print(b < 8)
print(b <= 8)
print((b+c) > 12)

Make sure to run the above code and guess what they do before reading onwards.

The operators are quite intuitive except for the == operator. It’s a bit strange that double equal to is used to compare two values to see if they’re equal. Remember that = is used to assign a value to a variable and == is, therefore, used to ask if the value on the left is equal to the value on the right. I’ve made so many errors in my life thanks to missing an = .

Source: W3Schools.com

There are 3 logical operators:

Source: W3Schools.com

Try to figure out what these statements will output before running the code:

a = 5
b = 8
print(a==5 and b==8)
print(a<8 or b>9)
print(a<3 or b>9)
print(a==5 and not b==8)
print((a==5 and not b==8) or a < 8)

The first statement checks if a is equal to 5 and if b is equal to 8 and then outputs True if both conditions are met.

The second statement will print True if any of the conditions are met. Since a is less than 8, we get True. Similarly, we see a False in the third statement.

The fourth statement is similar to the first one but also has a not. The not will reverse the condition of whatever is next to it. Since b==8 outputs True, adding a not will make it False. In other words, the statement now reads “Is a equal to 5 and is b not equal to 8?” Since b is equal to 8, we get a False on the right. Remember that and will only return True if both conditions are met.

The final statement just shows that you can combine conditions using brackets and conditions in brackets will be evaluated first. To understand the output, it’s helpful to break it down.

Python likes to be fancy and emulate English with the inclusion of the is and in operators.

a = 5
print(a is 5)
print(a is not 5)
names = ["Martha", "Lewis", "Dave"]
print("Lewis" in names)
print("Derek" in names)

The is operator is similar to == and the in operator checks if the variable is inside a sequence and returns True if it is.

Why am I being attacked? I thought we were attacking CS students.

Conditionals

Now that we’ve talked about operators, we can extend their use with conditional statements.

Also known as if/else statements, these are used to execute code only if a certain condition is met (or not met or some hodgepodge of multiple combinations, e.g. between the ages of 5 and 100 but not 6).

You should be able to guess what this does:

a = 5
b = 6
if a > b:
print("a is greater than b")
elif a == b:
print("a is equal to b")
else:
print("b is greater than a")

The statement has 3 layers: the first one checks if a is greater than b, if this condition is met, we get the first output “a is greater than b” and the statement doesn’t continue further.

If the condition is not met, Python goes to the next layer (elif stands for else if ) and checks if a is equal to b and outputs “a is equal to b” if this is true.

If this condition is also not met, the program just prints “b is greater than a”. Note that we can add as many elif layers as we want to check as many statements as we want. Python treats the whole thing as one big block of code and will skip every subsequent layer when a condition is met. So what if we want to check two things independently?

a = 5if a > 2:
print("a is greater than 2")
if a < 10:
print("a is less than 10")

This will test both conditions independently and won’t stop even if one condition is met. The if is used to tell Python that we’re starting a condition check block.

Note that else statements don’t check anything and are used when no other condition is met. Also, note that the indentation (4 spaces or 1 tab after an if/elif/else statement) is mandatory in Python and is automatic in any IDE if you just press enter after the colon. Anything that is indented directly below the conditional counts as being inside the conditional.

Loops

Loops are used to continuously carry out a certain instruction on something until a condition is fulfilled (“while” loops are an example of this) or until everything has been looped over (“for” loops in Python are used like this).

Say we want to find out the birth year of every student in a school and we have their exact ages. We can loop over every age and deduct it from the current year to find the birth year. A for loop would be useful here.

An example of a for loop for this operation is given here, where we iterate over the student age list:

age_list = [15, 17, 17, 18, 12, 14, 13, 10, 15]for age in age_list:
print(2020 - age)

This is simpler than it looks. age is just the name we give to the items on the list. You can use any name you want and the code will work. Next, we access the items in the list using that name we used earlier (age).

age_list = [15, 17, 17, 18, 12, 14, 13, 10, 15]
for random_name in age_list:
print(random_name)

This prints out every item individually. The indentation rules are similar to the conditional.

For loops can be used like this as well:

for i in range(5):
print("Hello")

range(n) creates the equivalent of a list of values starting from 0 to n-1. for i in range(n) iterates over that list and ends up doing it n times. So here, it’ll output “hello” 5 times. Remember you can name the i as you wish and even use it inside the statement. Try printing the value of i every loop.

While loops will keep doing something as long as a certain condition is true.

num = 0
while num < 5:
print("i is less than 5")
num = num+1

Here, we declare a variable num , assign a value to it, and then output a sentence as long as the variable is true. Note that we also increment the value of num every loop by adding 1 to the existing value. The diagram below should make it clearer.

If you’re clever, you might have guessed that we can use this while statement to do what we did in our for i in range(5) example and vice versa.

We can also use break to stop a loop prematurely and continue to force it to skip over some code and go back to the beginning of the loop.

for i in range(5):
print(i)
if i == 2:
break
print("Hello")

You’ll notice that “hello” is only displayed twice because the loop stops when the value of i hits 2. I added the first print(i) statement to show you what’s going on inside.

for i in range(5):
print("Hello")
if i != 4:
continue
print("Hi")

“Hi” is only output once because the continue statement forces Python to skip over the code below it until i has a value of 4.

The Dunning-Kruger Effect is a cognitive bias that says that we feel like gods when we start learning something new. Unfortunately, we’re about to hit a brick wall and then think we’re useless. Fret not! We’ll slowly start learning and become an expert. See? This tutorial isn’t all memes.

Whew, that was a lot of stuff. Make sure to go through this page multiple times until you have it all in the back of your head. You probably won’t but I’m an optimistic man.

In the next part of the series, we look at the final building blocks, some nifty Python tricks and tips, and, of course, some tests.

--

--

Shuvo Saha
intelligentmachines

A business grad who spends way too much time on his computer. Currently a Marketing Analyst at Wise!