10 <class 'int'>
3.14 <class 'float'>
(1+5j) <class 'complex'>
01. Python basics
Computational methods
Learning objectives
- Understand Python syntax and variable assignment
- Identify and use basic data types
- Apply common built-in functions
- Explore attributes and methods of objects
Basic concepts
Python is an object-oriented programming language. Objects in Python are instances of classes, which encapsulate properties such as attributes (data) and methods (functions). Class attributes and methods in Python are accessed through the dot (.) notation. Such properties can also be inherited from parent to child classes.
- Example: A
Personcan be a class that contains characteristics and behaviors of a person, such asPerson.nameandPerson.age. AMaleperson can be a child class fromPerson, thus inherting the same properties.
Variable assignment
A variable corresponds to an object that resides in memory and can be accesed by a given name. Python offers dynamic typing, meaning that the type of a variable is inferred at runtime based on its value, rather than being explicitly declared during assignment.
Variables in Python are assigned through the following syntax: \[ \textit{name} = \textit{value}\]
As a general convention, name of variables must begin with a letter, not a number. It is also common to use lowercase letters hyphenated with underscores _, but this is not mandatory. You can check the PEP 8 style guide for python code for more details on name convention.
Data types
Python offers several data types to store variables. The value of a variable can be printed in console with the print() function, while the data type of a given object can be accesed with the type() function:
Inline comments are declared with the hash character #, and are useful to provide context for a given line of code.
Multiple variables can be assigned in a single line of code by separating them with a comma , operator:
10 <class 'int'>
3.14 <class 'float'>
(1+5j) <class 'complex'>
Alternatively, multiple variables can be assigned in a single line by separating each assignment with a semicolon ; operator.
10 <class 'int'>
3.14 <class 'float'>
(1+5j) <class 'complex'>
Additional data types are strings (text) and booleans (True/False). Note that text strings must be enclosed with either single ', double ", or triple quotes '''.
Operations on variables
Numerical variables can be operated arithmetically, relationally, and logically. Data types can also be modified by type casting. Lets explore some of these operations.
Arithmetic operations
Numerical variables support the following arithmetical operations:
# variable assignment
a = 9; b= 2
# arithmetic operations
add = a + b # addition
sub = a - b # subtraction
mul = a * b # multiplication
div = a / b # division
flo = a // b # floor division
mod = a % b # modulo
exp = a ** b # power
print('Addition:', add, type(add))
print('Subtraction:', sub, type(sub))
print('Multiplication:', mul, type(mul))
print('Division:', div, type(div))
print('Floor division:', flo, type(flo))
print('Modulo:', mod, type(mod))
print('Power:', exp, type(exp))Addition: 11 <class 'int'>
Subtraction: 7 <class 'int'>
Multiplication: 18 <class 'int'>
Division: 4.5 <class 'float'>
Floor division: 4 <class 'int'>
Modulo: 1 <class 'int'>
Power: 81 <class 'int'>
By default, the resulting data type from a division operation between int objects is a float object.
String variables support addition and scalar multiplication:
Comparison operations
Numerical variables can also be compared by relational operators:
False <class 'bool'>
False <class 'bool'>
True <class 'bool'>
Note that the result of a relation operation is a boolean object bool. Numerical variables are compared based on their value, regardless of data type.
A summary of relational operators is given below:
| Operator | Meaning | Example | Result |
|---|---|---|---|
== |
Equal to | 7 == 3 |
False |
!= |
Not equal to | 7 != 3 |
True |
< |
Less than | 8 < 12 |
True |
> |
Greater than | 8 > 12 |
False |
<= |
Less or equal to | 7 <= 7 |
True |
>= |
Greater or equal to | 8 >= 12 |
False |
String variables can be lexicographically compared by the same relation operators.
Logical operations
Boolean variables can be operated logically:
String methods
String variables are particularly useful to manipulate text, including file and folder names. Python offer several methods to remove leading or trailing characters from a string:
strip(): leading and trailing characters removed.lstrip(): leading characters removed.rstrip(): trailing characters removed.
'Hello WorLD'
'Hello WorLD '
' Hello WorLD'
A formatted string literal (f-string) is a string literal that is prefixed with an ‘f’, and allows content to be modified in replacement fields delimited by curly braces {}. You can read the lexical analysis to learn more about printing f-strings.
The following string methods allow case manipulation:
lower(): all cased characters converted to lowercase.upper(): all lowercase characters converted to uppercase.title(): titlecased version of the string.capitalize(): first character capitalized and remaining characters lowercased.
'hello world once more'
'HELLO WORLD ONCE MORE'
'Hello World Once More'
'Hello world once more'
In addition to case manipulation, Python offers string methods for searching, replacing, and splitting:
find(sub): returns the lowest index in the string where substring sub is found.replace(old, new): all occurrences of substring old replaced by new.count(sub): number of occurrences of substring sub in the string.startswith(prefix):Trueif string starts with prefix, otherwise returnsFalse.endswith(suffix): returnsTrueif string ends with suffix, otherwise returnsFalse.split(sep): return a list of words in the string, using sep as the delimiter.
# variable assignment
text = "This IS a mOre compleX chAin of complex evEnTs"
# find subtext
sub = 'complex'
index = text.find(sub)
print(f'Index of word {sub}: {index}')
# replace text
ntext = text.replace('complex', 'strange').capitalize()
print(ntext)
# count text occurrences
count = text.lower().count(sub)
print(f'Counting occurrence of word {sub}: {count}')Index of word complex: 32
This is a more complex chain of strange events
Counting occurrence of word complex: 2
Type casting
Variables can also be converted to different data types. For instance, string variables that represent numbers can be converted to numerical variables with either the int() or float() function. On the other hand, numerical variables can be converted to string variables with the str() function:
# convert from text to number
num_str = "123"
num_int = int(num_str)
num_float = float(num_str)
# printing and comparing both values
print(num_int, type(num_int))
print(num_float, type(num_float))
print(num_int == num_float)
# convert from number to text
num_text = str(num_int)
print(num_text, type(num_text))
print(num_text == num_str)123 <class 'int'>
123.0 <class 'float'>
True
123 <class 'str'>
True
Collections
Collections are special type of variables in Python designed to store a sequence of other variables. Collections include ordered sequences such as lists, and tuples, unordered sequences such as sets, and mapping collections such as dictionaries. Lets first explore common sequences:
List: [1, 2, 3] 3 <class 'list'>
Tuple: (4, 6) 3 <class 'tuple'>
Set: {8, 9, 10, 7} 4 <class 'set'>
Although sequences such as lists, tuples, and sets can store multiple data types, it is common practice to contain a single data type, i.e., either numeric or string types.
Functions for collections
The number of items inside a collection can be recovered with the len() function. Since collections often contain numerical values, we can use the min(), max() and sum() functions to obtain the smallest, largest, and sum of values, respectively. We can also use the sorted() function to sort values from the smallest to the largest.
# list assignment
vlist = [-4, 3, -2, 2, -1, 5]
vsort = sorted(vlist) # sorted
lenval = len(vlist) # length
minval = min(vlist) # minimum value
maxval = max(vlist) # maximum value
sumval = sum(vlist) # sum of values
meanval = sumval/lenval # mean value
print('List: ', vlist, type(vlist))
print('Sorted list: ', vsort, type(vsort))
print('Length: ', lenval)
print('Minimum value: ', minval)
print('Maximum value: ', maxval)
print('Mean value: ', meanval)List: [-4, 3, -2, 2, -1, 5] <class 'list'>
Sorted list: [-4, -2, -1, 2, 3, 5] <class 'list'>
Length: 6
Minimum value: -4
Maximum value: 5
Mean value: 0.5
Indexing
Indexing allows to retrieve individual items in a collection. The syntax for indexing is the square brackets notation [i], enclosing the index i for the item to retrieve.
Item indexing in collections begin with the index zero 0. Indexing also supports negative values, to retrieve elements starting from the end of the list. Note that string variables can also be indexed to recover a given character.
10 <class 'int'>
50 <class 'int'>
Indexing can also be used to modify a given element in a mutable list:
Slicing
Slicing allows to retrieve a subset from a collection. The syntax for slicing is [start:end:step].
The slicing interval is closed at the lower endpoint start, but open at the upper endpoint end. By default the slicing operation begins at 0 and ends at the last element, with a step of 1. Slicing also supports negative indexing, to retrieve elements counting from the end of the collection.
['a', 'b', 'c']
['d', 'e', 'f']
['a', 'c', 'e']
['f', 'e', 'd', 'c', 'b', 'a']
List methods
Lists can store an ordered collection of variables. The stored variables can be of any type, including other collections. Items inside a list are mutable, meaning that they can be modified after the list is created. List modification is conveniently performed through several available methods:
append(val): appendsvalto the end of the list.remove(val): removes the first occurrence of tvalin the list.insert(i ,val): insertsvalat indexiof the list.index(val): returns the index for the first occurrence ofvalin the list.extend(iter): extends the list with contents ofiter.copy(): creates a copy of the list.clear(): remove all items from the list.
# list assignment
vlist = [0, 1, 2, 3, 4]
print(vlist, len(vlist))
# appending an element in the list
vlist.append(5)
print(vlist, len(vlist))
# removing an element from the list
vlist.remove(5)
print(vlist, len(vlist))
# inserting an element in the first position (index 0) of the list
vlist.insert(0, 4)
print(vlist, len(vlist))
# returns index for a given element in the list
ival = vlist.index(4)
print(ival)[0, 1, 2, 3, 4] 5
[0, 1, 2, 3, 4, 5] 6
[0, 1, 2, 3, 4] 5
[4, 0, 1, 2, 3, 4] 6
0
Dictionary
A dictionary is a special type of collection that stores unordered paired data of values associated with a given key. Dictionaries are assigned with the curly brackets operator {}.
Once assigned, a given value in a dictionary is recovered with the square brackets operator [key], enclosing the key for the corresponding value. All the values and keys of a dictionary can be accessed through the values() and keys() method, respectively.
Keys must be unique and immutable, while stored values can be of any type, including other collections.
{'firstname': 'Willy', 'lastname': 'Wonka', 'age': 35} <class 'dict'>
Willy Wonka
dict_keys(['firstname', 'lastname', 'age'])
dict_values(['Willy', 'Wonka', 35])
Exercises
- Declare the following variables:
- Print the data type of each variable with the
type()function. - Print the length of each variable with the
len()function. - Print the list
valssorted from smallest to largest value with thesorted()function. - Compute and print the mean value for the list
vals. - Use the index operator to create a new variable containing only the last value of
vals. - Insert in the first position of
valsthe number 7. - Print a version of
textwith only uppercase letters. - Find the index for the word “chain” in the variable
text. - Slice the
textvariable to create a new string that only contains “chain of text”. - Split the
textvariable considering blank spaces as separators, and print the third word of the result. - Compute the range of
vals(maximum minus minimum value) and print the result. - Compare whether the range of
valsis greater than the mean valuevals. - Convert the mean value of
valsto string using thestr()function. Print the data type before and after the conversion. - Create a dictionary
datawith two keys:valsandtext, storing the corresponding variables. Print all keys and retrieve the value associated with each key.