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))
- Variable can now be reassigned with a value of different data type
name = 100
print(name)
print(type(name))
- 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)
# Float to integer
num1 = int(40.23)
num2 = int(40.93)
num3 = int(41.00)
print(num1)
print(num2)
print(num3)
# Tuple to list
elems = list(("A","B","C","D"))
print(elems)
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))
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)
- Length of the string can be returned with len(function)
# Return length of the whole string
len(sentence)
- Below is an example where positive and negative indexing information is presented
# 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])
- 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])
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)
# Format string
s = "{} is going to paint his {} in {} color.".format("Mike","fence","white")
print(s)
# Check if the first character in string is a letter
var1 = "automatic"
var2 = "2021"
print(var1[0].isalpha())
print(var2[0].isalpha())
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))
- 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)
# Subtraction
print(30 - 15 - 5)
# Multiplication
print(50 * 5)
# Division for floating number
print(25 / 6)
# Division for whole number
print(25 // 6)
# Power
print(2**8)
# Modulo
print(25 % 5)
print(27 % 5)
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)
- List elements can be accessed by using element index number inside square brackets
# Get the last element from grocery list
print(grocery_collection[-1])
- 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)
- 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)
- 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)
- 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)
# Remove salad from the grocery list
del grocery_collection[2]
print(grocery_collection)
# Remove flour from the grocery list
grocery_collection.pop(-1)
# Remove milk from the grocery list
grocery_collection.remove("Milk")
print(grocery_collection)
- 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)
- 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)
- 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)
# Count the appearance of Honey in the grocery list
print(grocery_collection.count("Honey"))
# Get index of Coffee
print(grocery_collection.index("Coffee"))
# 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)
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))
- 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))
- 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))
- 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)
# Get the second sublist
print(new_2d_list[1])
# Get the last element from the third sublist
print(new_2d_list[2][-1])
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)
# Show data type
print(type(names))
# Print third element
print(names[2])
# Print last two names
print(names[-2:])
# Try to change the value
names[1] = "Barry"
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)
- 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)
- 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)
- 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())