01. Python basics

Computational methods

Author

Marco A. Alsina

Published

May 17, 2026

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 Person can be a class that contains characteristics and behaviors of a person, such as Person.name and Person.age. A Male person can be a child class from Person, 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}\]

Note

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:

# assignment of numerical variables
a = 10     # integer 
b = 3.14   # float
c = 1 + 5j # complex

print(a, type(a))
print(b, type(b))
print(c, type(c))
10 <class 'int'>
3.14 <class 'float'>
(1+5j) <class 'complex'>
Note

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:

# multiple variable assingment
a, b, c = 10, 3.14, 1 + 5j

print(a, type(a))
print(b, type(b))
print(c, type(c))
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.

a = 10; b = 3.14; c = 1 + 5j

print(a, type(a))
print(b, type(b))
print(c, type(c))
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 '''.

# assignment of string and boolean variables
text = 'Hi Python' # string
var  = True        # boolean

print(text, type(text))
print(var , type(var))
Hi Python <class 'str'>
True <class 'bool'>

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'>
Note

By default, the resulting data type from a division operation between int objects is a float object.

String variables support addition and scalar multiplication:

# variable assignment
s1 = 'Hi, '
s2 = 'welcome to Python.'
i  = 3

# addition of strings
print(s1 + s2)

# scalar multiplication
print(i*s2)
Hi, welcome to Python.
welcome to Python.welcome to Python.welcome to Python.

Comparison operations

Numerical variables can also be compared by relational operators:

# variable assignment
a = 9; b = 2.0

# relational operations
lot = (a < b)  # less than
equ = (a == b) # equal to
grt = (a > b)  # greater than

print(lot, type(lot))
print(equ, type(equ))
print(grt, type(grt))
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
Important

String variables can be lexicographically compared by the same relation operators.

Logical operations

Boolean variables can be operated logically:

# variable assignment
x = False; y = True

# logical operations
cand = (x and y)
cor  = (x or y)
cnot = (not x)

print(cand, type(cand))
print(cor, type(cor))
print(cnot, type(cnot))
False <class 'bool'>
True <class 'bool'>
True <class 'bool'>

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.
# variable assignment
text = "   Hello WorLD   "

# removal of characters
print(f" '{text.strip()}'  ") # leading/trailing characters
print(f" '{text.lstrip()}' ") # leading characters
print(f" '{text.rstrip()}' ") # trailing characters
 'Hello WorLD'  
 'Hello WorLD   ' 
 '   Hello WorLD' 
Note

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.
# variable assignment
text = "hello WorLD oncE MoRe"

# case manipulation 
print(f" '{text.lower()}' ")       # lowercase characters
print(f" '{text.upper()}' ")       # uppercase characters
print(f" '{text.title()}' ")       # titlecased characters
print(f" '{text.capitalize()}' ")  # capitalized text
 '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): True if string starts with prefix, otherwise returns False.
  • endswith(suffix): returns True if string ends with suffix, otherwise returns False.
  • 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:

# collection assignment
vlist  = [1, 2, 3]        # list (mutable)
vtuple = (4, 6)           # tuple (immutable)
vset   = {7, 8, 8, 9, 10} # set (no duplicates)

print('List: ' , vlist , len(vlist), type(vlist))
print('Tuple: ', vtuple, len(vlist), type(vtuple))
print('Set: '  , vset  , len(vset) , type(vset))
List:  [1, 2, 3] 3 <class 'list'>
Tuple:  (4, 6) 3 <class 'tuple'>
Set:  {8, 9, 10, 7} 4 <class 'set'>
Note

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.

Important

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.

# list assignment
vlist = [10, 20, 30, 40, 50]

# extracting the first element
first = vlist[0]
print(first, type(first))

# extracting the last element
last = vlist[-1]
print(last, type(last))
10 <class 'int'>
50 <class 'int'>

Indexing can also be used to modify a given element in a mutable list:

# modifying the 5th element in the list
vlist[4] = '5' # string 
print(vlist, type(vlist[4]))
[10, 20, 30, 40, '5'] <class 'str'>

Slicing

Slicing allows to retrieve a subset from a collection. The syntax for slicing is [start:end:step].

Important

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.

# list assignment
letters = ['a', 'b', 'c', 'd', 'e', 'f']

# extract the first 3 letters
print(letters[:3])

# extract the last 3 letters
print(letters[-3:])

# extract letters each 2 steps
print(letters[::2])

# invert the list
print(letters[::-1])
['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): appends val to the end of the list.
  • remove(val): removes the first occurrence of tval in the list.
  • insert(i ,val): inserts val at index i of the list.
  • index(val): returns the index for the first occurrence of val in the list.
  • extend(iter): extends the list with contents of iter.
  • 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
# lists assignment
list1 = [1, 2, 3, 4]
list2 = [5, 6, 7, 8]

# extending first list
list1.extend(list2)
print(list1)

# creating a copy
nlist = list1.copy()
print(nlist)

# clearing list
list1.clear()
print(list1)
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]
[]

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.

Important

Keys must be unique and immutable, while stored values can be of any type, including other collections.

vals = {'firstname': 'Willy', 'lastname': 'Wonka', 'age': 35}

# printing dictionary
print(vals, type(vals))

# printing value associated with a given key
print(vals['firstname'], vals['lastname'])

# printing all keys
print(vals.keys())

# printing all values
print(vals.values())
{'firstname': 'Willy', 'lastname': 'Wonka', 'age': 35} <class 'dict'>
Willy Wonka
dict_keys(['firstname', 'lastname', 'age'])
dict_values(['Willy', 'Wonka', 35])

Exercises

  1. Declare the following variables:
vals = [-1, 2, 1, -4, 3, 5]
text = "This is a chain of text"
  1. Print the data type of each variable with the type() function.
  2. Print the length of each variable with the len() function.
  3. Print the list vals sorted from smallest to largest value with the sorted() function.
  4. Compute and print the mean value for the list vals.
  5. Use the index operator to create a new variable containing only the last value of vals.
  6. Insert in the first position of vals the number 7.
  7. Print a version of text with only uppercase letters.
  8. Find the index for the word “chain” in the variable text.
  9. Slice the text variable to create a new string that only contains “chain of text”.
  10. Split the text variable considering blank spaces as separators, and print the third word of the result.
  11. Compute the range of vals (maximum minus minimum value) and print the result.
  12. Compare whether the range of vals is greater than the mean value vals.
  13. Convert the mean value of vals to string using the str() function. Print the data type before and after the conversion.
  14. Create a dictionary data with two keys: vals and text, storing the corresponding variables. Print all keys and retrieve the value associated with each key.

Additional resources