Python fundamentals - Part 1#

  • In this lesson we take a look how we can utilize Anaconda environment to write and run Python
  • This lesson can also be considered as a brief repeat to basics of Python programming

Variables and data types#

  • In Python, variables are not declared
  • Variables do not need to be set with data type
  • Variable is created when the value is assigned to it
  • Data type of the variable can be checked with type() function
  • Important: Variable names cannot begin with number and can only contain alpha-numeric characters and underscores (A-z, 0-9 and _)
name = "Mike"
print(name)
print(type(name))
Mike
<class 'str'>

  • Variable can now be reassigned with a value of different data type
name = 100
print(name)
print(type(name))
100
<class 'int'>

  • Python has many built-in data types
  • Below is a table containing some of the different built-in data types in Python
Type Data type
Text str
Numeric int, float
Sequence list, tuple
Mapping dict
Set set
Boolean bool
Binary bytes, bytearray

Data type conversions#

  • Every once in a while there is a need to convert one data type to another
  • Python has five data type conversion functions
  • Table below presentes conversion functions and possible targets for conversion
Conversion function From To
int() String, floating point integer
float() String, integer floating point
str() Integer, floating point, list, tuple, dictionary string
list() String, tuple, dictionary list
tuple() String, list tuple
  • Let's go through some examples of conversions
# Integer to string
value = str(10000 + 2000 + 1000)
print(value)
13000

# Float to integer
num1 = int(40.23)
num2 = int(40.93)
num3 = int(41.00)
print(num1)
print(num2)
print(num3)
40
40
41

# Tuple to list
elems = list(("A","B","C","D"))
print(elems)
['A', 'B', 'C', 'D']

Comments#

  • There are two types of comments in Python:
    • single line comment (#)
    • multi line comment (""" """)
# Function call
def add_and_divide(a,b,c):
    return (a+b)/c
"""
Function called add_and_divide() will be
called here with the following parameters:
    - a = 5
    - b = 10
    - c = 15
The result will then be returned to user
"""
print(add_and_divide(5,10,15))

1.0

Strings#

  • Python does not have individual characters (CHAR) as data type but individual characters in string are presented as string with a length of 1
  • String parts are accessed in similar ways than in arrays (indexes start from 0)
  • Strings can be marked either with double quotes ("") or with quotes ('')
# Initialize variables and form a sentence
car = "Mustang"
owner = 'Mike'
sentence = owner + " has a red " + car + "."
print(sentence)
Mike has a red Mustang.

  • Length of the string can be returned with len(function)
# Return length of the whole string
len(sentence)
23
  • Below is an example where positive and negative indexing information is presented

String indexing in Python

# Print the first, tenth and last character from previously formed sentence
print("First character: " + sentence[0])
print("Tenth character: " + sentence[9])
print("Last character:" + sentence[-1])
First character: M
Tenth character: a
Last character:.

  • String can also be sliced with index information
  • Slicing means taking a part of existing string
  • Slicing syntax: string[x:y:z], where
    • x is the start index (will be the first character in the sliced string!)
    • y the end index (end index not included in sliced string!)
    • z determines the increment for indexes
# Print first eleven characters from the string
print(sentence[:11])

# Print the last half of the string
print(sentence[len(sentence)//2:])

# Print the reversed string
print(sentence[::-1])

# Print every other character
print(sentence[::2])
Mike has a 
red Mustang.
.gnatsuM der a sah ekiM
Mk a  e utn.

String functions#

  • Python has a lot of useful string functions
  • The most comprehensive and up-to-date list can be found from Python documentation here
  • In this section we are covering some of them
  • Below is a set of examples where several string methods are used
s = "At the end of the day, going forward, a new normal that has evolved from generation X is on the runway heading towards a streamlined cloud solution."

# Convert string to a list (use white space as separator)
lst = s.split(" ")
print(lst)
['At', 'the', 'end', 'of', 'the', 'day,', 'going', 'forward,', 'a', 'new', 'normal', 'that', 'has', 'evolved', 'from', 'generation', 'X', 'is', 'on', 'the', 'runway', 'heading', 'towards', 'a', 'streamlined', 'cloud', 'solution.']

# Format string
s = "{} is going to paint his {} in {} color.".format("Mike","fence","white")
print(s)
Mike is going to paint his fence in white color.

# Check if the first character in string is a letter
var1 = "automatic"
var2 = "2021"
print(var1[0].isalpha())
print(var2[0].isalpha())
True
False

Numbers#

  • In this section we cover basically the following two numeric datatypes:
    • int (Interger): either positive or negative whole number with unlimited length
    • float (Floating point number): either positive or negative number with decimals
    • float numbers can be rounded to integer or to a float number with certain amount of decimals using round() function
# First calculation
num = 5 + 5 + 5 + 5 + 10
print(num)

new_num = num / 45
print(new_num)

print(round(new_num,2))
30
0.6666666666666666
0.67

  • The following mathematical operators can be used for calculations
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division for floating number
// Division for whole number (down)
** Power
% Modulo
# Addition
print(5 + 10 + 15)
30

# Subtraction
print(30 - 15 - 5)
10

# Multiplication
print(50 * 5)
250

# Division for floating number
print(25 / 6)

# Division for whole number
print(25 // 6)
4.166666666666667
4

# Power
print(2**8)
256

# Modulo
print(25 % 5)
print(27 % 5)
0
2

Lists#

  • List is an ordered data structure where sequential numbers are stored inside square brackets and separated with comma
  • Lists have several operations we are going to cover in this section:
    • indexing
    • checking membership
    • slicing
    • adding
    • removing
  • List can have elements with different data types stored in it
  • Similar to strings list elements are accessed with index numbers either with positive or negative indexes
# Store groceries to list
grocery_collection = ["Cheese","Tomato","Salad","Potato"]
print(grocery_collection)

# Store person information to list
person = ["Mike","Johnson",38,"Edmonton"]
print(person)
['Cheese', 'Tomato', 'Salad', 'Potato']
['Mike', 'Johnson', 38, 'Edmonton']

  • List elements can be accessed by using element index number inside square brackets
# Get the last element from grocery list
print(grocery_collection[-1])
Potato

  • Elements can be added to list using append() method for list
# Add two groceries to list
grocery_collection.append("Cucumber")
grocery_collection.append("Milk")
print(grocery_collection)
['Cheese', 'Tomato', 'Salad', 'Potato', 'Cucumber', 'Milk']

  • There is also a possibility to add multiple elements with one line using extend() method
# Add a new list of groceries to the existing grocery list
grocery_collection.extend(["Juice","Coffee","Tomato","Honey","Salt","Cheese"])
print(grocery_collection)
['Cheese', 'Tomato', 'Salad', 'Potato', 'Cucumber', 'Milk', 'Juice', 'Coffee', 'Tomato', 'Honey', 'Salt', 'Cheese']

  • This could also be achieved with addition operator like shown in the example below
# Add a new list of groceries to the existing grocery list
grocery_collection = grocery_collection + ["Cerial","Sausage","flour"]
print(grocery_collection)
['Cheese', 'Tomato', 'Salad', 'Potato', 'Cucumber', 'Milk', 'Juice', 'Coffee', 'Tomato', 'Honey', 'Salt', 'Cheese', 'Cerial', 'Sausage', 'flour']

  • In Python you can remove list elements with three different ways:
    • del command: remove element by index number
    • pop method: remove element by index number and return the removed value
    • remove method: remove element by value
  • Existing list values can be reassigned with new values like shown in the example below
# Replace seventh element (Juice) with Tea
grocery_collection[6] = "Tea"
print(grocery_collection)
['Cheese', 'Tomato', 'Salad', 'Potato', 'Cucumber', 'Milk', 'Tea', 'Coffee', 'Tomato', 'Honey', 'Salt', 'Cheese', 'Cerial', 'Sausage', 'flour']

# Remove salad from the grocery list
del grocery_collection[2]
print(grocery_collection)
['Cheese', 'Tomato', 'Potato', 'Cucumber', 'Milk', 'Tea', 'Coffee', 'Tomato', 'Honey', 'Salt', 'Cheese', 'Cerial', 'Sausage', 'flour']

# Remove flour from the grocery list
grocery_collection.pop(-1)
'flour'
# Remove milk from the grocery list
grocery_collection.remove("Milk")
print(grocery_collection)
['Cheese', 'Tomato', 'Potato', 'Cucumber', 'Tea', 'Coffee', 'Tomato', 'Honey', 'Salt', 'Cheese', 'Cerial', 'Sausage']

  • Slicing works the same way for lists as it would with strings so the syntax is [start,end,step]
  • Let's slice our grocery list so that the new list would only have the last five groceries
# Leave only the last five elements to grocery list
new_grocery_collection = grocery_collection[-5:]
print(new_grocery_collection)
['Honey', 'Salt', 'Cheese', 'Cerial', 'Sausage']

  • Element membership can be checked with either in or not in operators
  • These operations will return True or False values depending whether the statement is true or not
# Check if Potato is a member
print("Potato" in new_grocery_collection)

# Check if Honey is a member
print("Honey" in new_grocery_collection)

# Check if Salad is not a member
print("Salad" not in new_grocery_collection)
False
True
True

  • Some other useful methods to cover here when we are operating with lists:
    • len() returns the length of the list
    • count() returns the count of given element in list
    • index() returns the index of desired element (returns error if element is not in the list)
    • set() returns a set with unique elements (duplicates will be removed from the input iterable data structure)
# Count the groceries from the original list
len(grocery_collection)
12
# Count the appearance of Honey in the grocery list
print(grocery_collection.count("Honey"))
1

# Get index of Coffee
print(grocery_collection.index("Coffee"))
5

# Remove duplicates (Tomato and Cheese) from the list
print(grocery_collection)
uniques = set(grocery_collection)
print(uniques)

# Important: The output is not a list!
print(type(uniques))
uniques = list(uniques)
print(type(uniques))
print(uniques)
['Cheese', 'Tomato', 'Potato', 'Cucumber', 'Tea', 'Coffee', 'Tomato', 'Honey', 'Salt', 'Cheese', 'Cerial', 'Sausage']
{'Cucumber', 'Honey', 'Sausage', 'Coffee', 'Salt', 'Cheese', 'Potato', 'Cerial', 'Tea', 'Tomato'}
<class 'set'>
<class 'list'>
['Cucumber', 'Honey', 'Sausage', 'Coffee', 'Salt', 'Cheese', 'Potato', 'Cerial', 'Tea', 'Tomato']

List sorting#

  • In Python lists can be sorted using sorted() function
  • This function requires at least the target list as an input, but it also has the following useful parameters:
    • key: for custom sorting operations
    • reverse: can be used for changing the sorting order (by default ascending order is used)
  • Below is an example where list containing integers is sorted with default settings (ascending order)
lst = [10,5,22,53,1,11,19]

print(sorted(lst))
[1, 5, 10, 11, 19, 22, 53]

  • Now let's check another example where we utilize key and reverse parameters
  • Below is an example where list of fruits is sorted alphabetically in descending order
lst = ["banana","mango","apple","lime","watermelon","grapefruit","pear"]

print(sorted(lst,reverse=True))
['watermelon', 'pear', 'mango', 'lime', 'grapefruit', 'banana', 'apple']

  • Key parameter accepts functions for customized sorting methods, but here we could utilize Python's built-in function len, which counts the length of strings
print(sorted(lst,key=len,reverse=True))
['watermelon', 'grapefruit', 'banana', 'mango', 'apple', 'lime', 'pear']

  • Now items were sorted by length in descending order

Two dimensional lists (Matrix)#

  • Two dimensional list (also called the matrix) is basically a list including sublists as elements
  • Accessing element inside two dimensional list is done with the following syntax: list[x][y], where
    • x = sublist selection
    • y = element selection inside the sublist
  • Below is an example where two dimensional list is first initialized and then couple of elements are retrieved from the two dimensional list
# Let's first initialize two dimensional list with values
new_2d_list = [[1,2,3,4,5],[6,7,8,9,10],["Apple","Banana","Pear","Avocado"],["Train","Car","Bus"]]
print(new_2d_list)
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], ['Apple', 'Banana', 'Pear', 'Avocado'], ['Train', 'Car', 'Bus']]

# Get the second sublist
print(new_2d_list[1])

# Get the last element from the third sublist
print(new_2d_list[2][-1])
[6, 7, 8, 9, 10]
Avocado

Tuples#

  • Tuple is similar to list except that elements stored in tuple cannot be changed
  • While lists are marked with square brackets [], tuple is marked with parenthesis
  • Element access and slicing is done using index numbers just like in lists
names = ("Mike","Jack","Sara","Whitney")
print(names)
('Mike', 'Jack', 'Sara', 'Whitney')

# Show data type
print(type(names))
<class 'tuple'>

# Print third element
print(names[2])
Sara

# Print last two names
print(names[-2:])
('Sara', 'Whitney')

# Try to change the value
names[1] = "Barry"
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Ubuntu\var\www\ttc2050-material\docs\material\01-python-fundamentals-part-1.ipynb Cell 75 in <cell line: 2>()
      <a href='vscode-notebook-cell://wsl%24/Ubuntu/var/www/ttc2050-material/docs/material/01-python-fundamentals-part-1.ipynb#Y134sZmlsZQ%3D%3D?line=0'>1</a> # Try to change the value
----> <a href='vscode-notebook-cell://wsl%24/Ubuntu/var/www/ttc2050-material/docs/material/01-python-fundamentals-part-1.ipynb#Y134sZmlsZQ%3D%3D?line=1'>2</a> names[1] = "Barry"

TypeError: 'tuple' object does not support item assignment

Dictionaries#

  • In dictionary is a data structure where elements are stored in key-value pairs
  • Keys and values are separated with colon (:) and similarly to lists each key-value pair is separated with comma
  • Elements can be accessed with key value
  • Similar to lists, dictionary can also have subdictionaries
  • In newer Python versions (3.7->) dictionaries are ordered data structures
# Let"s initialize a dictionary where we store fruits and colors
fruit_collection = {
    "apple":["red","green","yellow"],
    "banana":"yellow",
    "pear":"green",
    "orange":"orange",
    "kiwi":"brown"
}

print(fruit_collection)
{'apple': ['red', 'green', 'yellow'], 'banana': 'yellow', 'pear': 'green', 'orange': 'orange', 'kiwi': 'brown'}

  • Now the fruit colors can be retrieved by giving the fruit name as a key
  • Similarly, the existing values can be reassigned
# Get the color of banana
print(fruit_collection["banana"])

# Change the color of kiwi to be lightbrown
fruit_collection["kiwi"] = "lightbrown"
print(fruit_collection)
yellow
{'apple': ['red', 'green', 'yellow'], 'banana': 'yellow', 'pear': 'green', 'orange': 'orange', 'kiwi': 'lightbrown'}

  • Dictionary can also be presented as a list of dictionary objects
  • Below is an example where employees are stored in the list so that each employee has its information stored in dictionary object
# Employee collection
employee_collection = [
    {"firstname":"Mike",
    "lastname":"Johnson",
    "age":37},
    {"firstname":"Luke",
    "lastname":"Brown",
    "age":45},
    {"firstname":"Missy",
    "lastname":"Jackson",
    "age":28},
    {"firstname":"Carrie",
    "lastname":"Smith",
    "age":42}
]
print(employee_collection)

[{'firstname': 'Mike', 'lastname': 'Johnson', 'age': 37}, {'firstname': 'Luke', 'lastname': 'Brown', 'age': 45}, {'firstname': 'Missy', 'lastname': 'Jackson', 'age': 28}, {'firstname': 'Carrie', 'lastname': 'Smith', 'age': 42}]

  • It is also possible to retrieve list of keys or values of dictionary object
  • The example above has a list containing four employee objects
  • Since objects are list elements, let's print the keys and values of the first dict object using keys() and values() methods
print(employee_collection[0].keys())
print(employee_collection[0].values())
dict_keys(['firstname', 'lastname', 'age'])
dict_values(['Mike', 'Johnson', 37])