Introduction to Python

Build-in types

The type of an object determines what we can do with it and use it for.

type(2)
int
type(2.)
float

Note: 2. is shorthand for 2.0

2. == 2.0
True
type("2")
str
2*3
6
"2"*3
'222'

converting from one type to another

type(int("2"))
int
type(float("2"))
float
type(str(2))
str

The type function told us that 2 is an int (short for integer), 2. is a float (short for floating point number), and "2" is a str (short for string). Note that the double quotes around the characters indicate that it is a string. So, "2" is a string, but 2 is an integer. Both single (') and double (") quotes can be used to represent strings (try typing "2"=='2). In some cases we may want to use, for example, a single quote as part of the string itself (e.g. “That’s great!”). Or vice versa - use double quotes in the string (e.g. I "like" boiled fish). To represent these as string in Python we should use double quotes in the first and single quotes in the second case.

"That's great!"
"That's great!"
'I "like" boiled fish'
'I "like" boiled fish'

Interactive calculations

The following are Python’s arithmetic operators

action

operator

addition

+

subtraction

-

multiplication

*

division

/

raise to power

**

modulo

%

floor division

//

2 + 2
4
50 - 5*6
20
(50 - 5*6) / 4
5.0
8 / 5  # division always returns a floating point number
1.6
5 ** 2  # 5 squared
25
25
5%2
1
5//2
2

The results from calculations can be stored in (assigned to) variables. For example:

# The equal sign (=) is used to assign a value to a variable.

width = 20
height = 5 * 9
area = width * height

Python will not print the result. To do so, type the variable name

area
900

After assigning a value, we can change it

x = 3
print(f"The values of x before: {x}")
x = x + 1
print(f"The values of x after: {x}")
The values of x before: 3
The values of x after: 4

The same can be achieved using the += operator

x = 3
print(f"The values of x before: {x}")
x += 1 # Note here
print(f"The values of x after: {x}")
The values of x before: 3
The values of x after: 4

We can similarly use -=, *=, /=, //=, %=, and **=.

x = 3
print(f"The values of x before: {x}")
x -= 1 # Note here
print(f"The values of x after: {x}")
The values of x before: 3
The values of x after: 2
x = 3
print(f"The values of x before: {x}")
x *= 2 # Note here
print(f"The values of x after: {x}")
The values of x before: 3
The values of x after: 6
x = 5
print(f"The values of x before: {x}")
x /= 2 # Note here
print(f"The values of x after: {x}")
The values of x before: 5
The values of x after: 2.5
x = 5
print(f"The values of x before: {x}")
x //= 2 # Note here
print(f"The values of x after: {x}")
The values of x before: 5
The values of x after: 2
x = 5
print(f"The values of x before: {x}")
x %= 2 # Note here
print(f"The values of x after: {x}")
The values of x before: 5
The values of x after: 1
x = 5
print(f"The values of x before: {x}")
x **= 2 # Note here
print(f"The values of x after: {x}")
The values of x before: 5
The values of x after: 25

Operations on strings

"Olá " + "Olá " + "Olá " 
'Olá Olá Olá '

Note the space in "Olá "

"Olá" + " " + "Olá"+ " " + "Olá" 
'Olá Olá Olá'
"Olá" + ", " + "Olá"+ ", " + "Olá" 
'Olá, Olá, Olá'
"Olá, "*20
'Olá, Olá, Olá, Olá, Olá, Olá, Olá, Olá, Olá, Olá, Olá, Olá, Olá, Olá, Olá, Olá, Olá, Olá, Olá, Olá, '

Useful data container objects, part I

Lists

ordered sequence of objects inside square brackets separated by commas

list_of_numbers = [4,1,2,5,6]
list_of_letters = ['a','c','s', 'w', 'ç']
type(list_of_numbers), type(list_of_letters)
(list, list)
  • the length of a list can be found with the build-in len() function

len(list_of_numbers)
5
  • the elements of a list can be referenced by their index

list_of_numbers[0]
4
list_of_letters[1]
'c'
list_of_numbers[-1]
6
list_of_letters[-2]
'w'
  • you can slice a list up between certain characters or up to certain characters

list_of_letters[2:4]
['s', 'w']
list_of_numbers[1:5]
[1, 2, 5, 6]
list_of_numbers[0:4:2]
[4, 2]
list_of_letters[3:]
['w', 'ç']
  • the full slice notation is your_list[start:stop:step]. If we ommit stop the slice goes to the end of the list. The default step is 1, so we can ommit it if that’s what we want.

mixed_list = ['a', 10, 'Ana', 'Bruno', 3, 'Carla', ['w', 'y']]
mixed_list[2]
'Ana'
mixed_list[-1]
['w', 'y']
mixed_list[-1][0] # mixed_list[-1] is a list, [0] is its first element
'w'
mixed_list[::-1] 
[['w', 'y'], 'Carla', 3, 'Bruno', 'Ana', 10, 'a']

Tuples

ordered sequence of objects inside parentheses separated by commas

tuple_of_numbers = (4,1,2,5,6)
type(tuple_of_numbers)
tuple
tuple_of_letters = ('a','c','s', 'w', 'ç')
  • unlike lists, tuples are read-only (immutable)

list_of_letters
['a', 'c', 's', 'w', 'ç']
list_of_letters[-1]='ã'
list_of_letters
['a', 'c', 's', 'w', 'ã']
tuple_of_letters
('a', 'c', 's', 'w', 'ç')
tuple_of_letters[-1]='ã'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [97], in <module>
----> 1 tuple_of_letters[-1]='ã'

TypeError: 'tuple' object does not support item assignment

Conditionals

We use conditional to do a set of instructions depending on whether or something is True:

x, y = 10, 1

if y > x:
    print("y is larger")
elif x > y:
    print("x is larger")
else:
    print("x and y are equal")
x is larger
y = 10

for x in [0, 10, 11]:
    if y > x:
        print("y is larger")
    elif x > y:
        print("x is larger")
    else:
        print("x and y are equal")
y is larger
x and y are equal
x is larger

Iterations

The above cell is an example of an iteration or a loop. Iterations are used to do an operation many times.

for loop

iterate over the elements of a sequence

for letter in list_of_letters:
    print(letter)
a
c
s
w
ã
for num in tuple_of_numbers:
    print((num, num**2))
(4, 16)
(1, 1)
(2, 4)
(5, 25)
(6, 36)
list_of_squares=[] # initialize an empty list

for num in tuple_of_numbers:
    list_of_squares.append(num**2) # append a new element to an existing list
    
print(list_of_squares)
[16, 1, 4, 25, 36]

enumerate() is a built-in Python function returning the index in addition to the element of a list or tuple (more generally, a sequence)

for i, x in enumerate(mixed_list):
    print(i, x)
0 a
1 10
2 Ana
3 Bruno
4 3
5 Carla
6 ['w', 'y']
for i, x in enumerate(tuple_of_numbers):
    print(i, x)
0 4
1 1
2 2
3 5
4 6

while loop

iterate until an expression returns False

i = 0
while i <= 10:
    print(i)
    i+=1
0
1
2
3
4
5
6
7
8
9
10
list_of_numbers
[4, 1, 2, 5, 6]
i = 0
while list_of_numbers[i] < 5:
    print(list_of_numbers[i])
    i += 1
4
1
2

Keywords

The following words are reserved in Python - you cannot use them as variables names

import keyword
keyword.kwlist
['False',
 'None',
 'True',
 'and',
 'as',
 'assert',
 'async',
 'await',
 'break',
 'class',
 'continue',
 'def',
 'del',
 'elif',
 'else',
 'except',
 'finally',
 'for',
 'from',
 'global',
 'if',
 'import',
 'in',
 'is',
 'lambda',
 'nonlocal',
 'not',
 'or',
 'pass',
 'raise',
 'return',
 'try',
 'while',
 'with',
 'yield']
  • some examples of use

(2>3) is True
False
(2>3) is False
True
(2<3) and (1>0) # both are true
True
(2>3) or (1>0) # at least one is true
True