print(2 + 3)5
In this chapter we will learn how to use Python as a calculator and see some basic programming concepts.
We start with the most basic mathematical (arithmetic) operations: Addition, subtraction, multiplication and division are given by the standard +, -, * and / operators that you would use in other programs like Excel. For example, addition:
print(2 + 3)5
Subtraction:
print(5 - 3)2
Multiplication:
print(2 * 3)6
Division:
print(3 / 2)1.5
It is also possible to do multiple operations at the same time using parentheses. For example, suppose we wanted to calculate: \frac{2+4}{4 \cdot 2} = \frac{6}{8} = 0.75 We can calculate this in Python as follows:
print((2 + 4) / (4 * 2))0.75
With the ** operator (two stars) we can raise a number to the power of another number. For example, 2^3=2\times 2\times 2 = 8 can be computed as
print(2 ** 3)8
Do not use ^ for exponentiation. This actually does a very different thing in Python.
Compute the following expressions using the operator +, -, *, / and **:
In Python we can assign single numbers, as well as text, to variables and then work with and manipulate those variables.
Assigning a single number to a variable is very straightforward. We put the name we want to give to the variable on the left, then use the = symbol as the assignment operator, and put the number to the right of the =. The = operator binds a number (on the right-hand size of =) to a name (on the left-hand side of =).
To see this at work, let’s set x=2 and y=3 and calculate x+y:
x = 2
y = 3
print(x + y)5
When we assign x=2, in our code, the number is not fixed forever. We can assign a new number to x. For example, we can assign the number 6 to x instead. The sum of x (which is 6) and y ( which is 3), is now 9:
# Original variable assignment
x = 2
y = 3
print(x + y)
# Overwriting assignment of variable x
x = 6
print(x + y)5
9
Finally, you cannot set x=2 with the command 2 = x. That will result in an error. The name must be on the left of = and the number must be on the right of =.
Define variables a,b,c with numbers 19, 3 and 7, respectively. Compute the following expressions:
We can also store multiple variables in one object, a so-called list. A list with numbers is created by writing down a sequence of numbers, separated by commas, in between two brackets [ and ].
z = [3, 9, 1, 7]
print(z)[3, 9, 1, 7]
We can also create lists with fractional numbers.
z = [3.1, 9, 1.9, 7]
print(z)[3.1, 9, 1.9, 7]
To access the numbers in the list, we can index the list at the position of interest. If we want to get the number at position i in the list, we use the syntax z[i].
print(z[1])9
Something strange is happening here… The left-most number in the list is 3.1, but z[1] returns 9. This happens because Python actually starts counting at index 0 (instead of 1).
The left-most number in a Python list is located at position 0. The number next to that at position 1, etc. That is, the i-th number in a list with n numbers can be found at position i - 1 for i = 1,\dots,n
In other words, the “first” number in the list is located at position 0, and we can access it using z[0] instead.
Below we index the number of the list at positions i \in \{0,1,2,3\} separately.
print(z[0])3.1
print(z[1])9
print(z[2])1.9
print(z[3])7
Consider the list a = [11, 41, 12, 35, 6, 33, 7].
It is also possible to print text in Python with the print() command. To do this, you have to put the desired text in quotation marks, either single '' or double "". It does not matter if you use single or double quotation as long as you use the same type on both end of the text.
print('Hello world!')Hello world!
print("Hello world!")Hello world!
A piece of text within quotation marks is called a string in Python. It is also possible to store text (strings) in a list, and print it from the list. For example, we can store the days of the weeks as text in the list days as follows.
days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]If we now want to print a day, we should index the list at the corresponding position. For example, to print "Wednesday", we should index the list at position 2.
print(days[2])Wednesday
If you want to print both text(s) and variables within the same print() command, you can do this by separating these quantities with a comma.
print("The third day of the week is", days[2])The third day of the week is Wednesday
Create a list called courses that contains five course names as text/strings. Then:
For-loops are a convenient way to avoid unnecessary repetition of different lines of code. Suppose we want to print all the days of the week from the days list.
We can do this by using a print statement for every day separately by indexing days at all its positions.
days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
print("The days of the week are:")
print(days[0])
print(days[1])
print(days[2])
print(days[3])
print(days[4])
print(days[5])
print(days[6])The days of the week are:
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
However, looking at the above, the only thing that changes in the last seven lines of code is the position at which we access days. We can also print all the days of the week based on the list days above using a for-loop.
days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
for i in range(0,7):
print(days[i])Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
With the line for i in range(0,7): we tell Python that we would like to carry out a piece of code (the line below it) with different values of the iteration variable i ranging from 0 to 7, but NOT including 7. In other words, we want to run a piece of code for the values of i being 0,1,2,3,4,5 and 6. It is important to realize here that the index 7 is not included as value for i in the for-loop (this is what the Python developers decided on).
In Python such a range, called the iterable, can be specified with the range(a,b) function where a is the smallest value and b-1 the largest value of i. In the first iteration with i = 0 Python will now print days[0], in the second iteration with i = 1 Python will print days[1], etcetera.
The code we want to execute repeatedly can be found under the lines for i in range(0,7): with an indentation (or tab). The indendation is important so that Python known this is the line of code you want to be carried out repeatedly. We can also carry out multiple lines of code in a for-loop, then all these lines should be indented.
days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
for i in range(0,7):
print("Day", i+1, "of the week is:")
print(days[i])Day 1 of the week is:
Monday
Day 2 of the week is:
Tuesday
Day 3 of the week is:
Wednesday
Day 4 of the week is:
Thursday
Day 5 of the week is:
Friday
Day 6 of the week is:
Saturday
Day 7 of the week is:
Sunday
Note that in the first line in the for-loop, here we print three aspects in one print() statement: The word Day, the value of i+1, and the words of the week is:. As i ranges from 0 to 6, the values of i+1 ranges from 1 to 7.
We note that we only use two print statements for the sake of illustration. The above could have been printed with one print() statement as well.
days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
for i in range(0,7):
print("Day", i+1, "of the week is:", days[i])Day 1 of the week is: Monday
Day 2 of the week is: Tuesday
Day 3 of the week is: Wednesday
Day 4 of the week is: Thursday
Day 5 of the week is: Friday
Day 6 of the week is: Saturday
Day 7 of the week is: Sunday
Take your list courses from the previous exercise and consider the list days from above. Print the five sentences: On Monday the course [course0] is being taught., On Tuesday the course [course1] is being taught.; etc. by using a for-loop in which you index the courses and days from the two lists, and where [course0], [course1], etc. are the first, second, etc. course names from the list.
We remark that it is also possible to directly iterate over the values in a list (the iterable).
days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
for i in days:
print(i)Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
In this case, i does not range from 0 to 6, but in iterates directly over the strings in the list days. So in the first iteration i = “Monday”, in the second iteration i = “Tuesday”, etcetera.
It is also possible in Python have different lines of code executed based on conditions. For this we use an if/else statement. This allows the program to execute certain lines of code only when a condition is true.
For example, suppose we store a number in the variable x and want to print a message only if x is greater than 5.
x = 8
if x > 5:
print("x is greater than 5")x is greater than 5
The line if x > 5: checks whether the condition x > 5 is true. If it is true, Python executes the indented line below it. If the condition is false, nothing happens and Python continues with the rest of the code. You can check this yourself by changing the value of x to something strictly smaller than 5. If you run the code snippet, nothing should be printed.
We can also tell Python what to do if the condition is false by adding an else statement.
x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")x is not greater than 5
Here Python checks the condition. Since 3 > 5 is false, i.e., the condition x > 5 is not true, the code under else: is executed instead.
Just like with for-loops, indentation is important. All lines that belong to the if or else block must be indented so Python knows which code belongs to which condition.
We can also check more than two conditions using elif (short for “else if”):
x = 5
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is exactly 5")
print("You can execute multiple lines of code when a condition is true")
else:
print("x is less than 5")x is exactly 5
You can execute multiple lines of code when a condition is true
In this case Python checks the conditions from top to bottom and executes only the first one that is true. In the snippet above the line "x is exactly 5" will be printed. You can play around with this code snippet by changing the values of x and observing that, depending on its value, a different line will be printed.
You can use the following symbols to compare a variable with a given number.
| Operator | Meaning | Example (x = 5) |
Result |
|---|---|---|---|
< |
Less than | x < 7 |
True |
> |
Greater than | x > 7 |
False |
<= |
Less than or equal to | x <= 5 |
True |
>= |
Greater than or equal to | x >= 6 |
False |
== |
Equal to | x == 5 |
True |
!= |
Not equal to | x != 5 |
False |
You can also combine multiple statements into one condition using the and and or keyword arguments. In the code below, we do not finish with an else statement; this is not mandatory.
x = 5
if x > 5 and x < 10:
print("x is between 5 and 10")
elif x == 5 or x == -5:
print("The absolute value of x is 5")The absolute value of x is 5
You can also combine for-loops and if/else statements. For example, recall the original if/else statement where we checked whether x was greater or equal than 5.
x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")x is not greater than 5
We can also check this for a collection of numbers stored in a list numbers by iterating with a for-loop over these numbers and check the conditions for every element in the list.
numbers = [3, 7, -3, 4, 10]
for x in numbers:
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")x is not greater than 5
x is greater than 5
x is not greater than 5
x is not greater than 5
x is greater than 5
Note that in the above code we use indentation twice! For every iteration of the for-loop we want to check the if/else statement, so all those lines need to be indented. Because it also needs to be clear, for every iteration, which lines correspond to the if-statement, and which to the else-statement, the print() statements are indented once more.
Consider the list of temparatures (in degrees Celsius) [20, 14, 12, 18, 25, 30, 31] corresponding to the days of the week Monday through Sunday. For every day you have to print the message: [day] is a [cold/normal/hot] summer day., where a day is cold if the temperature is below 15, normal if it is in the interval [15,25] (i.e., greater or equal than 15 and smaller or equal than 25), and hot if it is higher than 25.
The output of your code should be:
Monday is a normal summer day.
Tuesday is a cold day.
Wednesday is a cold day.
Thursday is a normal summer day.
Friday is a normal summer day.
Saturday is a hot summer day.
Sunday is a hot summer day.