Thomas M. Kehrenberg

A high-level introduction to programming — Part 2

Equality

Let’s look at the following function from the standard library: eq. You can import it with from operator import eq. This function takes two variables and tells you whether the values are the same (or in other words, if they are equal, which is where the name of the function comes from). The function returns a bool which, as you remember, can only be one of two values: True or False.

Let’s see this in action:

from operator import eq

result: bool = eq(3, 4)
print(result)

Here we are checking whether 3 and 4 are equal. They are of course not equal, so result will have the value false.

We can also use variables:

from operator import eq

number_of_children = 3
number_of_seats = 4
result: bool = eq(number_of_children, number_of_seats)
print(result)

This will give exactly the same result. But if the change the value of number_of_children from 3 to 4, then the result will be true:

from operator import eq

number_of_children = 4
number_of_seats = 4
result: bool = eq(number_of_children, number_of_seats)
print(result)

The two variables have the same value.

If you compare a variable with itself, then the result is of course always true:

from operator import eq

number = 10
always_true: bool = eq(number, number)
print(always_true)

We can also compare variables with other types. For example strings:

from operator import eq

name1 = "Joe"
name2 = "Joe"
are_strings_the_same = eq(name1, name2)
print(are_strings_the_same)

This should give True.

You can also compare things that don’t have the same type:

string = "Joe"
number = 3
silly_comparison = eq(string, number)
print(silly_comparison)

But this is not very useful as the result is always False.

The eq function is especially useful when used in combination with if-statements, which are our next topic.

if-statements

Let’s say you want to execute different code depending on the value of a bool variable. This can be done with if-statements. They look like this:

my_bool = True
if my_bool:
print("the value of the variable 'condition' is true!")

Let’s look at this in detail. First, I define a variable called “my_bool”. Then I use the keyword “if” to test whether the value of my_bool is True. If yes, then the following code which starts with 4 spaces is executed.

Now, the example I gave is not very useful, but take a look at this code:

from operator import add, eq

some_value = add(3, 5)

if eq(some_value, 7) {
print("3 + 5 is 7")
}
if eq(some_value, 8) {
print("3 + 5 is 8")
}

Here we used the eq function to get a bool value. Then we check if the result is True and if yes, we execute some code. If the computer has calculated correctly (and it does always calculate correctly; that’s what computers do!), then the output of the program is “3 + 5 is 8”.

Operators

At this point I should explain why we always have to import the functions add and eq from operator. The reason is that you’re meant to write the code differently from what I have been doing so far. This:

from operator import add
result = add(num1, num2)

should actually be written like this:

result = num1 + num2

These two lines of code have the exact same effect, but the second line just looks more natural. However, the second line makes it harder to see that we are calling a function. That’s why I preferred to use the style in the first line for the introduction. I will from now on use the second style and I advise you to do the same, but please always keep in mind that when you use a + sign like that, what you are actually doing is calling a function that adds two numbers.

Symbols like + that can be put in between two variables are called operators. (That’s why we had to import the function add from the library “operator”.) Operators are used just like mathematical symbols.

Similarly, instead of the “equal function” eq, you are supposed to use the == operator:

some_value = 3 + 5

if some_value == 8:
print("3 + 5 is 8")

But be careful not to confuse = and ==! = is used to define the value of a variable; == is used to compare values.

The other math operations can also be written like this: subtraction 5 - 3, multiplication: 7 * 23 and division: 90 / 5.

In addition, there are several other functions for comparing numbers. All of these functions return a bool value; so either True or False.

Less than: 3 < 5

Less than or equal: 5 <= 5

Greater than: 6 > 5

Greater than or equal: 6 >= 6

These can also be written explicitly as functions: lt(3, 5) (this is equivalent to 3 < 5), but no-one ever does.

if-statements continued

Back to if-statements.

Here is another example:

income = 2500.0
tax_percent = 15.0
tax = income * (tax_percent / 100)

if tax > 300:
print("You are paying more than 300 in taxes.")

You should now be able to understand what is going on there.

The equal function also has an opposite: the unequal function. It is written like this: !=. (The ! is supposed to look a bit like a line through the =.) You can use it like this: 3 != 5. As you might have guessed, it returns True if the two arguments are not equal.

Example code:

my_name = "Joe"

if my_name != "Ben":
print("Your name is not Ben.")

It happens very often that you want to check for a condition and also for the opposite of the condition:

my_name = "Joe"

if my_name == "Ben":
print("Hi Ben!")
if my_name != "Ben":
print("Your name is not Ben.")

In this case you can use an else block. (“else” is another keyword.) The following has exactly the same effect as the previous code:

my_name = "Joe"

if my_name == "Ben":
print("Hi Ben!")
else:
print("Your name is not Ben.")

The code in the else-block is executed if my_name == "Ben" is False. (When I say “else-block” I mean the code that comes after the else and begins with 4 spaces. In this case print("Your name is not Ben."), but it can be multiple lines.) else can only be located immediately after an if-statement. It doesn’t make sense to use else without if. It can never happen that both the code in the if-block and code in the else-block are executed. Only one of the two blocks will be executed.

Operator overloading

I previously said that it doesn’t make sense to use + on strings. That’s true in the mathematical sense, but actually you can use the + operator with two strings:

added_strings = "Hi " + "Ben!"
print(added_strings)

The output of this is “Hi Ben!”. So, if you give the + operator two strings, then it will concatenate them.

This is an example of a common technique, which is called operator overloading. Operator overloading means that depending on the type of the variable, the behavior changes. For integers, + does addition, but for strings, + does concatenation.

Some programming languages do not allow operator overloading, because it can be a bit confusing, but a lot of them do, because it can also be very convenient. (Some languages even have function overloading where two functions can have the same name but they differ in terms of the types they accept. But Python doesn’t have this.)

Now, what actually happens when you execute code like 3 + 5 is that the function int.__add__() is called. This is the function that ultimately adds the two numbers. You can call it directly:

int.__add__(3, 5)

but you never should because you can just use +. This function can only add two integers. It doesn’t even work with floats:

int.__add__(3.0, 5.0)

This gives an error. For floats, you need the function float.__add__().

So, you see: when you use the operator +, what Python does is look for the right function that does what we want and then executes it. And this depends on the type of the data.

Now back to string concatenation. As we’ve just learned, the + operator can be used to concatenate strings. One more example:

name = "Joe"
greeting = "Hello"
print(greeting + ", " + name + "!")

The output of this is “Hello, Joe!”.

Sometimes you would like to do this:

number_of_children = 3
print("There are " + number_of_children + " children.")

But this does not work. This is because we are trying to use the + operator with a str and an int. But there is no behavior defined where + is between a str and an int. What you have to do instead is converting the int to a str first. This is fortunately very easy:

num = 3
num_as_string = str(num)

So, the correct code for the previous example would be:

number_of_children = 3
print("There are " + str(number_of_children) + " children.")

This works and gives the output “There are 3 children.”

We can use this in order to make one of the earlier examples somewhat more useful:

income = 2500.0
tax_percent = 15.0
tax = income * (tax_percent / 100)

print("You are paying " + str(tax) + " in taxes.")
if tax > 300:
print("Attention! You are paying more than 300!")
else:
print("Luckily, you are paying no more than 300.")

Recap

Let’s recap what we have learned.

Instead of the functions add, eq and so on, we should be using operators like +, -, / and * that can be used just like math symbols between the numbers: 3 + 5.

You can execute code conditionally on a bool variable with if-else. if and else are keywords.

There are a lot of functions for comparisons in the standard library: ==, !=, <, <=, >, >=.

Strings can be concatenated with +. The behavior of + changes depending on the type of the arguments.

Numbers can be converted to strings by using str like a function: str(455).