Python
Python
Example:
Getting user input using the input() built-in function. Let us assign the data
we get from a user into first_name and age variables. Example:
print(first_name)
print(age)
# Variables in Python
first_name = 'Asabeneh'
last_name = 'Yetayeh'
country = 'Finland'
city = 'Helsinki'
age = 250
is_married = True
skills = ['HTML', 'CSS', 'JS', 'React', 'Python']
person_info = {
'firstname':'Asabeneh',
'lastname':'Yetayeh',
'country':'Finland',
'city':'Helsinki'
}
first_name, last_name, country, age, is_married = 'Asabeneh', 'Yetayeh', 'Helsink', 250, True
String formatting
Old Style String Formatting (% Operator)
In Python there are many ways of formatting strings. In this section, we will
cover some of them. The "%" operator is used to format a set of variables
enclosed in a "tuple" (a fixed size list), together with a format string, which
contains normal text together with "argument specifiers", special symbols
like "%s", "%d", "%f", "%.number of digitsf".
# Strings only
first_name = 'Asabeneh'
last_name = 'Yetayeh'
language = 'Python'
formated_string = 'I am %s %s. I teach %s' %(first_name, last_name, language)
print(formated_string)
first_name = 'Asabeneh'
last_name = 'Yetayeh'
language = 'Python'
formated_string = 'I am {} {}. I teach {}'.format(first_name, last_name,
language)
print(formated_string)
a = 4
b = 3
# output
4 + 3 = 7
4 - 3 = 1
4 * 3 = 12
4 / 3 = 1.33
4 % 3 = 1
4 // 3 = 1
4 ** 3 = 64
# Strings and numbers
radius = 10
pi = 3.14
area = pi * radius ** 2
formated_string = 'The area of a circle with a radius {} is
{:.2f}.'.format(radius, area) # 2 digits after decimal
print(formated_string)
a = 4
b = 3
print(f'{a} + {b} = {a +b}')
print(f'{a} - {b} = {a - b}')
print(f'{a} * {b} = {a * b}')
print(f'{a} / {b} = {a / b:.2f}')
print(f'{a} % {b} = {a % b}')
print(f'{a} // {b} = {a // b}')
print(f'{a} ** {b} = {a ** b}')
Unpacking Characters
language = 'Python'
a,b,c,d,e,f = language # unpacking sequence characters into variables
print(a) # P
print(b) # y
print(c) # t
print(d) # h
print(e) # o
print(f) # n
If we want to start from right end we can use negative indexing. -1 is the last
index.
language = 'Python'
last_letter = language[-1]
print(last_letter) # n
second_last = language[-2]
print(second_last) # o
language = 'Python'
Reversing a String
We can easily reverse strings in python.
language = 'Python'
pto = language[0:6:2] #
print(pto) # Pto
challenge = 'thirty\tdays\tof\tpython'
print([Link]()) # 'thirty days of python'
print([Link](10)) # 'thirty days of python'
first_name = 'Asabeneh'
last_name = 'Yetayeh'
age = 250
job = 'teacher'
country = 'Finland'
sentence = 'I am {} {}. I am a {}. I am {} years old. I live in
{}.'.format(first_name, last_name, age, job, country)
print(sentence) # I am Asabeneh Yetayeh. I am 250 years old. I am a teacher.
I live in Finland.
radius = 10
pi = 3.14
area = pi * radius ** 2
result = 'The area of a circle with radius {} is {}'.format(str(radius),
str(area))
print(result) # The area of a circle with radius 10 is 314
challenge = 'ThirtyDaysPython'
print([Link]()) # True
challenge = '30DaysPython'
print([Link]()) # True
isalpha(): Checks if all string elements are alphabet characters (a-z and
A-Z)
isdigit(): Checks if all characters in a string are numbers (0-9 and some
other unicode characters for numbers)
challenge = 'Thirty'
print([Link]()) # False
challenge = '30'
print([Link]()) # True
challenge = '\u00B2'
print([Link]()) # True
num = '10'
print([Link]()) # True
num = '\u00BD' # ½
print([Link]()) # True
num = '10.5'
print([Link]()) # False
challenge = '30DaysOfPython'
print([Link]()) # False, because it starts with a number
challenge = 'thirty_days_of_python'
print([Link]()) # True
islower(): Checks if all alphabet characters in the string are lowercase
strip(): Removes all given characters starting from the beginning and
end of the string
🌕 You are an extraordinary person and you have a remarkable potential. You
have just completed day 4 challenges and you are four steps a head in to
your way to greatness. Now do some exercises for your brain and muscles.
radius = 10
area = 3.14 * radius ** 2
The area of a circle with radius 10 is 314 meters square.
8 + 6 = 14
8 - 6 = 2
8 * 6 = 48
8 / 6 = 1.33
8 % 6 = 2
8 // 6 = 1
8 ** 6 = 262144
# String Concatenation
first_name = 'Asabeneh'
last_name = 'Yetayeh'
space = ' '
full_name = first_name + space + last_name
print(full_name) # Asabeneh Yetayeh
# Checking length of a string using len() builtin function
print(len(first_name)) # 8
print(len(last_name)) # 7
print(len(first_name) > len(last_name)) # True
print(len(full_name)) # 15
# If we want to start from right end we can use negative indexing. -1 is the
last index
language = 'Python'
last_letter = language[-1]
print(last_letter) # n
second_last = language[-2]
print(second_last) # o
# Slicing
language = 'Python'
first_three = language[0:3] # starts at zero index and up to 3 but not
include 3
last_three = language[3:6]
print(last_three) # hon
# Another way
last_three = language[-3:]
print(last_three) # hon
last_three = language[3:]
print(last_three) # hon
## String Methods
# capitalize(): Converts the first character the string to Capital Letter
radius = 10
pi = 3.14
area = pi # radius ## 2
result = 'The area of circle with {} is {}'.format(str(radius), str(area))
print(result) # The area of circle with 10 is 314.0
challenge = '30DaysPython'
print([Link]()) # True
challenge = 'Thirty'
print([Link]()) # False
challenge = '30'
print([Link]()) # True
challenge = '30DaysOfPython'
print([Link]()) # False, because it starts with a number
challenge = 'thirty_days_of_python'
print([Link]()) # True
# syntax
lst = list()
empty_list = list() # this is an empty list, no item in the list
print(len(empty_list)) # 0
# syntax
lst = []
empty_list = [] # this is an empty list, no item in the list
print(len(empty_list)) # 0
Lists with initial values. We use len() to find the length of a list.
Negative indexing means beginning from the end, -1 refers to the last item, -
2 refers to the second last item.
Modifying Lists
List is a mutable or modifiable ordered collection of items. Lets modify the
fruit list.
# syntax
lst = list()
[Link](item)
fruits = ['banana', 'orange', 'mango', 'lemon']
[Link]('apple')
print(fruits) # ['banana', 'orange', 'mango', 'lemon', 'apple']
[Link]('lime') # ['banana', 'orange', 'mango', 'lemon', 'apple',
'lime']
print(fruits)
# syntax
lst = ['item1', 'item2']
[Link](index, item)
fruits = ['banana', 'orange', 'mango', 'lemon']
[Link](2, 'apple') # insert apple between orange and mango
print(fruits) # ['banana', 'orange', 'apple', 'mango', 'lemon']
[Link](3, 'lime') # ['banana', 'orange', 'apple', 'lime', 'mango',
'lemon']
print(fruits)
# syntax
lst = ['item1', 'item2']
[Link](item)
fruits = ['banana', 'orange', 'mango', 'lemon', 'banana']
[Link]('banana')
print(fruits) # ['orange', 'mango', 'lemon', 'banana'] - this method removes
the first occurrence of the item in the list
[Link]('lemon')
print(fruits) # ['orange', 'mango', 'banana']
# syntax
lst = ['item1', 'item2']
[Link]() # last item
[Link](index)
fruits = ['banana', 'orange', 'mango', 'lemon']
[Link]()
print(fruits) # ['banana', 'orange', 'mango']
[Link](0)
print(fruits) # ['orange', 'mango']
# syntax
lst = ['item1', 'item2']
del lst[index] # only a single item
del lst # to delete the list completely
fruits = ['banana', 'orange', 'mango', 'lemon', 'kiwi', 'lime']
del fruits[0]
print(fruits) # ['orange', 'mango', 'lemon', 'kiwi', 'lime']
del fruits[1]
print(fruits) # ['orange', 'lemon', 'kiwi', 'lime']
del fruits[1:3] # this deletes items between given indexes, so it does
not delete the item with index 3!
print(fruits) # ['orange', 'lime']
del fruits
print(fruits) # This should give: NameError: name 'fruits' is not
defined
# syntax
lst = ['item1', 'item2']
[Link]()
fruits = ['banana', 'orange', 'mango', 'lemon']
[Link]()
print(fruits) # []
Copying a List
It is possible to copy a list by reassigning it to a new variable in the following
way: list2 = list1. Now, list2 is a reference of list1, any changes we make in
list2 will also modify the original, list1. But there are lots of case in which we
do not like to modify the original instead we like to have a different copy.
One of way of avoiding the problem above is using copy().
# syntax
lst = ['item1', 'item2']
lst_copy = [Link]()
fruits = ['banana', 'orange', 'mango', 'lemon']
fruits_copy = [Link]()
print(fruits_copy) # ['banana', 'orange', 'mango', 'lemon']
Joining Lists
There are several ways to join, or concatenate, two or more lists in Python.
# syntax
list3 = list1 + list2
positive_numbers = [1, 2, 3, 4, 5]
zero = [0]
negative_numbers = [-5,-4,-3,-2,-1]
integers = negative_numbers + zero + positive_numbers
print(integers) # [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
fruits = ['banana', 'orange', 'mango', 'lemon']
vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot']
fruits_and_vegetables = fruits + vegetables
print(fruits_and_vegetables ) # ['banana', 'orange', 'mango', 'lemon',
'Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot']
# syntax
list1 = ['item1', 'item2']
list2 = ['item3', 'item4', 'item5']
[Link](list2)
num1 = [0, 1, 2, 3]
num2= [4, 5, 6]
[Link](num2)
print('Numbers:', num1) # Numbers: [0, 1, 2, 3, 4, 5, 6]
negative_numbers = [-5,-4,-3,-2,-1]
positive_numbers = [1, 2, 3,4,5]
zero = [0]
negative_numbers.extend(zero)
negative_numbers.extend(positive_numbers)
print('Integers:', negative_numbers) # Integers: [-5, -4, -3, -2, -1, 0, 1,
2, 3, 4, 5]
fruits = ['banana', 'orange', 'mango', 'lemon']
vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot']
[Link](vegetables)
print('Fruits and vegetables:', fruits ) # Fruits and vegetables: ['banana',
'orange', 'mango', 'lemon', 'Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot']
# syntax
lst = ['item1', 'item2']
[Link](item)
fruits = ['banana', 'orange', 'mango', 'lemon']
print([Link]('orange')) # 1
ages = [22, 19, 24, 25, 26, 24, 25, 24]
print([Link](24)) # 3
# syntax
lst = ['item1', 'item2']
[Link](item)
fruits = ['banana', 'orange', 'mango', 'lemon']
print([Link]('orange')) # 1
ages = [22, 19, 24, 25, 26, 24, 25, 24]
print([Link](24)) # 2, the first occurrence
Reversing a List
The reverse() method reverses the order of a list.
# syntax
lst = ['item1', 'item2']
[Link]()
fruits = ['banana', 'orange', 'mango', 'lemon']
[Link]()
print(fruits) # ['lemon', 'mango', 'orange', 'banana']
ages = [22, 19, 24, 25, 26, 24, 25, 24]
[Link]()
print(ages) # [24, 25, 24, 26, 25, 24, 19, 22]
# syntax
lst = ['item1', 'item2']
[Link]() # ascending
[Link](reverse=True) # descending
Example:
[Link](reverse=True)
print(ages) # [26, 25, 25, 24, 24, 24, 22, 19]
# Modifying list
# Accessing items
fruits = ['banana', 'orange', 'mango', 'lemon']
last_fruit = fruits[-1]
second_last = fruits[-2]
print(last_fruit) # lemon
print(second_last) # mango
# Slicing items
fruits = ['banana', 'orange', 'mango', 'lemon']
all_fruits = fruits[0:4] # it returns all the fruits
# this is also give the same result as the above
all_fruits = fruits[0:] # if we don't set where to stop it takes all the rest
orange_and_mango = fruits[1:3] # it does not include the end index
orange_mango_lemon = fruits[1:]
# checking items
fruits = ['banana', 'orange', 'mango', 'lemon']
does_exist = 'banana' in fruits
print(does_exist) # True
does_exist = 'lime' in fruits
print(does_exist) # False
# Append
fruits = ['banana', 'orange', 'mango', 'lemon']
[Link]('apple')
print(fruits) # ['banana', 'orange', 'mango', 'lemon', 'apple']
[Link]('lime') # ['banana', 'orange', 'mango', 'lemon', 'apple',
'lime]
print(fruits)
# insert
fruits = ['banana', 'orange', 'mango', 'lemon']
[Link](2, 'apple') # insert apple between orange and mango
print(fruits) # ['banana', 'orange', 'apple', 'mango', 'lemon']
[Link](3, 'lime') # ['banana', 'orange', 'apple', 'mango',
'lime','lemon',]
print(fruits)
# remove
fruits = ['banana', 'orange', 'mango', 'lemon']
[Link]('banana')
print(fruits) # ['orange', 'mango', 'lemon']
[Link]('lemon')
print(fruits) # ['orange', 'mango']
# pop
fruits = ['banana', 'orange', 'mango', 'lemon']
[Link]()
print(fruits) # ['banana', 'orange', 'mango']
[Link](0)
print(fruits) # ['orange', 'mango']
# del
fruits = ['banana', 'orange', 'mango', 'lemon']
del fruits[0]
print(fruits) # ['orange', 'mango', 'lemon']
del fruits[1]
print(fruits) # ['orange', 'lemon']
del fruits
print(fruits) # This should give: NameError: name 'fruits' is not
defined
# clear
fruits = ['banana', 'orange', 'mango', 'lemon']
[Link]()
print(fruits) # []
# copying a lits
# join
positive_numbers = [1, 2, 3,4,5]
zero = [0]
negative_numbers = [-5,-4,-3,-2,-1]
integers = negative_numbers + zero + positive_numbers
print(integers)
fruits = ['banana', 'orange', 'mango', 'lemon']
vegetables = ['Tomato', 'Potato', 'Cabbage','Onion', 'Carrot']
fruits_and_vegetables = fruits + vegetables
print(fruits_and_vegetables )
negative_numbers.extend(zero)
negative_numbers.extend(positive_numbers)
print('Integers:', negative_numbers)
fruits = ['banana', 'orange', 'mango', 'lemon']
vegetables = ['Tomato', 'Potato', 'Cabbage','Onion', 'Carrot']
[Link](vegetables)
print('Fruits and vegetables:', fruits )
# count
fruits = ['banana', 'orange', 'mango', 'lemon']
print([Link]('orange')) # 1
ages = [22, 19, 24, 25, 26, 24, 25, 24]
print([Link](24)) # 3
# index
fruits = ['banana', 'orange', 'mango', 'lemon']
print([Link]('orange')) # 1
ages = [22, 19, 24, 25, 26, 24, 25, 24]
print([Link](24))
# Reverse
fruits = ['banana', 'orange', 'mango', 'lemon']
[Link]()
print(fruits)
ages = [22, 19, 24, 25, 26, 24, 25, 24]
[Link]()
print(ages)
# sort
fruits = ['banana', 'orange', 'mango', 'lemon']
[Link]()
print(fruits)
[Link](reverse=True)
print(fruits)
ages = [22, 19, 24, 25, 26, 24, 25, 24]
[Link]()
print(ages)
[Link](reverse=True)
print(ages)
Tuples
A tuple is a collection of different data types which is ordered and
unchangeable (immutable). Tuples are written with round brackets, (). Once
a tuple is created, we cannot change its values. We cannot use add, insert,
remove methods in a tuple because it is not modifiable (mutable). Unlike list,
tuple has few methods. Methods related to tuples:
Creating a Tuple
Empty tuple: Creating an empty tuple
# syntax
empty_tuple = ()
# or using the tuple constructor
empty_tuple = tuple()
# syntax
tpl = ('item1', 'item2','item3')
fruits = ('banana', 'orange', 'mango', 'lemon')
Tuple length
We use the len() method to get the length of a tuple.
# syntax
tpl = ('item1', 'item2', 'item3')
len(tpl)
# Syntax
tpl = ('item1', 'item2', 'item3')
first_item = tpl[0]
second_item = tpl[1]
fruits = ('banana', 'orange', 'mango', 'lemon')
first_fruit = fruits[0]
second_fruit = fruits[1]
last_index =len(fruits) - 1
last_fruit = fruits[las_index]
# Syntax
tpl = ('item1', 'item2', 'item3','item4')
first_item = tpl[-4]
second_item = tpl[-3]
fruits = ('banana', 'orange', 'mango', 'lemon')
first_fruit = fruits[-4]
second_fruit = fruits[-3]
last_fruit = fruits[-1]
Slicing tuples
We can slice out a sub-tuple by specifying a range of indexes where to start
and where to end in the tuple, the return value will be a new tuple with the
specified items.
# Syntax
tpl = ('item1', 'item2', 'item3','item4')
all_items = tpl[0:4] # all items
all_items = tpl[0:] # all items
middle_two_items = tpl[1:3] # does not include item at index 3
fruits = ('banana', 'orange', 'mango', 'lemon')
all_fruits = fruits[0:4] # all items
all_fruits= fruits[0:] # all items
orange_mango = fruits[1:3] # doesn't include item at index 3
orange_to_the_rest = fruits[1:]
# Syntax
tpl = ('item1', 'item2', 'item3','item4')
all_items = tpl[-4:] # all items
middle_two_items = tpl[-3:-1] # does not include item at index 3 (-1)
fruits = ('banana', 'orange', 'mango', 'lemon')
all_fruits = fruits[-4:] # all items
orange_mango = fruits[-3:-1] # doesn't include item at index 3
orange_to_the_rest = fruits[-3:]
# Syntax
tpl = ('item1', 'item2', 'item3','item4')
lst = list(tpl)
fruits = ('banana', 'orange', 'mango', 'lemon')
fruits = list(fruits)
fruits[0] = 'apple'
print(fruits) # ['apple', 'orange', 'mango', 'lemon']
fruits = tuple(fruits)
print(fruits) # ('apple', 'orange', 'mango', 'lemon')
# Syntax
tpl = ('item1', 'item2', 'item3','item4')
'item2' in tpl # True
fruits = ('banana', 'orange', 'mango', 'lemon')
print('orange' in fruits) # True
print('apple' in fruits) # False
fruits[0] = 'apple' # TypeError: 'tuple' object does not support item
assignment
Joining Tuples
We can join two or more tuples using + operator
# syntax
tpl1 = ('item1', 'item2', 'item3')
tpl2 = ('item4', 'item5','item6')
tpl3 = tpl1 + tpl2
fruits = ('banana', 'orange', 'mango', 'lemon')
vegetables = ('Tomato', 'Potato', 'Cabbage','Onion', 'Carrot')
fruits_and_vegetables = fruits + vegetables
Deleting Tuples
It is not possible to remove a single item in a tuple but it is possible to delete
the tuple itself using del.
# syntax
tpl1 = ('item1', 'item2', 'item3')
del tpl1
fruits = ('banana', 'orange', 'mango', 'lemon')
del fruits
🌕 You are so brave, you made it to this far. You have just completed day 6
challenges and you are 6 steps a head in to your way to greatness. Now do
some exercises for your brain and for your muscle.
Sets
Set is a collection of items. Let me take you back to your elementary or high
school Mathematics lesson. The Mathematics definition of a set can be
applied also in Python. Set is a collection of unordered and un-indexed
distinct elements. In Python set is used to store unique items, and it is
possible to find the union, intersection, difference, symmetric
difference, subset, super set and disjoint set among sets.
Creating a Set
We use the set() built-in function.
# syntax
st = set()
# syntax
st = {'item1', 'item2', 'item3', 'item4'}
Example:
# syntax
fruits = {'banana', 'orange', 'mango', 'lemon'}
# syntax
st = {'item1', 'item2', 'item3', 'item4'}
len(st)
Example:
Checking an Item
To check if an item exist in a list we use in membership operator.
# syntax
st = {'item1', 'item2', 'item3', 'item4'}
print("Does set st contain item3? ", 'item3' in st) # Does set st contain
item3? True
Example:
# syntax
st = {'item1', 'item2', 'item3', 'item4'}
[Link]('item5')
Example:
Add multiple items using update() The update() allows to add multiple
items to a set. The update() takes a list argument.
# syntax
st = {'item1', 'item2', 'item3', 'item4'}
[Link](['item5','item6','item7'])
Example:
# syntax
st = {'item1', 'item2', 'item3', 'item4'}
[Link]('item2')
The pop() methods remove a random item from a list and it returns the
removed item.
Example:
# syntax
st = {'item1', 'item2', 'item3', 'item4'}
[Link]()
Example:
Deleting a Set
If we want to delete the set itself we use del operator.
# syntax
st = {'item1', 'item2', 'item3', 'item4'}
del st
Example:
# syntax
lst = ['item1', 'item2', 'item3', 'item4', 'item1']
st = set(lst) # {'item2', 'item4', 'item1', 'item3'} - the order is random,
because sets in general are unordered
Example:
Joining Sets
We can join two sets using the union() or update() method.
# syntax
st1 = {'item1', 'item2', 'item3', 'item4'}
st2 = {'item5', 'item6', 'item7', 'item8'}
st3 = [Link](st2)
Example:
# syntax
st1 = {'item1', 'item2', 'item3', 'item4'}
st2 = {'item5', 'item6', 'item7', 'item8'}
[Link](st2) # st2 contents are added to st1
Example:
# syntax
st1 = {'item1', 'item2', 'item3', 'item4'}
st2 = {'item3', 'item2'}
[Link](st2) # {'item3', 'item2'}
Example:
Subset: issubset()
Super set: issuperset
# syntax
st1 = {'item1', 'item2', 'item3', 'item4'}
st2 = {'item2', 'item3'}
[Link](st1) # True
[Link](st2) # True
Example:
# syntax
st1 = {'item1', 'item2', 'item3', 'item4'}
st2 = {'item2', 'item3'}
[Link](st1) # set()
[Link](st2) # {'item1', 'item4'} => st1\st2
Example:
# syntax
st1 = {'item1', 'item2', 'item3', 'item4'}
st2 = {'item2', 'item3'}
# it means (A\B)∪(B\A)
st2.symmetric_difference(st1) # {'item1', 'item4'}
Example:
whole_numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
some_numbers = {1, 2, 3, 4, 5}
whole_numbers.symmetric_difference(some_numbers) # {0, 6, 7, 8, 9, 10}
Joining Sets
If two sets do not have a common item or items we call them disjoint sets.
We can check if two sets are joint or disjoint using isdisjoint() method.
# syntax
st1 = {'item1', 'item2', 'item3', 'item4'}
st2 = {'item2', 'item3'}
[Link](st1) # False
Example:
🌕 You are a rising star . You have just completed day 7 challenges and you
are 7 steps ahead in to your way to greatness. Now do some exercises for
your brain and muscles.
Dictionaries
A dictionary is a collection of unordered, modifiable(mutable) paired (key:
value) data type.
Creating a Dictionary
To create a dictionary we use curly brackets, {} or the dict() built-in function.
# syntax
empty_dict = {}
# Dictionary with data values
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
Example:
person = {
'first_name':'Asabeneh',
'last_name':'Yetayeh',
'age':250,
'country':'Finland',
'is_marred':True,
'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],
'address':{
'street':'Space street',
'zipcode':'02210'
}
}
The dictionary above shows that a value could be any data types:string,
boolean, list, tuple, set or a dictionary.
Dictionary Length
It checks the number of 'key: value' pairs in the dictionary.
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
print(len(dct)) # 4
Example:
person = {
'first_name':'Asabeneh',
'last_name':'Yetayeh',
'age':250,
'country':'Finland',
'is_married':True,
'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],
'address':{
'street':'Space street',
'zipcode':'02210'
}
}
print(len(person)) # 7
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
print(dct['key1']) # value1
print(dct['key4']) # value4
Example:
person = {
'first_name':'Asabeneh',
'last_name':'Yetayeh',
'age':250,
'country':'Finland',
'is_marred':True,
'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],
'address':{
'street':'Space street',
'zipcode':'02210'
}
}
print(person['first_name']) # Asabeneh
print(person['country']) # Finland
print(person['skills']) # ['JavaScript', 'React', 'Node', 'MongoDB',
'Python']
print(person['skills'][0]) # JavaScript
print(person['address']['street']) # Space street
print(person['city']) # Error
Accessing an item by key name raises an error if the key does not exist. To
avoid this error first we have to check if a key exist or we can use
the get method. The get method returns None, which is a NoneType object
data type, if the key does not exist.
person = {
'first_name':'Asabeneh',
'last_name':'Yetayeh',
'age':250,
'country':'Finland',
'is_marred':True,
'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],
'address':{
'street':'Space street',
'zipcode':'02210'
}
}
print([Link]('first_name')) # Asabeneh
print([Link]('country')) # Finland
print([Link]('skills')) #['HTML','CSS','JavaScript', 'React', 'Node',
'MongoDB', 'Python']
print([Link]('city')) # None
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
dct['key5'] = 'value5'
Example:
person = {
'first_name':'Asabeneh',
'last_name':'Yetayeh',
'age':250,
'country':'Finland',
'is_marred':True,
'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],
'address':{
'street':'Space street',
'zipcode':'02210'
}
}
person['job_title'] = 'Instructor'
person['skills'].append('HTML')
print(person)
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
dct['key1'] = 'value-one'
Example:
person = {
'first_name':'Asabeneh',
'last_name':'Yetayeh',
'age':250,
'country':'Finland',
'is_marred':True,
'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],
'address':{
'street':'Space street',
'zipcode':'02210'
}
}
person['first_name'] = 'Eyob'
person['age'] = 252
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
print('key2' in dct) # True
print('key5' in dct) # False
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
[Link]('key1') # removes key1 item
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
[Link]() # removes the last item
del dct['key2'] # removes key2 item
Example:
person = {
'first_name':'Asabeneh',
'last_name':'Yetayeh',
'age':250,
'country':'Finland',
'is_marred':True,
'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],
'address':{
'street':'Space street',
'zipcode':'02210'
}
}
[Link]('first_name') # Removes the firstname item
[Link]() # Removes the address item
del person['is_married'] # Removes the is_married item
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
print([Link]()) # dict_items([('key1', 'value1'), ('key2', 'value2'),
('key3', 'value3'), ('key4', 'value4')])
Clearing a Dictionary
If we don't want the items in a dictionary we can clear them
using clear() method
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
print([Link]()) # None
Deleting a Dictionary
If we do not use the dictionary we can delete it completely
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
del dct
Copy a Dictionary
We can copy a dictionary using a copy() method. Using copy we can avoid
mutation of the original dictionary.
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
dct_copy = [Link]() # {'key1':'value1', 'key2':'value2', 'key3':'value3',
'key4':'value4'}
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
keys = [Link]()
print(keys) # dict_keys(['key1', 'key2', 'key3', 'key4'])
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
values = [Link]()
print(values) # dict_values(['value1', 'value2', 'value3', 'value4'])
🌕 You are astonishing. Now, you are super charged with the power of
dictionaries. You have just completed day 8 challenges and you are 8 steps a
head in to your way to greatness. Now do some exercises for your brain and
muscles.
Conditionals
By default, statements in Python script are executed sequentially from top to
bottom. If the processing logic require so, the sequential flow of execution
can be altered in two way:
# syntax
if condition:
this part of code runs for truthy conditions
Example: 1
a = 3
if a > 0:
print('A is a positive number')
# A is a positive number
As you can see in the example above, 3 is greater than 0. The condition was
true and the block code was executed. However, if the condition is false, we
do not see the result. In order to see the result of the falsy condition, we
should have another block, which is going to be else.
If Else
If condition is true the first block will be executed, if not the else condition
will run.
# syntax
if condition:
this part of code runs for truthy conditions
else:
this part of code runs for false conditions
Example:
a = 3
if a < 0:
print('A is a negative number')
else:
print('A is a positive number')
The condition above proves false, therefore the else block was executed.
How about if our condition is more than two? We could use elif.
If Elif Else
In our daily life, we make decisions on daily basis. We make decisions not by
checking one or two conditions but multiple conditions. As similar to life,
programming is also full of conditions. We use elif when we have multiple
conditions.
# syntax
if condition:
code
elif condition:
code
else:
code
Example:
a = 0
if a > 0:
print('A is a positive number')
elif a < 0:
print('A is a negative number')
else:
print('A is zero')
Short Hand
# syntax
code if condition else code
Example:
a = 3
print('A is positive') if a > 0 else print('A is negative') # first condition
met, 'A is positive' will be printed
Nested Conditions
Conditions can be nested
# syntax
if condition:
code
if condition:
code
Example:
a = 0
if a > 0:
if a % 2 == 0:
print('A is a positive and even integer')
else:
print('A is a positive number')
elif a == 0:
print('A is zero')
else:
print('A is a negative number')
Example:
a = 0
if a > 0 and a % 2 == 0:
print('A is an even and positive integer')
elif a > 0 and a % 2 != 0:
print('A is a positive integer')
elif a == 0:
print('A is zero')
else:
print('A is negative')
Example:
user = 'James'
access_level = 3
if user == 'admin' or access_level >= 4:
print('Access granted!')
else:
print('Access denied!')
🌕 You are doing [Link] give up because great things take time. You
have just completed day 9 challenges and you are 9 steps a head in to your
way to greatness. Now do some exercises for your brain and muscles.
Loops
Life is full of routines. In programming we also do lots of repetitive tasks. In
order to handle repetitive task programming languages use loops. Python
programming language also provides the following types of two loops:
1. while loop
2. for loop
While Loop
We use the reserved word while to make a while loop. It is used to execute a
block of statements repeatedly until a given condition is satisfied. When the
condition becomes false, the lines of code after the loop will be continued to
be executed.
# syntax
while condition:
code goes here
Example:
count = 0
while count < 5:
print(count)
count = count + 1
#prints from 0 to 4
In the above while loop, the condition becomes false when count is 5. That is
when the loop stops. If we are interested to run block of code once the
condition is no longer true, we can use else.
# syntax
while condition:
code goes here
else:
code goes here
Example:
count = 0
while count < 5:
print(count)
count = count + 1
else:
print(count)
The above loop condition will be false when count is 5 and the loop stops,
and execution starts the else statement. As a result 5 will be printed.
# syntax
while condition:
code goes here
if another_condition:
break
Example:
count = 0
while count < 5:
print(count)
count = count + 1
if count == 3:
break
The above while loop only prints 0, 1, 2, but when it reaches 3 it stops.
# syntax
while condition:
code goes here
if another_condition:
continue
Example:
count = 0
while count < 5:
if count == 3:
count = count + 1
continue
print(count)
count = count + 1
For Loop
A for keyword is used to make a for loop, similar with other programming
languages, but with some syntax differences. Loop is used for iterating over
a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
# syntax
for iterator in lst:
code goes here
Example:
numbers = [0, 1, 2, 3, 4, 5]
for number in numbers: # number is temporary name to refer to the list's
items, valid only inside this loop
print(number) # the numbers will be printed line by line, from 0 to
5
# syntax
for iterator in string:
code goes here
Example:
language = 'Python'
for letter in language:
print(letter)
for i in range(len(language)):
print(language[i])
# syntax
for iterator in tpl:
code goes here
Example:
numbers = (0, 1, 2, 3, 4, 5)
for number in numbers:
print(number)
For loop with dictionary Looping through a dictionary gives you the key
of the dictionary.
# syntax
for iterator in dct:
code goes here
Example:
person = {
'first_name':'Asabeneh',
'last_name':'Yetayeh',
'age':250,
'country':'Finland',
'is_marred':True,
'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],
'address':{
'street':'Space street',
'zipcode':'02210'
}
}
for key in person:
print(key)
Loops in set
# syntax
for iterator in st:
code goes here
Example:
# syntax
for iterator in sequence:
code goes here
if condition:
break
Example:
numbers = (0,1,2,3,4,5)
for number in numbers:
print(number)
if number == 3:
break
Continue: We use continue when we like to skip some of the steps in the
iteration of the loop.
# syntax
for iterator in sequence:
code goes here
if condition:
continue
Example:
numbers = (0,1,2,3,4,5)
for number in numbers:
print(number)
if number == 3:
continue
print('Next number should be ', number + 1) if number != 5 else
print("loop's end") # for short hand conditions need both if and else
statements
print('outside the loop')
In the example above, if the number equals 3, the step after the condition
(but inside the loop) is skipped and the execution of the loop continues if
there are any iterations left.
lst = list(range(11))
print(lst) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
st = set(range(1, 11)) # 2 arguments indicate start and end of the
sequence, step set to default 1
print(st) # {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
lst = list(range(0,11,2))
print(lst) # [0, 2, 4, 6, 8, 10]
st = set(range(0,11,2))
print(st) # {0, 2, 4, 6, 8, 10}
# syntax
for iterator in range(start, end, step):
Example:
# syntax
for x in y:
for t in x:
print(t)
Example:
person = {
'first_name': 'Asabeneh',
'last_name': 'Yetayeh',
'age': 250,
'country': 'Finland',
'is_marred': True,
'skills': ['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],
'address': {
'street': 'Space street',
'zipcode': '02210'
}
}
for key in person:
if key == 'skills':
for skill in person['skills']:
print(skill)
For Else
If we want to execute some message when the loop ends, we use else.
# syntax
for iterator in range(start, end, step):
do something
else:
print('The loop ended')
Example:
Pass
In python when statement is required (after semicolon), but we don't like to
execute any code there, we can write the word pass to avoid errors. Also we
can use it as a placeholder, for future statements.
Example:
🌕 You established a big milestone, you are unstoppable. Keep going! You
have just completed day 10 challenges and you are 10 steps a head in to
your way to greatness. Now do some exercises for your brain and muscles.
Functions
So far we have seen many built-in Python functions. In this section, we will
focus on custom functions. What is a function? Before we start making
functions, let us learn what a function is and why we need them?
Defining a Function
A function is a reusable block of code or programming statements designed
to perform a certain task. To define or declare a function, Python provides
the def keyword. The following is the syntax for defining a function. The
function block of code is executed only if the function is called or invoked.
# syntax
# Declaring a function
def function_name():
codes
codes
# Calling a function
function_name()
Example:
# syntax
# Declaring a function
def function_name(parameter):
codes
codes
# Calling function
print(function_name(argument))
Example:
print(greetings('Asabeneh'))
def add_ten(num):
ten = 10
return num + ten
print(add_ten(90))
def square_number(x):
return x * x
print(square_number(2))
def sum_of_numbers(n):
total = 0
for i in range(n+1):
total+=i
print(total)
print(sum_of_numbers(10)) # 55
print(sum_of_numbers(100)) # 5050
# syntax
# Declaring a function
def function_name(para1, para2):
codes
codes
# Calling function
print(function_name(arg1, arg2))
Example:
# syntax
# Declaring a function
def function_name(para1, para2):
codes
codes
# Calling function
print(function_name(para1 = 'John', para2 = 'Doe')) # the order of arguments
does not matter here
Example:
def print_name(firstname):
return firstname
print_name('Asabeneh') # Asabeneh
Returning a number:
Example:
def find_even_numbers(n):
evens = []
for i in range(n + 1):
if i % 2 == 0:
[Link](i)
return evens
print(find_even_numbers(10))
# syntax
# Declaring a function
def function_name(param = value):
codes
codes
# Calling function
function_name()
function_name(arg)
Example:
print(generate_full_name())
print(generate_full_name('David','Smith'))
# syntax
# Declaring a function
def function_name(*args):
codes
codes
# Calling function
function_name(param1, param2, param3,..)
Example:
def sum_all_nums(*nums):
total = 0
for num in nums:
total += num # same as total = total + num
return total
print(sum_all_nums(2, 3, 5)) # 10
Exercises: Level 2
1. Declare a function named evens_and_odds . It takes a positive integer
as parameter and it counts number of evens and odds in the number.
print(evens_and_odds(100))
# The number of odds are 50.
# The number of evens are 51.
Modules
What is a Module
A module is a file containing a set of codes or a set of functions which can be
included to an application. A module could be a file containing a single
variable, a function or a big code base.
Creating a Module
To create a module we write our codes in a python script and we save it as
a .py file. Create a file named [Link] inside your project folder. Let us
write some code in this file.
# [Link] file
def generate_full_name(firstname, lastname):
return firstname + ' ' + lastname
Create [Link] file in your project directory and import the [Link]
file.
Importing a Module
To import the file we use the import keyword and the name of the file only.
# [Link] file
import mymodule
print(mymodule.generate_full_name('Asabeneh', 'Yetayeh')) # Asabeneh Yetayeh
# [Link] file
from mymodule import generate_full_name, sum_two_nums, person, gravity
print(generate_full_name('Asabneh','Yetayeh'))
print(sum_two_nums(1,9))
mass = 100;
weight = mass * gravity
print(weight)
print(person['firstname'])
# [Link] file
from mymodule import generate_full_name as fullname, sum_two_nums as total,
person as p, gravity as g
print(fullname('Asabneh','Yetayeh'))
print(total(1, 9))
mass = 100;
weight = mass * g
print(weight)
print(p)
print(p['firstname'])
OS Module
Using python os module it is possible to automatically perform many
operating system tasks. The OS module in Python provides functions for
creating, changing current working directory, and removing a directory
(folder), fetching its contents, changing and identifying the current directory.
Sys Module
The sys module provides functions and variables used to manipulate
different parts of the Python runtime environment. Function [Link] returns
a list of command line arguments passed to a Python script. The item at
index 0 in this list is always the name of the script, at index 1 is the
argument passed from the command line.
import sys
#print([Link][0], argv[1],[Link][2]) # this line would print out:
filename argument1 argument2
print('Welcome {}. Enjoy {} challenge!'.format([Link][1], [Link][2]))
The result:
# to exit sys
[Link]()
# To know the largest integer variable it takes
[Link]
# To know environment path
[Link]
# To know the version of python you are using
[Link]
Statistics Module
The statistics module provides functions for mathematical statistics of
numeric data. The popular statistical functions which are defined in this
module: mean, median, mode, stdev etc.
Math Module
Module containing many mathematical operations and constants.
import math
print([Link]) # 3.141592653589793, pi constant
print([Link](2)) # 1.4142135623730951, square root
print([Link](2, 3)) # 8.0, exponential function
print([Link](9.81)) # 9, rounding to the lowest
print([Link](9.81)) # 10, rounding to the highest
print(math.log10(100)) # 2, logarithm with 10 as base
Now, we have imported the math module which contains lots of function
which can help us to perform mathematical calculations. To check what
functions the module has got, we can use help(math), or dir(math). This will
display the available functions in the module. If we want to import only a
specific function from the module we import it as follows:
But if we want to import all the function in math module we can use * .
import string
print(string.ascii_letters) #
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
print([Link]) # 0123456789
print([Link]) # !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
Random Module
By now you are familiar with importing modules. Let us do one more import
to get very familiar with it. Let us import random module which gives us a
random number between 0 and 0.9999.... The random module has lots of
functions but in this section we will only use random and randint.
🌕 You are going far. Keep going! You have just completed day 12 challenges
and you are 12 steps a head in to your way to greatness. Now do some
exercises for your brain and muscles.
[Link]
print(fullname('Asabneh','Yetayeh'))
print(total(1, 9))
mass = 100;
weight = mass * g
print(weight)
print(p)
print(p['firstname']
My [Link]
return fullname
gravity = 9.81
person = {
"firstname": "Asabeneh",
"age": 250,
"country": "Finland",
"city":'Helsinki'
List Comprehension
List comprehension in Python is a compact way of creating a list from a
sequence. It is a short way to create a new list. List comprehension is
considerably faster than processing a list using the for loop.
# syntax
[i for i in iterable if expression]
Example:1
For instance if you want to change a string to a list of characters. You can
use a couple of methods. Let's see some of them:
# One way
language = 'Python'
lst = list(language) # changing the string to list
print(type(lst)) # list
print(lst) # ['P', 'y', 't', 'h', 'o', 'n']
Example:2
# Generating numbers
numbers = [i for i in range(11)] # to generate numbers from 0 to 10
print(numbers) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Example:2
Lambda Function
Lambda function is a small anonymous function without a name. It can take
any number of arguments, but can only have one expression. Lambda
function is similar to anonymous functions in JavaScript. We need it when we
want to write an anonymous function inside another function.
# syntax
x = lambda param1, param2, param3: param1 + param2 + param2
print(x(arg1, arg2, arg3))
Example:
# Named function
def add_two_nums(a, b):
return a + b
print(add_two_nums(2, 3)) # 5
# Lets change the above function to a lambda function
add_two_nums = lambda a, b: a + b
print(add_two_nums(2,3)) # 5
square = lambda x : x ** 2
print(square(3)) # 9
cube = lambda x : x ** 3
print(cube(3)) # 27
# Multiple variables
multiple_variable = lambda a, b, c: a ** 2 - 3 * b + 4 * c
print(multiple_variable(5, 5, 3)) # 22
def power(x):
return lambda n : x ** n
💻 Exercises: Day 13
1. Filter only negative and zero in the list using list comprehension
7. [(0, 1, 0, 0, 0, 0, 0),
8. (1, 1, 1, 1, 1, 1, 1),
9. (2, 1, 2, 4, 8, 16, 32),
10. (3, 1, 3, 9, 27, 81, 243),
11. (4, 1, 4, 16, 64, 256, 1024),
12. (5, 1, 5, 25, 125, 625, 3125),
13. (6, 1, 6, 36, 216, 1296, 7776),
14. (7, 1, 7, 49, 343, 2401, 16807),
15. (8, 1, 8, 64, 512, 4096, 32768),
16. (9, 1, 9, 81, 729, 6561, 59049),
(10, 1, 10, 100, 1000, 10000, 100000)]
Function as a Parameter
def sum_numbers(nums): # normal function
return sum(nums) # a sad function abusing the built-in sum function :<
result = higher_order_function('square')
print(result(3)) # 9
result = higher_order_function('cube')
print(result(3)) # 27
result = higher_order_function('absolute')
print(result(-3)) # 3
You can see from the above example that the higher order function is
returning different functions depending on the passed parameter
Python Closures
Python allows a nested function to access the outer scope of the enclosing
function. This is is known as a Closure. Let us have a look at how closures
work in Python. In Python, closure is created by nesting a function inside
another encapsulating function and then returning the inner function. See
the example below.
Example:
def add_ten():
ten = 10
def add(num):
return num + ten
return add
closure_result = add_ten()
print(closure_result(5)) # 15
print(closure_result(10)) # 20
Python Decorators
A decorator is a design pattern in Python that allows a user to add new
functionality to an existing object without modifying its structure. Decorators
are usually called before the definition of a function you want to decorate.
Creating Decorators
To create a decorator function, we need an outer function with an inner
wrapper function.
Example:
# Normal function
def greeting():
return 'Welcome to Python'
def uppercase_decorator(function):
def wrapper():
func = function()
make_uppercase = [Link]()
return make_uppercase
return wrapper
g = uppercase_decorator(greeting)
print(g()) # WELCOME TO PYTHON
# First Decorator
def uppercase_decorator(function):
def wrapper():
func = function()
make_uppercase = [Link]()
return make_uppercase
return wrapper
# Second decorator
def split_string_decorator(function):
def wrapper():
func = function()
splitted_string = [Link]()
return splitted_string
return wrapper
@split_string_decorator
@uppercase_decorator # order with decorators is important in this case
- .upper() function does not work with lists
def greeting():
return 'Welcome to Python'
print(greeting()) # WELCOME TO PYTHON
def decorator_with_parameters(function):
def wrapper_accepting_parameters(para1, para2, para3):
function(para1, para2, para3)
print("I live in {}".format(para3))
return wrapper_accepting_parameters
@decorator_with_parameters
def print_full_name(first_name, last_name, country):
print("I am {} {}. I love to teach.".format(
first_name, last_name, country))
print_full_name("Asabeneh", "Yetayeh",'Finland')
# syntax
map(function, iterable)
Example:1
Example:2
Example:3
def change_to_upper(name):
return [Link]()
What actually map does is iterating over a list. For instance, it changes the
names to upper case and returns a new list.
# syntax
filter(function, iterable)
Example:1
def is_even(num):
if num % 2 == 0:
return True
return False
Example:2
def is_odd(num):
if num % 2 != 0:
return True
return False
💻 Exercises: Day 14
countries = ['Estonia', 'Finland', 'Sweden', 'Denmark', 'Norway', 'Iceland']
names = ['Asabeneh', 'Lidiya', 'Ermias', 'Abraham']
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Exercises: Level 1
1. Explain the difference between map, filter, and reduce.
2. Explain the difference between higher order function, closure and
decorator
3. Define a call function before map, filter or reduce, see examples.
4. Use for loop to print each country in the countries list.
5. Use for to print each name in the names list.
6. Use for to print each number in the numbers list.
Exercises: Level 2
1. Use map to create a new list by changing each country to uppercase in
the countries list
2. Use map to create a new list by changing each number to its square in
the numbers list
3. Use map to change each name to uppercase in the names list
4. Use filter to filter out countries containing 'land'.
5. Use filter to filter out countries having exactly six characters.
6. Use filter to filter out countries containing six letters and more in the
country list.
7. Use filter to filter out countries starting with an 'E'
8. Chain two or more list iterators (eg.
[Link](callback).filter(callback).reduce(callback))
9. Declare a function called get_string_lists which takes a list as a
parameter and then returns a list containing only string items.
10. Use reduce to sum all the numbers in the numbers list.
11. Use reduce to concatenate all the countries and to produce this
sentence: Estonia, Finland, Sweden, Denmark, Norway, and Iceland are
north European countries
12. Declare a function called categorize_countries that returns a list
of countries with some common pattern (you can find the countries
list in this repository as [Link](eg 'land', 'ia', 'island', 'stan')).
13. Create a function returning a dictionary, where keys stand for
starting letters of countries and values are the number of country
names starting with that letter.
14. Declare a get_first_ten_countries function - it returns a list of first
ten countries from the [Link] list in the data folder.
15. Declare a get_last_ten_countries function that returns the last
ten countries in the countries list.
SyntaxError
Example 1: SyntaxError
asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print 'hello world'
File "<stdin>", line 1
print 'hello world'
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean
print('hello world')?
>>>
As you can see we made a syntax error because we forgot to enclose the
string with parenthesis and Python already suggests the solution. Let us fix
it.
asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print 'hello world'
File "<stdin>", line 1
print 'hello world'
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean
print('hello world')?
>>> print('hello world')
hello world
>>>
The error was a SyntaxError. After the fix our code was executed without a
hitch. Let see more error types.
NameError
Example 1: NameError
asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print(age)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'age' is not defined
>>>
As you can see from the message above, name age is not defined. Yes, it is
true that we did not define an age variable but we were trying to print it out
as if we had had declared it. Now, lets fix this by declaring it and assigning
with a value.
asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print(age)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'age' is not defined
>>> age = 25
>>> print(age)
25
>>>
The type of error was a NameError. We debugged the error by defining the
variable name.
IndexError
Example 1: IndexError
asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> numbers = [1, 2, 3, 4, 5]
>>> numbers[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>>
In the example above, Python raised an IndexError, because the list has only
indexes from 0 to 4 , so it was out of range.
ModuleNotFoundError
Example 1: ModuleNotFoundError
asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import maths
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'maths'
>>>
asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import maths
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'maths'
>>> import math
>>>
We fixed it, so let's use some of the functions from the math module.
AttributeError
Example 1: AttributeError
asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import maths
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'maths'
>>> import math
>>> [Link]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'math' has no attribute 'PI'
>>>
As you can see, I made a mistake again! Instead of pi, I tried to call a PI
function from maths module. It raised an attribute error, it means, that the
function does not exist in the module. Lets fix it by changing from PI to pi.
asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import maths
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'maths'
>>> import math
>>> [Link]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'math' has no attribute 'PI'
>>> [Link]
3.141592653589793
>>>
Now, when we call pi from the math module we got the result.
KeyError
Example 1: KeyError
asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> users = {'name':'Asab', 'age':250, 'country':'Finland'}
>>> users['name']
'Asab'
>>> users['county']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'county'
>>>
As you can see, there was a typo in the key used to get the dictionary value.
so, this is a key error and the fix is quite straight forward. Let's do this!
asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> user = {'name':'Asab', 'age':250, 'country':'Finland'}
>>> user['name']
'Asab'
>>> user['county']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'county'
>>> user['country']
'Finland'
>>>
We debugged the error, our code ran and we got the value.
TypeError
Example 1: TypeError
asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 4 + '3'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>
asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 4 + '3'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> 4 + int('3')
7
>>> 4 + float('3')
7.0
>>>
ImportError
Example 1: TypeError
asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from math import power
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'power' from 'math'
>>>
There is no function called power in the math module, it goes with a different
name: pow. Let's correct it:
asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from math import power
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'power' from 'math'
>>> from math import pow
>>> pow(2,3)
8.0
>>>
ValueError
asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> int('12a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '12a'
>>>
In this case we cannot change the given string to a number, because of the
'a' letter in it.
ZeroDivisionError
asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 1/0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>>
We have covered some of the python error types, if you want to check more
about it check the python documentation about python error types. If you
are good at reading the error types then you will be able to fix your bugs fast
and you will also become a better programmer.
🌕 You are excelling. You made it to half way to your way to greatness. Now
do some exercises for your brain and for your muscle.
Python datetime
Python has got datetime module to handle date and time.
import datetime
print(dir(datetime))
['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__',
'__loader__', '__name__', '__package__', '__spec__', 'date', 'datetime',
'datetime_CAPI', 'sys', 'time', 'timedelta', 'timezone', 'tzinfo']
Formatting date time using strftime method and the documentation can be
found here.
Here are all the strftime symbols we use to format time. An example of all
the formats for this module.
String to Time Using strptime
Here is a documentation hat helps to understand the format.
output
a = 00:00:00
b = 10:30:50
c = 10:30:50
d = 10:30:50.200555
Exception Handling
Python uses try and except to handle errors gracefully. A graceful exit (or
graceful handling) of errors is a simple programming idiom - a program
detects a serious error condition and "exits gracefully", in a controlled
manner as a result. Often the program prints a descriptive error message to
a terminal or log as part of the graceful exit, this makes our application more
robust. The cause of an exception is often external to the program itself. An
example of exceptions could be an incorrect input, wrong file name, unable
to find a file, a malfunctioning IO device. Graceful handling of errors prevents
our applications from crashing.
We have covered the different Python error types in the previous section. If
we use try and except in our program, then it will not raise errors in those
blocks.
try:
code in this block if things go well
except:
code in this block run if things go wrong
Example:
try:
print(10 + '5')
except:
print('Something went wrong')
In the example above the second operand is a string. We could change it to
float or int to add it with the number to make it work. But without any
changes, the second block, except, will be executed.
Example:
try:
name = input('Enter your name:')
year_born = input('Year you were born:')
age = 2019 - year_born
print(f'You are {name}. And your age is {age}.')
except:
print('Something went wrong')
Something went wrong
In the above example, the exception block will run and we do not know
exactly the problem. To analyze the problem, we can use the different error
types with except.
In the following example, it will handle the error and will also tell us the kind
of error raised.
try:
name = input('Enter your name:')
year_born = input('Year you were born:')
age = 2019 - year_born
print(f'You are {name}. And your age is {age}.')
except TypeError:
print('Type error occured')
except ValueError:
print('Value error occured')
except ZeroDivisionError:
print('zero division error occured')
Enter your name:Asabeneh
Year you born:1920
Type error occured
In the code above the output is going to be TypeError. Now, let's add an
additional block:
try:
name = input('Enter your name:')
year_born = input('Year you born:')
age = 2019 - int(year_born)
print(f'You are {name}. And your age is {age}.')
except TypeError:
print('Type error occur')
except ValueError:
print('Value error occur')
except ZeroDivisionError:
print('zero division error occur')
else:
print('I usually run with the try block')
finally:
print('I alway run.')
Enter your name:Asabeneh
Year you born:1920
You are Asabeneh. And your age is 99.
I usually run with the try block
I alway run.
try:
name = input('Enter your name:')
year_born = input('Year you born:')
age = 2019 - int(year_born)
print(f'You are {name}. And your age is {age}.')
except Exception as e:
print(e)
* for tuples
** for dictionaries
Let us take as an example below. It takes only arguments but we have list.
We can unpack the list and changes to argument.
Unpacking
Unpacking Lists
lst = [1, 2, 3, 4, 5]
print(sum_of_five_nums(lst)) # TypeError: sum_of_five_nums() missing 4
required positional arguments: 'b', 'c', 'd', and 'e'
When we run the this code, it raises an error, because this function takes
numbers (not a list) as arguments. Let us unpack/destructure the list.
lst = [1, 2, 3, 4, 5]
print(sum_of_five_nums(*lst)) # 15
We can also use unpacking in the range built-in function that expects a start
and an end.
Unpacking Dictionaries
Packing
Sometimes we never know how many arguments need to be passed to a
python function. We can use the packing method to allow our function to
take unlimited number or arbitrary number of arguments.
Packing Lists
def sum_all(*args):
s = 0
for i in args:
s += i
return s
print(sum_all(1, 2, 3)) # 6
print(sum_all(1, 2, 3, 4, 5, 6, 7)) # 28
Packing Dictionaries
def packing_person_info(**kwargs):
# check the type of kwargs and it is a dict type
# print(type(kwargs))
# Printing dictionary items
for key in kwargs:
print(f"{key} = {kwargs[key]}")
return kwargs
print(packing_person_info(name="Asabeneh",
country="Finland", city="Helsinki", age=250))
name = Asabeneh
country = Finland
city = Helsinki
age = 250
{'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250}
Spreading in Python
Like in JavaScript, spreading is possible in Python. Let us check it in an
example below:
lst_one = [1, 2, 3]
lst_two = [4, 5, 6, 7]
lst = [0, *lst_one, *lst_two]
print(lst) # [0, 1, 2, 3, 4, 5, 6, 7]
country_lst_one = ['Finland', 'Sweden', 'Norway']
country_lst_two = ['Denmark', 'Iceland']
nordic_countries = [*country_lst_one, *country_lst_two]
print(nordic_countries) # ['Finland', 'Sweden', 'Norway', 'Denmark',
'Iceland']
Enumerate
If we are interested in an index of a list, we use enumerate built-in function
to get the index of each item in the list.
Zip
Sometimes we would like to combine lists when looping through them. See
the example below:
🌕 You are determined. You are 17 steps a head to your way to greatness.
Now do some exercises for your brain and mus
Regular Expressions
A regular expression or RegEx is a special text string that helps to find
patterns in data. A RegEx can be used to check if some pattern exists in a
different data type. To use RegEx in python first we should import the RegEx
module which is called re.
The re Module
After importing the module we can use it to detect or find patterns.
import re
Methods in re Module
To find a pattern we use different set of re character sets that allows to
search for a match in a string.
[Link](): searches only in the beginning of the first line of the string
and returns matched objects if found, else returns None.
[Link]: Returns a match object if there is one anywhere in the
string, including multiline strings.
[Link]: Returns a list containing all matches
[Link]: Takes a string, splits it at the match points, returns a list
[Link]: Replaces one or many matches within a string
Match
# syntac
[Link](substring, string, re.I)
# substring is a string or a pattern, string is the text we look for a
pattern , re.I is case ignore
import re
As you can see from the example above, the pattern we are looking for (or
the substring we are looking for) is I love to teach. The match function
returns an object only if the text starts with the pattern.
import re
The string does not string with I like to teach, therefore there was no match
and the match method returned None.
Search
# syntax
[Link](substring, string, re.I)
# substring is a pattern, string is the text we look for a pattern , re.I is
case ignore flag
import re
txt = '''Python is the most beautiful language that a human being has ever
created.
I recommend python for a first programming language'''
As you can see, search is much better than match because it can look for the
pattern throughout the text. Search returns a match object with a first match
that was found, otherwise it returns None. A much better re function
is findall. This function checks for the pattern through the whole string and
returns all the matches as a list.
txt = '''Python is the most beautiful language that a human being has ever
created.
I recommend python for a first programming language'''
# It return a list
matches = [Link]('language', txt, re.I)
print(matches) # ['language', 'language']
As you can see, the word language was found two times in the string. Let us
practice some more. Now we will look for both Python and python words in
the string:
txt = '''Python is the most beautiful language that a human being has ever
created.
I recommend python for a first programming language'''
# It returns list
matches = [Link]('python', txt, re.I)
print(matches) # ['Python', 'python']
Since we are using re.I both lowercase and uppercase letters are included. If
we do not have the re.I flag, then we will have to write our pattern
differently. Let us check it out:
txt = '''Python is the most beautiful language that a human being has ever
created.
I recommend python for a first programming language'''
#
matches = [Link]('[Pp]ython', txt)
print(matches) # ['Python', 'python']
Replacing a Substring
txt = '''Python is the most beautiful language that a human being has ever
created.
I recommend python for a first programming language'''
Let us add one more example. The following string is really hard to read
unless we remove the % symbol. Replacing the % with an empty string will
clean the text.
import re
regex_pattern = r'apple'
txt = 'Apple and banana are fruits. An old cliche says an apple a day a
doctor way has been replaced by a banana a day keeps the doctor far far away.
'
matches = [Link](regex_pattern, txt)
print(matches) # ['apple']
Square Bracket
Let us use square bracket to include lower and upper case
Period(.)
regex_pattern = r'[a].' # this square bracket means a and . means any
character except new line
txt = '''Apple and banana are fruits'''
matches = [Link](regex_pattern, txt)
print(matches) # ['an', 'an', 'an', 'a ', 'ar']
txt = '''I am not sure if there is a convention how to write the word e-mail.
Some people write it as email others may write it as Email or E-mail.'''
regex_pattern = r'[Ee]-?mail' # ? means here that '-' is optional
matches = [Link](regex_pattern, txt)
print(matches) # ['e-mail', 'email', 'Email', 'E-mail']
Quantifier in RegEx
We can specify the length of the substring we are looking for in a text, using
a curly bracket. Let us imagine, we are interested in a substring with a length
of 4 characters:
txt = 'This regular expression example was made on December 6, 2019 and
revised on July 8, 2021'
regex_pattern = r'\d{4}' # exactly four times
matches = [Link](regex_pattern, txt)
print(matches) # ['2019', '2021']
txt = 'This regular expression example was made on December 6, 2019 and
revised on July 8, 2021'
regex_pattern = r'\d{1, 4}' # 1 to 4
matches = [Link](regex_pattern, txt)
print(matches) # ['6', '2019', '8', '2021']
Cart ^
Starts with
txt = 'This regular expression example was made on December 6, 2019 and
revised on July 8, 2021'
regex_pattern = r'^This' # ^ means starts with
matches = [Link](regex_pattern, txt)
print(matches) # ['This']
Negation
txt = 'This regular expression example was made on December 6, 2019 and
revised on July 8, 2021'
regex_pattern = r'[^A-Za-z ]+' # ^ in set character means negation, not A to
Z, not a to z, no space
matches = [Link](regex_pattern, txt)
File Handling
So far we have seen different Python data types. We usually store our data in
different file formats. In addition to handling files, we will also see different
file formats(.txt, .json, .xml, .csv, .tsv, .excel) in this section. First, let us get
familiar with handling files with common file format(.txt).
# Syntax
open('filename', mode) # mode(r, a, w, x, t,b) could be to read, write,
update
"r" - Read - Default value. Opens a file for reading, it returns an error if
the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not
exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
"t" - Text - Default value. Text mode
"b" - Binary - Binary mode (e.g. images)
f = open('./files/reading_file_example.txt')
print(f) # <_io.TextIOWrapper name='./files/reading_file_example.txt'
mode='r' encoding='UTF-8'>
As you can see in the example above, I printed the opened file and it gave
some information about it. Opened file has different reading
methods: read(), readline, readlines. An opened file has to be closed
with close() method.
read(): read the whole text as string. If we want to limit the number of
characters we want to read, we can limit it by passing int value to
the read(number) method.
f = open('./files/reading_file_example.txt')
txt = [Link]()
print(type(txt))
print(txt)
[Link]()
# output
<class 'str'>
This is an example to show how to open a file and read.
This is the second line of the text.
Instead of printing all the text, let us print the first 10 characters of the text
file.
f = open('./files/reading_file_example.txt')
txt = [Link](10)
print(type(txt))
print(txt)
[Link]()
# output
<class 'str'>
This is an
f = open('./files/reading_file_example.txt')
line = [Link]()
print(type(line))
print(line)
[Link]()
# output
<class 'str'>
This is an example to show how to open a file and read.
readlines(): read all the text line by line and returns a list of lines
f = open('./files/reading_file_example.txt')
lines = [Link]()
print(type(lines))
print(lines)
[Link]()
# output
<class 'list'>
['This is an example to show how to open a file and read.\n', 'This is the
second line of the text.']
f = open('./files/reading_file_example.txt')
lines = [Link]().splitlines()
print(type(lines))
print(lines)
[Link]()
# output
<class 'list'>
['This is an example to show how to open a file and read.', 'This is the
second line of the text.']
After we open a file, we should close it. There is a high tendency of forgetting
to close them. There is a new way of opening files using with - closes the
files by itself. Let us rewrite the the previous example with the with method:
with open('./files/reading_file_example.txt') as f:
lines = [Link]().splitlines()
print(type(lines))
print(lines)
# output
<class 'list'>
['This is an example to show how to open a file and read.', 'This is the
second line of the text.']
"a" - append - will append to the end of the file, if the file does not it
creates a new file.
"w" - write - will overwrite any existing content, if the file does not exist
it creates.
with open('./files/reading_file_example.txt','a') as f:
[Link]('This text has to be appended at the end')
The method below creates a new file, if the file does not exist:
with open('./files/writing_file_example.txt','w') as f:
[Link]('This text will be written in a newly created file')
Deleting Files
We have seen in previous section, how to make and remove a directory
using os module. Again now, if we want to remove a file we use os module.
import os
[Link]('./files/[Link]')
If the file does not exist, the remove method will raise an error, so it is good
to use a condition like this:
import os
if [Link]('./files/[Link]'):
[Link]('./files/[Link]')
else:
print('The file does not exist')
File Types
Example:
# dictionary
person_dct= {
"name":"Asabeneh",
"country":"Finland",
"city":"Helsinki",
"skills":["JavaScrip", "React","Python"]
}
# JSON: A string form a dictionary
person_json = "{'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki',
'skills': ['JavaScrip', 'React', 'Python']}"
# we use three quotes and make it multiple line to make it more readable
person_json = '''{
"name":"Asabeneh",
"country":"Finland",
"city":"Helsinki",
"skills":["JavaScrip", "React","Python"]
}'''
import json
# JSON
person_json = '''{
"name": "Asabeneh",
"country": "Finland",
"city": "Helsinki",
"skills": ["JavaScrip", "React", "Python"]
}'''
# let's change JSON to dictionary
person_dct = [Link](person_json)
print(type(person_dct))
print(person_dct)
print(person_dct['name'])
# output
<class 'dict'>
{'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'skills':
['JavaScrip', 'React', 'Python']}
Asabeneh
import json
# python dictionary
person = {
"name": "Asabeneh",
"country": "Finland",
"city": "Helsinki",
"skills": ["JavaScrip", "React", "Python"]
}
# let's convert it to json
person_json = [Link](person, indent=4) # indent could be 2, 4, 8. It
beautifies the json
print(type(person_json))
print(person_json)
# output
# when you print it, it does not have the quote, but actually it is a string
# JSON does not have type, it is a string type.
<class 'str'>
{
"name": "Asabeneh",
"country": "Finland",
"city": "Helsinki",
"skills": [
"JavaScrip",
"React",
"Python"
]
}
import json
# python dictionary
person = {
"name": "Asabeneh",
"country": "Finland",
"city": "Helsinki",
"skills": ["JavaScrip", "React", "Python"]
}
with open('./files/json_example.json', 'w', encoding='utf-8') as f:
[Link](person, f, ensure_ascii=False, indent=4)
In the code above, we use encoding and indentation. Indentation makes the
json file easy to read.
Example:
"name","country","city","skills"
"Asabeneh","Finland","Helsinki","JavaScript"
Example:
import csv
with open('./files/csv_example.csv') as f:
csv_reader = [Link](f, delimiter=',') # w use, reader method to read
csv
line_count = 0
for row in csv_reader:
if line_count == 0:
print(f'Column names are :{", ".join(row)}')
line_count += 1
else:
print(
f'\t{row[0]} is a teachers. He lives in {row[1]}, {row[2]}.')
line_count += 1
print(f'Number of lines: {line_count}')
# output:
Column names are :name, country, city, skills
Asabeneh is a teacher. He lives in Finland, Helsinki.
Number of lines: 2
import xlrd
excel_book = xlrd.open_workbook('[Link])
print(excel_book.nsheets)
print(excel_book.sheet_names)
File with xml Extension
XML is another structured data format which looks like HTML. In XML the tags
are not predefined. The first line is an XML declaration. The person tag is the
root of the XML. The person has a gender attribute. Example:XML
<?xml version="1.0"?>
<person gender="female">
<name>Asabeneh</name>
<country>Finland</country>
<city>Helsinki</city>
<skills>
<skill>JavaScrip</skill>
<skill>React</skill>
<skill>Python</skill>
</skills>
</person>
For more information on how to read an XML file check the documentation
import [Link] as ET
tree = [Link]('./files/xml_example.xml')
root = [Link]()
print('Root tag:', [Link])
print('Attribute:', [Link])
for child in root:
print('field: ', [Link])
# output
Root tag: person
Attribute: {'gender': 'male'}
field: name
field: country
field: city
field: skills
🌕 You are making a big progress. Maintain your momentum, keep the good
work. Now do some exercises for your brain and muscles.
💻 Exercises: Day 19
Exercises: Level 1
1. Write a function which count number of lines and number of words in a
text. All the files are in the data the folder: a) Read obama_speech.txt
file and count number of lines and words b) Read
michelle_obama_speech.txt file and count number of lines and words
c) Read donald_speech.txt file and count number of lines and words d)
Read melina_trump_speech.txt file and count number of lines and
words
2. Read the countries_data.json data file in data directory, create a
function that finds the ten most spoken languages
[(10, 'the'),
(8, 'be'),
(6, 'to'),
(6, 'of'),
(5, 'and')]
What is PIP ?
PIP stands for Preferred installer program. We use pip to install different
Python packages. Package is a Python module that can contain one or more
modules or other packages. A module or modules that we can install to our
application is a package. In programming, we do not have to write every
utility program, instead we install packages and import them to our
applications.
Installing PIP
If you did not install pip, let us install it now. Go to your terminal or command
prompt and copy and paste this:
pip --version
asabeneh@Asabeneh:~$ pip --version
pip 21.1.3 from /usr/local/lib/python3.7/site-packages/pip (python 3.9.6)
As you can see, I am using pip version 21.1.3, if you see some number a bit
below or above that, means you have pip installed.
Let us check some of the packages used in the Python community for
different purposes. Just to let you know that there are lots of packages
available for use with different applications.
Let us start using numpy. Open your python interactive shell, write python
and then import numpy as follows:
asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>> [Link]
'1.20.1'
>>> lst = [1, 2, 3,4, 5]
>>> np_arr = [Link](lst)
>>> np_arr
array([1, 2, 3, 4, 5])
>>> len(np_arr)
5
>>> np_arr * 2
array([ 2, 4, 6, 8, 10])
>>> np_arr + 2
array([3, 4, 5, 6, 7])
>>>
This section is not about numpy nor pandas, here we are trying to learn how
to install packages and how to import them. If it is needed, we will talk about
different packages in other sections.
Let us import a web browser module, which can help us to open any website.
We do not need to install this module, it is already installed by default with
Python 3. For instance if you like to open any number of websites at any time
or if you like to schedule something, this webbrowser module can be used.
Uninstalling Packages
If you do not like to keep the installed packages, you can remove them using
the following command.
List of Packages
To see the installed packages on our machine. We can use pip followed by
list.
pip list
Show Package
To show information about a package
PIP Freeze
Generate installed Python packages with their version and the output is
suitable to use it in a requirements file. A [Link] file is a file that
should contain all the installed Python packages in a Python project.
The pip freeze gave us the packages used, installed and their version. We
use it with [Link] file for deployment.
get(): to open a network and fetch data from url - it returns a response
object
status_code: After we fetched data, we can check the status of the
operation (success, error, etc)
headers: To check the header types
text: to extract the text from the fetched response object
json: to extract json data Let's read a txt file from this
website, [Link]
Let us read from an API. API stands for Application Program Interface. It
is a means to exchange structure data between servers primarily a
json data. An example of an API:[Link] Let
us read this API using requests module.
import requests
url = '[Link] # countries api
response = [Link](url) # opening a network and fetching a data
print(response) # response object
print(response.status_code) # status code, success:200
countries = [Link]()
print(countries[:1]) # we sliced only the first country, remove the slicing
to see all countries
<Response [200]>
200
[{'alpha2Code': 'AF',
'alpha3Code': 'AFG',
'altSpellings': ['AF', 'Afġānistān'],
'area': 652230.0,
'borders': ['IRN', 'PAK', 'TKM', 'UZB', 'TJK', 'CHN'],
'callingCodes': ['93'],
'capital': 'Kabul',
'cioc': 'AFG',
'currencies': [{'code': 'AFN', 'name': 'Afghan afghani', 'symbol': '؋'}],
'demonym': 'Afghan',
'flag': '[Link]
'gini': 27.8,
'languages': [{'iso639_1': 'ps',
'iso639_2': 'pus',
'name': 'Pashto',
'nativeName': '}'پښتو,
{'iso639_1': 'uz',
'iso639_2': 'uzb',
'name': 'Uzbek',
'nativeName': 'Oʻzbek'},
{'iso639_1': 'tk',
'iso639_2': 'tuk',
'name': 'Turkmen',
'nativeName': 'Türkmen'}],
'latlng': [33.0, 65.0],
'name': 'Afghanistan',
'nativeName': ''افغانستان,
'numericCode': '004',
'population': 27657145,
'region': 'Asia',
'regionalBlocs': [{'acronym': 'SAARC',
'name': 'South Asian Association for Regional
Cooperation',
'otherAcronyms': [],
'otherNames': []}],
'subregion': 'Southern Asia',
'timezones': ['UTC+04:30'],
'topLevelDomain': ['.af'],
'translations': {'br': 'Afeganistão',
'de': 'Afghanistan',
'es': 'Afganistán',
'fa': ''افغانستان,
'fr': 'Afghanistan',
'hr': 'Afganistan',
'it': 'Afghanistan',
'ja': 'アフガニスタン',
'nl': 'Afghanistan',
'pt': 'Afeganistão'}}]
We use json() method from response object, if the we are fetching JSON data.
For txt, html, xml and other file formats we can use text.
Creating a Package
We organize a large number of files in different folders and sub-folders based
on some criteria, so that we can find and manage them easily. As you know,
a module can contain multiple objects, such as classes, functions, etc. A
package can contain one or more relevant modules. A package is actually a
folder containing one or more module files. Let us create a package named
mypackage, using the following steps:
# mypackage/[Link]
# [Link]
def add_numbers(*args):
total = 0
for num in args:
total += num
return total
─ mypackage
├── __init__.py
├── [Link]
└── [Link]
Now let's open the python interactive shell and try the package we have
created:
asabeneh@Asabeneh:~/Desktop/30DaysOfPython$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from mypackage import arithmetics
>>> arithmetics.add_numbers(1, 2, 3, 5)
11
>>> [Link](5, 3)
2
>>> [Link](5, 3)
15
>>> [Link](5, 3)
1.6666666666666667
>>> [Link](5, 3)
2
>>> [Link](5, 3)
125
>>> from mypackage import greet
>>> greet.greet_person('Asabeneh', 'Yetayeh')
'Asabeneh Yetayeh, welcome to 30DaysOfPython Challenge!'
>>>
As you can see our package works perfectly. The package folder contains a
special file called [Link] - it stores the package's content. If we put [Link] in
the package folder, python start recognizes it as a package. The [Link]
exposes specified resources from its modules to be imported to other python
files. An empty [Link] file makes all functions available when a package is
imported. The [Link] is essential for the folder to be recognized by Python
as a package.
XML Processing
Network:
[Link]
def add_numbers(*args):
total = 0
total += num
return total
return (a - b)
return a * b
return a / b
return a % b
return a ** b
[Link]
We have been working with classes and objects right from the beginning of
this challenge unknowingly. Every element in a Python program is an object
of a class. Let us check if everything in python is a class:
asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> num = 10
>>> type(num)
<class 'int'>
>>> string = 'string'
>>> type(string)
<class 'str'>
>>> boolean = True
>>> type(boolean)
<class 'bool'>
>>> lst = []
>>> type(lst)
<class 'list'>
>>> tpl = ()
>>> type(tpl)
<class 'tuple'>
>>> set1 = set()
>>> type(set1)
<class 'set'>
>>> dct = {}
>>> type(dct)
<class 'dict'>
Creating a Class
To create a class we need the key word class followed by the name and
colon. Class name should be CamelCase.
# syntax
class ClassName:
code goes here
Example:
class Person:
pass
print(Person)
<__main__.Person object at 0x10804e510>
Creating an Object
We can create an object by calling the class.
p = Person()
print(p)
Class Constructor
In the examples above, we have created an object from the Person class.
However, a class without a constructor is not really useful in real
applications. Let us use constructor function to make our class more useful.
Like the constructor function in Java or JavaScript, Python has also a built-
in init() constructor function. The init constructor function has self
parameter which is a reference to the current instance of the
class Examples:
class Person:
def __init__ (self, name):
# self allows to attach parameter to the class
[Link] =name
p = Person('Asabeneh')
print([Link])
print(p)
# output
Asabeneh
<__main__.Person object at 0x2abf46907e80>
class Person:
def __init__(self, firstname, lastname, age, country, city):
[Link] = firstname
[Link] = lastname
[Link] = age
[Link] = country
[Link] = city
Object Methods
Objects can have methods. The methods are functions which belong to the
object.
Example:
class Person:
def __init__(self, firstname, lastname, age, country, city):
[Link] = firstname
[Link] = lastname
[Link] = age
[Link] = country
[Link] = city
def person_info(self):
return f'{[Link]} {[Link]} is {[Link]} years old. He
lives in {[Link]}, {[Link]}'
Example:
class Person:
def __init__(self, firstname='Asabeneh', lastname='Yetayeh', age=250,
country='Finland', city='Helsinki'):
[Link] = firstname
[Link] = lastname
[Link] = age
[Link] = country
[Link] = city
def person_info(self):
return f'{[Link]} {[Link]} is {[Link]} years old. He
lives in {[Link]}, {[Link]}.'
p1 = Person()
print(p1.person_info())
p2 = Person('John', 'Doe', 30, 'Nomanland', 'Noman city')
print(p2.person_info())
# output
Asabeneh Yetayeh is 250 years old. He lives in Helsinki, Finland.
John Doe is 30 years old. He lives in Noman city, Nomanland.
class Person:
def __init__(self, firstname='Asabeneh', lastname='Yetayeh', age=250,
country='Finland', city='Helsinki'):
[Link] = firstname
[Link] = lastname
[Link] = age
[Link] = country
[Link] = city
[Link] = []
def person_info(self):
return f'{[Link]} {[Link]} is {[Link]} years old. He
lives in {[Link]}, {[Link]}.'
def add_skill(self, skill):
[Link](skill)
p1 = Person()
print(p1.person_info())
p1.add_skill('HTML')
p1.add_skill('CSS')
p1.add_skill('JavaScript')
p2 = Person('John', 'Doe', 30, 'Nomanland', 'Noman city')
print(p2.person_info())
print([Link])
print([Link])
# output
Asabeneh Yetayeh is 250 years old. He lives in Helsinki, Finland.
John Doe is 30 years old. He lives in Noman city, Nomanland.
['HTML', 'CSS', 'JavaScript']
[]
Inheritance
Using inheritance we can reuse parent class code. Inheritance allows us to
define a class that inherits all the methods and properties from parent class.
The parent class or super or base class is the class which gives all the
methods and properties. Child class is the class that inherits from another or
parent class. Let us create a student class by inheriting from person class.
class Student(Person):
pass
print(s2.person_info())
s2.add_skill('Organizing')
s2.add_skill('Marketing')
s2.add_skill('Digital Marketing')
print([Link])
output
Eyob Yetayeh is 30 years old. He lives in Helsinki, Finland.
['JavaScript', 'React', 'Python']
Lidiya Teklemariam is 28 years old. He lives in Espoo, Finland.
['Organizing', 'Marketing', 'Digital Marketing']
We did not call the init() constructor in the child class. If we didn't call it then
we can still access all the properties from the parent. But if we do call the
constructor we can access the parent properties by calling super.
We can add a new method to the child or we can override the parent class
methods by creating the same method name in the child class. When we add
the init() function, the child class will no longer inherit the parent's init()
function.
print(s2.person_info())
s2.add_skill('Organizing')
s2.add_skill('Marketing')
s2.add_skill('Digital Marketing')
print([Link])
Eyob Yetayeh is 30 years old. He lives in Helsinki, Finland.
['JavaScript', 'React', 'Python']
Lidiya Teklemariam is 28 years old. She lives in Espoo, Finland.
['Organizing', 'Marketing', 'Digital Marketing']
We can use super() built-in function or the parent name Person to
automatically inherit the methods and properties from its parent. In the
example above we override the parent method. The child method has a
different feature, it can identify, if the gender is male or female and assign
the proper pronoun(He/She).
🌕 Now, you are fully charged with a super power of programming. Now do
some exercises for your brain and muscles.
💻 Exercises: Day 21
Exercises: Level 1
1. Python has the module called statistics and we can use this module to
do all the statistical calculations. However, to learn how to make
function and reuse function let us try to develop a program, which
calculates the measure of central tendency of a sample (mean,
median, mode) and measure of variability (range, variance, standard
deviation). In addition to those measures, find the min, max, count,
percentile, and frequency distribution of the sample. You can create a
class called Statistics and create all the functions that do statistical
calculations as methods for the Statistics class. Check the output
below.
ages = [31, 26, 34, 37, 27, 26, 32, 32, 26, 27, 27, 24, 32, 33, 27, 25, 26,
38, 37, 31, 34, 24, 33, 29, 26]
print('Count:', [Link]()) # 25
print('Sum: ', [Link]()) # 744
print('Min: ', [Link]()) # 24
print('Max: ', [Link]()) # 38
print('Range: ', [Link]() # 14
print('Mean: ', [Link]()) # 30
print('Median: ', [Link]()) # 29
print('Mode: ', [Link]()) # {'mode': 26, 'count': 5}
print('Standard Deviation: ', [Link]()) # 4.2
print('Variance: ', [Link]()) # 17.5
print('Frequency Distribution: ', data.freq_dist()) # [(20.0, 26), (16.0,
27), (12.0, 32), (8.0, 37), (8.0, 34), (8.0, 33), (8.0, 31), (8.0, 24), (4.0,
38), (4.0, 29), (4.0, 25)]
# you output should look like this
print([Link]())
Count: 25
Sum: 744
Min: 24
Max: 38
Range: 14
Mean: 30
Median: 29
Mode: (26, 5)
Variance: 17.5
Standard Deviation: 4.2
Frequency Distribution: [(20.0, 26), (16.0, 27), (12.0, 32), (8.0, 37), (8.0,
34), (8.0, 33), (8.0, 31), (8.0, 24), (4.0, 38), (4.0, 29), (4.0, 25)]
Exercises: Level 2
1. Create a class called PersonAccount. It has firstname, lastname,
incomes, expenses properties and it has total_income, total_expense,
account_info, add_income, add_expense and account_balance
methods. Incomes is a set of incomes and its description. The same
goes for expenses.
Web scraping is the process of extracting and collecting data from websites
and storing it on a local machine or in a database.
To scrape data from websites, basic understanding of HTML tags and CSS
selectors is needed. We target content from a website using HTML tags,
classes or/and ids. Let us import the requests and BeautifulSoup module
import requests
from bs4 import BeautifulSoup
Let us declare url variable for the website which we are going to scrape.
import requests
from bs4 import BeautifulSoup
url = '[Link]
# Lets use the requests get method to fetch the data from url
response = [Link](url)
# lets check the status
status = response.status_code
print(status) # 200 means the fetching was successful
200
import requests
from bs4 import BeautifulSoup
url = '[Link]
response = [Link](url)
content = [Link] # we get all the content from the website
soup = BeautifulSoup(content, '[Link]') # beautiful soup will give a
chance to parse
print([Link]) # <title>UCI Machine Learning Repository: Data Sets</title>
print([Link].get_text()) # UCI Machine Learning Repository: Data Sets
print([Link]) # gives the whole page on the website
print(response.status_code)
If you run this code, you can see that the extraction is half done. You can
continue doing it because it is part of exercise 1. For reference check
the beautifulsoup documentation
🌕 You are so special, you are progressing everyday. You are left with only
eight days to your way to greatness. Now do some exercises for your brain
and muscles.
For Mac/Linux:
For Windows:
I prefer to call the new project venv, but feel free to name it differently. Let
us check if the the venv was created by using ls (or dir for windows
command prompt) command.
asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$ ls
venv/
For Mac/Linux:
asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$ source
venv/bin/activate
C:\Users\User\Documents\30DaysOfPython\flask_project> venv\Scripts\activate
After you write the activation command, your project directory will start with
venv. See the example below.
(venv) asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$
Now, lets check the available packages in this project by writing pip freeze.
You will not see any packages.
We are going to do a small flask project so let us install flask package to this
project.
Now, let us write pip freeze to see a list of installed packages in the project:
(venv) asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$ pip freeze
Click==7.0
Flask==1.1.1
itsdangerous==1.1.0
Jinja2==2.10.3
MarkupSafe==1.1.1
Werkzeug==0.16.0
When you finish you should dactivate active project using deactivate.
The necessary modules to work with flask are installed. Now, your project
directory is ready for a flask project. You should include the venv to
your .gitignore file not to push it to github.
💻 Exercises: Day 23
1. Create a project directory with a virtual environment based on the
example given above.
Statistics
Statistics is the discipline that studies
the collection, organization, displaying, analysing, interpretation and present
ation of data. Statistics is a branch of Mathematics that is recommended to
be a prerequisite for data science and machine learning. Statistics is a very
broad field but we will focus in this section only on the most relevant part.
After completing this challenge, you may go onto the web development, data
analysis, machine learning and data science path. Whatever path you may
follow, at some point in your career you will get data which you may work on.
Having some statistical knowledge will help you to make decisions based on
data, data tells as they say.
Data
What is data? Data is any set of characters that is gathered and translated
for some purpose, usually analysis. It can be any character, including text
and numbers, pictures, sound, or video. If data is not put in a context, it
doesn't make any sense to a human or computer. To make sense from data
we need to work on the data using different tools.
The work flow of data analysis, data science or machine learning starts from
data. Data can be provided from some data source or it can be created.
There are structured and unstructured data.
Data can be found in small or big format. Most of the data types we will get
have been covered in the file handling section.
Statistics Module
The Python statistics module provides functions for calculating mathematical
statistics of numerical data. The module is not intended to be a competitor to
third-party libraries such as NumPy, SciPy, or proprietary full-featured
statistics packages aimed at professional statisticians such as Minitab, SAS
and Matlab. It is aimed at the level of graphing and scientific calculators.
NumPy
In the first section we defined Python as a great general-purpose
programming language on its own, but with the help of other popular
libraries as(numpy, scipy, matplotlib, pandas etc) it becomes a powerful
environment for scientific computing.
So far, we have been using vscode but from now on I would recommend
using Jupyter Notebook. To access jupyter notebook let's install anaconda. If
you are using anaconda most of the common packages are included and you
don't have install packages if you installed anaconda.
Importing NumPy
Jupyter notebook is available if your are in favor of jupyter notebook
numpy_array_from_list = [Link](python_list)
print(type (numpy_array_from_list)) # <class '[Link]'>
print(numpy_array_from_list) # array([1, 2, 3, 4, 5])
# Python list
python_list = [1,2,3,4,5]
numpy_array_from_tuple = [Link](python_tuple)
print(type (numpy_array_from_tuple)) # <class '[Link]'>
print('numpy_array_from_tuple: ', numpy_array_from_tuple) #
numpy_array_from_tuple: [1 2 3 4 5]
print(int_array)
print(int_array.dtype)
print(float_array)
print(float_array.dtype)
[-3 -2 -1 0 1 2 3]
int64
[-3. -2. -1. 0. 1. 2. 3.]
float64
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
Modules (%)
Floor Division(//)
Exponential(**)
Addition
# Mathematical Operation
# Addition
numpy_array_from_list = [Link]([1, 2, 3, 4, 5])
print('original array: ', numpy_array_from_list)
ten_plus_original = numpy_array_from_list + 10
print(ten_plus_original)
original array: [1 2 3 4 5]
[11 12 13 14 15]
Subtraction
# Subtraction
numpy_array_from_list = [Link]([1, 2, 3, 4, 5])
print('original array: ', numpy_array_from_list)
ten_minus_original = numpy_array_from_list - 10
print(ten_minus_original)
original array: [1 2 3 4 5]
[-9 -8 -7 -6 -5]
Multiplication
# Multiplication
numpy_array_from_list = [Link]([1, 2, 3, 4, 5])
print('original array: ', numpy_array_from_list)
ten_times_original = numpy_array_from_list * 10
print(ten_times_original)
original array: [1 2 3 4 5]
[10 20 30 40 50]
Division
# Division
numpy_array_from_list = [Link]([1, 2, 3, 4, 5])
print('original array: ', numpy_array_from_list)
ten_times_original = numpy_array_from_list / 10
print(ten_times_original)
original array: [1 2 3 4 5]
[0.1 0.2 0.3 0.4 0.5]
Modulus
# Modulus; Finding the remainder
numpy_array_from_list = [Link]([1, 2, 3, 4, 5])
print('original array: ', numpy_array_from_list)
ten_times_original = numpy_array_from_list % 3
print(ten_times_original)
original array: [1 2 3 4 5]
[1 2 0 1 2]
Floor Division
# Floor division: the division result without the remainder
numpy_array_from_list = [Link]([1, 2, 3, 4, 5])
print('original array: ', numpy_array_from_list)
ten_times_original = numpy_array_from_list // 10
print(ten_times_original)
Exponential
# Exponential is finding some number the power of another:
numpy_array_from_list = [Link]([1, 2, 3, 4, 5])
print('original array: ', numpy_array_from_list)
ten_times_original = numpy_array_from_list ** 2
print(ten_times_original)
original array: [1 2 3 4 5]
[ 1 4 9 16 25]
print(numpy_int_arr.dtype)
print(numpy_float_arr.dtype)
print(numpy_bool_arr.dtype)
int64
float64
bool
Converting types
We can convert the data types of numpy array
1. Int to Float
2. Float to Int
numpy_int_arr = [Link]([1., 2., 3., 4.], dtype = 'int')
numpy_int_arr
array([1, 2, 3, 4])
3. Int ot boolean
4. Int to str
numpy_float_list.astype('int').astype('str')
array(['1', '2', '3'], dtype='<U21')
Multi-dimensional Arrays
# 2 Dimension Array
two_dimension_array = [Link]([(1,2,3),(4,5,6), (7,8,9)])
print(type (two_dimension_array))
print(two_dimension_array)
print('Shape: ', two_dimension_array.shape)
print('Size:', two_dimension_array.size)
print('Data type:', two_dimension_array.dtype)
<class '[Link]'>
[[1 2 3]
[4 5 6]
[7 8 9]]
Shape: (3, 3)
Size: 9
Data type: int64
print(np_list_one + np_list_two)
Matrix in numpy
four_by_four_matrix = [Link]([Link]((4,4), dtype=float))
four_by_four_matrix
matrix([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]])
[Link](four_by_four_matrix)[2] = 2
four_by_four_matrix
matrix([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[2., 2., 2., 2.],
[1., 1., 1., 1.]])
Numpy [Link]()
What is Arrange?
Sometimes, you want to create values that are evenly spaced within a
defined interval. For instance, you want to create values from 1 to 10; you
can use [Link]() function
# Syntax:
Numpy Functions
o Min [Link]()
o Max [Link]()
o Mean [Link]()
o Median [Link]()
o Varience
o Percentile
o Standard deviation [Link]()
# Syntax
# [Link](x, y, out=None)
Linear Algebra
1. Dot Product
## Linear algebra
### Dot product: product of two arrays
f = [Link]([1,2,3])
g = [Link]([4,5,3])
### 1*4+2*5 + 3*6
[Link](f, g) # 23
We use linear equation for quantities which have linear relationship. Let's
see the example below:
temp = [Link]([1,2,3,4,5])
pressure = temp * 2 + 5
pressure
[Link](temp,pressure)
[Link]('Temperature in oC')
[Link]('Pressure in atm')
[Link]('Temperature vs Pressure')
[Link]([Link](0, 6, step=0.5))
[Link]()
To draw the Gaussian normal distribution using numpy. As you can see
below, the numpy can generate random numbers. To create random sample,
we need the mean(mu), sigma(standard deviation), mumber of data points.
mu = 28
sigma = 15
samples = 100000
Summary
To summarize, the main differences with python lists are:
💻 Exercises: Day 24
1. Repeat all the examples
Pandas
Pandas is an open source, high-performance, easy-to-use data structures
and data analysis tools for the Python programming language. Pandas adds
data structures and tools designed to work with table-like data which
is Series and Data Frames. Pandas provides tools for data manipulation:
reshaping
merging
sorting
slicing
aggregation
imputation. If you are using anaconda, you do not have install pandas.
Installing Pandas
For Mac:
For Windows:
Countries Series
Cities Series
As you can see, pandas series is just one column of data. If we want to have
multiple columns we use data frames. The example below shows pandas
DataFrames.
Data frame is a collection of rows and columns. Look at the table below; it
has many more columns than the example above:
Next, we will see how to import pandas and how to create Series and
DataFrames using pandas
Importing Pandas
import pandas as pd # importing pandas as pd
import numpy as np # importing numpy as np
DataFrames
Pandas data frames can be created in different ways.
1 David UK London
1 David UK London
1 David UK London
curl -O [Link]
data/[Link]
import pandas as pd
df = pd.read_csv('[Link]')
print(df)
Data Exploration
Let us read only the first 5 rows using head()
Let us also explore the last recordings of the dataframe using the tail()
methods.
print([Link]()) # tails give the last five rows, we can increase the rows by
passing argument to tail method
999
Female 66.172652 136.777454
5
999
Female 67.067155 170.867906
6
999
Female 63.867992 128.475319
7
999
Female 69.034243 163.852461
8
999
Female 61.944246 113.649103
9
As you can see the csv file has three rows: Gender, Height and Weight. If the
DataFrame would have a long rows, it would be hard to know all the
columns. Therefore, we should use a method to know the colums. we do not
know the number of rows. Let's use shape meathod.
print([Link])
Index(['Gender', 'Height', 'Weight'], dtype='object')
Height Weight
Similar to describe(), the info() method also give information about the
dataset.
Modifying a DataFrame
Modifying a DataFrame: * We can create a new DataFrame * We can create a
new column and add it to the DataFrame, * we can remove an existing
column from a DataFrame, * we can modify an existing column in a
DataFrame, * we can change the data type of column values in the
DataFrame
Creating a DataFrame
As always, first we import the necessary packages. Now, lets import pandas
and numpy, two best friends ever.
import pandas as pd
import numpy as np
data = [
{"Name": "Asabeneh", "Country":"Finland","City":"Helsinki"},
{"Name": "David", "Country":"UK","City":"London"},
{"Name": "John", "Country":"Sweden","City":"Stockholm"}]
df = [Link](data)
print(df)
1 David UK London
First let's use the previous example to create a DataFrame. After we create
the DataFrame, we will start modifying the columns and column values.
1 David UK London 78
Name Country City Weight
Countr
Name City Weight Height
y
As you can see in the DataFrame above, we did add new columns, Weight
and Height. Let's add one additional column called BMI(Body Mass Index) by
calculating their BMI using thier mass and height. BMI is mass divided by
height squared (in meters) - Weight/Height * Height.
Countr
Name City Weight Height
y
bmi = calculate_bmi()
df['BMI'] = bmi
df
Countr Heigh
Name City Weight BMI
y t
df['BMI'] = round(df['BMI'], 1)
print(df)
Countr Heigh
Name City Weight BMI
y t
The information in the DataFrame seems not yet complete, let's add birth
year and current year columns.
birth_year = ['1769', '1985', '1990']
current_year = [Link](2020, index=[0, 1,2])
df['Birth Year'] = birth_year
df['Current Year'] = current_year
df
Birt
Countr Weigh Heigh BM Curren
Name City h
y t t I t Year
Year
Asabene
0 Finland Helsinki 74 1.73 24.7 1769 2020
h
Stockhol
2 John Sweden 69 1.69 24.2 1990 2020
m
Now, the column values of birth year and current year are integers. We can
calculate the age.
Birt
Curre
Count Weig Heig BM h Ag
Name City nt
ry ht ht I Yea es
Year
r
25. 198
1 David UK London 78 1.75 2019 34
5 5
The person in the first row lived so far for 251 years. It is unlikely for
someone to live so long. Either it is a typo or the data is cooked. So lets fill
that data with average of the columns without including outlier.
Boolean Indexing
print(df[df['Ages'] > 120])
Birt
Curre
Count Weig Heig BM h Age
Name City nt
ry ht ht I Yea s
Year
r
Exercises: Day 25
1. Read the hacker_news.csv file from data directory
2. Get the first five rows
3. Get the last five rows
4. Get the title column as pandas series
5. Count the number of rows and columns
o Filter the titles which contain python
o Filter the titles which contain JavaScript
o Explore the data and make sense of it
Flask
Flask is a web development framework written in Python. Flask uses Jinja2
template engine. Flask can be also used with other modern front libraries
such as React.
If you did not install the virtualenv package yet install it first. Virtual
environment will allows to isolate project dependencies from the local
machine dependencies.
Folder structure
After completing all the step, your project file structure should look like this:
├── Procfile
├── [Link]
├── env
│ ├── bin
├── [Link]
├── static
│ └── css
│ └── [Link]
└── templates
├── [Link]
├── [Link]
├── [Link]
├── [Link]
└── [Link]
Step 2:
Now, let's create [Link] file in the project directory and write the following
code. The [Link] file will be the main file in the project. The following code
has flask module, os module.
Creating routes
The home route.
app = Flask(__name__)
@[Link]('/about')
def about():
return '<h1>About us</h1>'
if __name__ == '__main__':
# for deployment we use the environ
# to make it work for both production and development
port = int([Link]("PORT", 5000))
[Link](debug=True, host='[Link]', port=port)
To run the flask application, write python [Link] in the main flask application
directory.
app = Flask(__name__)
@[Link]('/about')
def about():
return '<h1>About us</h1>'
if __name__ == '__main__':
# for deployment we use the environ
# to make it work for both production and development
port = int([Link]("PORT", 5000))
[Link](debug=True, host='[Link]', port=port)
Now, we added the about route in the above code. How about if we want to
render an HTML file instead of string? It is possible to render HTML file using
the function render_templae. Let us create a folder called templates and
create [Link] and [Link] in the project directory. Let us also import
the render_template function from flask.
Creating templates
Create the HTML files inside templates folder.
[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Home</title>
</head>
<body>
<h1>Welcome Home</h1>
</body>
</html>
[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>About</title>
</head>
<body>
<h1>About Us</h1>
</body>
</html>
Python Script
[Link]
app = Flask(__name__)
if __name__ == '__main__':
# for deployment we use the environ
# to make it work for both production and development
port = int([Link]("PORT", 5000))
[Link](debug=True, host='[Link]', port=port)
Navigation
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
</ul>
Now, we can navigate between the pages using the above link. Let us create
additional page which handle form data. You can call it any name, I like to
call it [Link].
We can inject data to the HTML files using Jinja2 template engine.
app = Flask(__name__)
@[Link]('/about')
def about():
name = '30 Days Of Python Programming'
return render_template('[Link]', name = name, title = 'About Us')
@[Link]('/post')
def post():
name = 'Text Analyzer'
return render_template('[Link]', name = name, title = name)
if __name__ == '__main__':
# for deployment
# to make it work for both production and development
port = int([Link]("PORT", 5000))
[Link](debug=True, host='[Link]', port=port)
[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Home</title>
</head>
<body>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
</ul>
<h1>Welcome to {{name}}</h1>
<ul>
{% for tech in techs %}
<li>{{tech}}</li>
{% endfor %}
</ul>
</body>
</html>
[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>About Us</title>
</head>
<body>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
</ul>
<h1>About Us</h1>
<h2>{{name}}</h2>
</body>
</html>
Creating a layout
In the template files, there are lots of repeated codes, we can write a layout
and we can remove the repetition. Let's create [Link] inside the
templates folder. After we create the layout we will import to every file.
Create a static folder in your project directory. Inside the static folder create
CSS or styles folder and create a CSS stylesheet. We use the url_for module
to serve the static file.
[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
href="[Link]
Nunito:300,400|Raleway:300,400,500&display=swap"
rel="stylesheet"
/>
<link
rel="stylesheet"
href="{{ url_for('static', filename='css/[Link]') }}"
/>
{% if title %}
<title>30 Days of Python - {{ title}}</title>
{% else %}
<title>30 Days of Python</title>
{% endif %}
</head>
<body>
<header>
<div class="menu-container">
<div>
<a class="brand-name nav-link" href="/">30DaysOfPython</a>
</div>
<ul class="nav-lists">
<li class="nav-list">
<a class="nav-link active" href="{{ url_for('home') }}">Home</a>
</li>
<li class="nav-list">
<a class="nav-link active"
href="{{ url_for('about') }}">About</a>
</li>
<li class="nav-list">
<a class="nav-link active" href="{{ url_for('post') }}"
>Text Analyzer</a
>
</li>
</ul>
</div>
</header>
<main>
{% block content %} {% endblock %}
</main>
</body>
</html>
Now, lets remove all the repeated code in the other template files and import
the [Link]. The href is using url_for function with the name of the route
function to connect each navigation route.
[Link]
{% endfor %}
</ul>
</div>
{% endblock %}
[Link]
[Link]
{% endblock %}
In the post, route we will use GET and POST method alternative depending
on the type of request, check how it looks in the code below. The request
method is a function to handle request methods and also to access form
data. [Link]
app = Flask(__name__)
# to stop caching static file
[Link]['SEND_FILE_MAX_AGE_DEFAULT'] = 0
@[Link]('/about')
def about():
name = '30 Days Of Python Programming'
return render_template('[Link]', name = name, title = 'About Us')
@[Link]('/result')
def result():
return render_template('[Link]')
So far, we have seen how to use template and how to inject data to
template, how to a common layout. Now, lets handle static file. Create a
folder called static in the project director and create a folder called css.
Inside css folder create [Link]. Your main. css file will be linked to the
[Link].
You don't have to write the css file, copy and use it. Let's move on to
deployment.
Deployment
Heroku provides a free deployment service for both front end and fullstack
applications. Create an account on heroku and install the heroku CLI for you
machine. After installing heroku write the following command
Login to Heroku
Let's see the result by clicking any key from the keyboard. When you press
any key from you keyboard it will open the heroku login page and click the
login page. Then you will local machine will be connected to the remote
heroku server. If you are connected to remote server, you will see this.
[Link]
Procfile
(env) asabeneh@Asabeneh:~/Desktop/python_for_web$ pip freeze
Click==7.0
Flask==1.1.1
itsdangerous==1.1.0
Jinja2==2.10.3
MarkupSafe==1.1.1
Werkzeug==0.16.0
(env) asabeneh@Asabeneh:~/Desktop/python_for_web$ touch [Link]
(env) asabeneh@Asabeneh:~/Desktop/python_for_web$ pip freeze >
[Link]
(env) asabeneh@Asabeneh:~/Desktop/python_for_web$ cat [Link]
Click==7.0
Flask==1.1.1
itsdangerous==1.1.0
Jinja2==2.10.3
MarkupSafe==1.1.1
Werkzeug==0.16.0
(env) asabeneh@Asabeneh:~/Desktop/python_for_web$ touch Procfile
(env) asabeneh@Asabeneh:~/Desktop/python_for_web$ ls
Procfile env/ static/
[Link] [Link] templates/
(env) asabeneh@Asabeneh:~/Desktop/python_for_web$
The Procfile will have the command which run the application in the web
server in our case on Heroku.
1. git init
2. git add .
3. git commit -m "commit message"
4. heroku create 'name of the app as one word'
5. git push heroku master
6. heroku open(to launch the deployed application)
Exercises: Day 26
1. You will build this application. Only the text analyser part is left
MongoDB
MongoDB is a NoSQL database. MongoDB stores data in a JSON like
document which make MongoDB very flexible and scalable. Let us see the
different terminologies of SQL and NoSQL databases. The following table will
make the difference between SQL versus NoSQL databases.
Choose the proximate free region and give any name for you cluster.
Now, a free sandbox is created
All local host access
Add user and password
Create a mongoDB uri link
Select Python 3.6 or above driver
Getting Connection String(MongoDB URI)
Copy the connection string link and you will get something like this:
mongodb+srv://asabeneh:<password>@[Link]/test?
retryWrites=true&w=majority
Do not worry about the url, it is a means to connect your application with
mongoDB. Let us replace the password placeholder with the password you
used to add a user.
Example:
mongodb+srv://asabeneh:123123123@[Link]/test?
retryWrites=true&w=majority
Now, I replaced everything and the password is 123123 and the name of the
database is thirty_days_python. This is just an example, your password must
be stronger than the example password.
app = Flask(__name__)
if __name__ == '__main__':
# for deployment we use the environ
# to make it work for both production and development
port = int([Link]("PORT", 5000))
[Link](debug=True, host='[Link]', port=port)
When we run the above code we get the default mongoDB databases.
['admin', 'local']
To create a database:
app = Flask(__name__)
if __name__ == '__main__':
# for deployment we use the environ
# to make it work for both production and development
port = int([Link]("PORT", 5000))
[Link](debug=True, host='[Link]', port=port)
If you see this on the mongoDB cluster, it means you have successfully
created a database and a collection.
If you have seen on the figure, the document has been created with a long id
which acts as a primary key. Every time we create a document mongoDB
create and unique id for it.
students = [
{'name':'David','country':'UK','city':'London','age':34},
{'name':'John','country':'Sweden','city':'Stockholm','age':28},
{'name':'Sami','country':'Finland','city':'Helsinki','age':25},
]
for student in students:
[Link].insert_one(student)
app = Flask(__name__)
if __name__ == '__main__':
# for deployment we use the environ
# to make it work for both production and development
port = int([Link]("PORT", 5000))
[Link](debug=True, host='[Link]', port=port)
MongoDB Find
The find() and findOne() methods are common method to find data in a
collection in mongoDB database. It is similar to the SELECT statement in a
MySQL database. Let us use the find_one() method to get a document in a
database collection.
app = Flask(__name__)
if __name__ == '__main__':
# for deployment we use the environ
# to make it work for both production and development
port = int([Link]("PORT", 5000))
[Link](debug=True, host='[Link]', port=port)
{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country':
'Helsinki', 'city': 'Helsinki', 'age': 250}
The above query returns the first entry but we can target specific document
using specific _id. Let us do one example, use David's id to get David object.
'_id':ObjectId('5df68a23f106fe2d315bbc8c')
app = Flask(__name__)
if __name__ == '__main__':
# for deployment we use the environ
# to make it work for both production and development
port = int([Link]("PORT", 5000))
[Link](debug=True, host='[Link]', port=port)
{'_id': ObjectId('5df68a23f106fe2d315bbc8c'), 'name': 'David', 'country':
'UK', 'city': 'London', 'age': 34}
We have seen, how to use find_one() using the above examples. Let's move
one to find()
MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-
[Link]/test?retryWrites=true&w=majority'
client = [Link](MONGODB_URI)
db = client['thirty_days_of_python'] # accessing the database
students = [Link]()
for student in students:
print(student)
app = Flask(__name__)
if __name__ == '__main__':
# for deployment we use the environ
# to make it work for both production and development
port = int([Link]("PORT", 5000))
[Link](debug=True, host='[Link]', port=port)
{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country':
'Finland', 'city': 'Helsinki', 'age': 250}
{'_id': ObjectId('5df68a23f106fe2d315bbc8c'), 'name': 'David', 'country':
'UK', 'city': 'London', 'age': 34}
{'_id': ObjectId('5df68a23f106fe2d315bbc8d'), 'name': 'John', 'country':
'Sweden', 'city': 'Stockholm', 'age': 28}
{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country':
'Finland', 'city': 'Helsinki', 'age': 25}
MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-
[Link]/test?retryWrites=true&w=majority'
client = [Link](MONGODB_URI)
db = client['thirty_days_of_python'] # accessing the database
students = [Link]({}, {"_id":0, "name": 1, "country":1}) # 0 means
not include and 1 means include
for student in students:
print(student)
app = Flask(__name__)
if __name__ == '__main__':
# for deployment we use the environ
# to make it work for both production and development
port = int([Link]("PORT", 5000))
[Link](debug=True, host='[Link]', port=port)
{'name': 'Asabeneh', 'country': 'Finland'}
{'name': 'David', 'country': 'UK'}
{'name': 'John', 'country': 'Sweden'}
{'name': 'Sami', 'country': 'Finland'}
MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-
[Link]/test?retryWrites=true&w=majority'
client = [Link](MONGODB_URI)
db = client['thirty_days_of_python'] # accessing the database
query = {
"country":"Finland"
}
students = [Link](query)
app = Flask(__name__)
if __name__ == '__main__':
# for deployment we use the environ
# to make it work for both production and development
port = int([Link]("PORT", 5000))
[Link](debug=True, host='[Link]', port=port)
{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country':
'Finland', 'city': 'Helsinki', 'age': 250}
{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country':
'Finland', 'city': 'Helsinki', 'age': 25}
MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-
[Link]/test?retryWrites=true&w=majority'
client = [Link](MONGODB_URI)
db = client['thirty_days_of_python'] # accessing the database
query = {
"city":"Helsinki"
}
students = [Link](query)
for student in students:
print(student)
app = Flask(__name__)
if __name__ == '__main__':
# for deployment we use the environ
# to make it work for both production and development
port = int([Link]("PORT", 5000))
[Link](debug=True, host='[Link]', port=port)
{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country':
'Finland', 'city': 'Helsinki', 'age': 250}
{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country':
'Finland', 'city': 'Helsinki', 'age': 25}
MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-
[Link]/test?retryWrites=true&w=majority'
client = [Link](MONGODB_URI)
db = client['thirty_days_of_python'] # accessing the database
query = {
"country":"Finland",
"city":"Helsinki"
}
students = [Link](query)
for student in students:
print(student)
app = Flask(__name__)
if __name__ == '__main__':
# for deployment we use the environ
# to make it work for both production and development
port = int([Link]("PORT", 5000))
[Link](debug=True, host='[Link]', port=port)
{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country':
'Finland', 'city': 'Helsinki', 'age': 250}
{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country':
'Finland', 'city': 'Helsinki', 'age': 25}
MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-
[Link]/test?retryWrites=true&w=majority'
client = [Link](MONGODB_URI)
db = client['thirty_days_of_python'] # accessing the database
query = {"age":{"$gt":30}}
students = [Link](query)
for student in students:
print(student)
app = Flask(__name__)
if __name__ == '__main__':
# for deployment we use the environ
# to make it work for both production and development
port = int([Link]("PORT", 5000))
[Link](debug=True, host='[Link]', port=port)
{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country':
'Finland', 'city': 'Helsinki', 'age': 250}
{'_id': ObjectId('5df68a23f106fe2d315bbc8c'), 'name': 'David', 'country':
'UK', 'city': 'London', 'age': 34}
# let's import the flask
from flask import Flask, render_template
import os # importing operating system module
import pymongo
MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-
[Link]/test?retryWrites=true&w=majority'
client = [Link](MONGODB_URI)
db = client['thirty_days_of_python'] # accessing the database
query = {"age":{"$gt":30}}
students = [Link](query)
for student in students:
print(student)
{'_id': ObjectId('5df68a23f106fe2d315bbc8d'), 'name': 'John', 'country':
'Sweden', 'city': 'Stockholm', 'age': 28}
{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country':
'Finland', 'city': 'Helsinki', 'age': 25}
Limiting documents
We can limit the number of documents we return using the limit() method.
MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-
[Link]/test?retryWrites=true&w=majority'
client = [Link](MONGODB_URI)
db = client['thirty_days_of_python'] # accessing the database
[Link]().limit(3)
MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-
[Link]/test?retryWrites=true&w=majority'
client = [Link](MONGODB_URI)
db = client['thirty_days_of_python'] # accessing the database
students = [Link]().sort('name')
for student in students:
print(student)
students = [Link]().sort('name',-1)
for student in students:
print(student)
students = [Link]().sort('age')
for student in students:
print(student)
students = [Link]().sort('age',-1)
for student in students:
print(student)
app = Flask(__name__)
if __name__ == '__main__':
# for deployment we use the environ
# to make it work for both production and development
port = int([Link]("PORT", 5000))
[Link](debug=True, host='[Link]', port=port)
Ascending order
Descending order
MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-
[Link]/test?retryWrites=true&w=majority'
client = [Link](MONGODB_URI)
db = client['thirty_days_of_python'] # accessing the database
query = {'age':250}
new_value = {'$set':{'age':38}}
[Link].update_one(query, new_value)
# lets check the result if the age is modified
for student in [Link]():
print(student)
app = Flask(__name__)
if __name__ == '__main__':
# for deployment we use the environ
# to make it work for both production and development
port = int([Link]("PORT", 5000))
[Link](debug=True, host='[Link]', port=port)
{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country':
'Finland', 'city': 'Helsinki', 'age': 38}
{'_id': ObjectId('5df68a23f106fe2d315bbc8c'), 'name': 'David', 'country':
'UK', 'city': 'London', 'age': 34}
{'_id': ObjectId('5df68a23f106fe2d315bbc8d'), 'name': 'John', 'country':
'Sweden', 'city': 'Stockholm', 'age': 28}
{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country':
'Finland', 'city': 'Helsinki', 'age': 25}
Delete Document
The method delete_one() deletes one document. The delete_one() takes a
query object parameter. It only removes the first occurrence. Let us remove
one John from the collection.
query = {'name':'John'}
[Link].delete_one(query)
app = Flask(__name__)
if __name__ == '__main__':
# for deployment we use the environ
# to make it work for both production and development
port = int([Link]("PORT", 5000))
[Link](debug=True, host='[Link]', port=port)
{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country':
'Finland', 'city': 'Helsinki', 'age': 38}
{'_id': ObjectId('5df68a23f106fe2d315bbc8c'), 'name': 'David', 'country':
'UK', 'city': 'London', 'age': 34}
{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country':
'Finland', 'city': 'Helsinki', 'age': 25}
As you can see John has been removed from the collection.
Drop a collection
Using the drop() method we can delete a collection from a database.
MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-
[Link]/test?retryWrites=true&w=majority'
client = [Link](MONGODB_URI)
db = client['thirty_days_of_python'] # accessing the database
[Link]()
Web API has been moving away from Simple Object Access Protocol (SOAP)
based web services and service-oriented architecture (SOA) towards more
direct representational state transfer (REST) style web resources.
Social media services, web APIs have allowed web communities to share
content and data between communities and different platforms.
Using API, content that is created in one place dynamically can be posted
and updated to multiple locations on the web.
For example, Twitter's REST API allows developers to access core Twitter
data and the Search API provides methods for developers to interact with
Twitter Search and trends data.
Many applications provide API end points. Some examples of API such as the
countries API, cat's breed API.
In this section, we will cover a RESTful API that uses HTTP request methods
to GET, PUT, POST and DELETE data.
Building API
RESTful API is an application program interface (API) that uses HTTP requests
to GET, PUT, POST and DELETE data. In the previous sections, we have
learned about python, flask and mongoDB. We will use the knowledge we
acquire to develop a RESTful API using Python flask and mongoDB database.
Every application which has CRUD(Create, Read, Update, Delete) operation
has an API to create data, to get data, to update data or to delete data from
a database.
To build an API, it is good to understand HTTP protocol and HTTP request and
response cycle.
Structure of HTTP
HTTP uses client-server model. An HTTP client opens a connection and sends
a request message to an HTTP server and the HTTP server returns response
message which is the requested resources. When the request response cycle
completes the server closes the connection.
The format of the request and response messages are similar. Both kinds of
messages have
an initial line,
zero or more header lines,
a blank line (i.e. a CRLF by itself), and
an optional message body (e.g. a file, or query data, or query output).
Let us an example of request and response messages by navigating this
site:[Link] This site has been
deployed on Heroku free dyno and in some months may not work because of
high request. Support this work to make the server run all the time.
GET is the most common HTTP that helps to get or read resource and POST
is a common request method to create resource.
HTTP version
Response status code that gives the result of the request, and a reason
which describes the status code. Example of status lines are: HTTP/1.0
200 OK or HTTP/1.0 404 Not Found Notes:
The most common status codes are: 200 OK: The request succeeded, and
the resulting resource (e.g. file or script output) is returned in the message
body. 500 Server Error A complete list of HTTP status code can be
found here. It can be also found here.
Header Fields
As you have seen in the above screenshot, header lines provide information
about the request or response, or about the object sent in the message
body.
GET / HTTP/1.1
Host: [Link]
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36
Sec-Fetch-User: ?1
Accept:
text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/
apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: navigate
Referer: [Link]
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en;q=0.9,fi-FI;q=0.8,fi;q=0.7,en-CA;q=0.6,en-
US;q=0.5,fr;q=0.4
If an HTTP message includes a body, there are usually header lines in the
message that describe the body. In particular,
Request Methods
The GET, POST, PUT and DELETE are the HTTP request methods which we are
going to implement an API or a CRUD operation application.
1. GET: GET method is used to retrieve and get information from the
given server using a given URI. Requests using GET should only
retrieve data and should have no other effect on the data.
2. POST: POST request is used to create data and send data to the server,
for example, creating a new post, file upload, etc. using HTML forms.
💻 Exercises: Day 28
1. Read about API and HTTP
Building API
In this section, we will cove a RESTful API that uses HTTP request methods to
GET, PUT, POST and DELETE data.
RESTful API is an application program interface (API) that uses HTTP requests
to GET, PUT, POST and DELETE data. In the previous sections, we have
learned about python, flask and mongoDB. We will use the knowledge we
acquire to develop a RESTful API using python flask and mongoDB. Every
application which has CRUD(Create, Read, Update, Delete) operation has an
API to create data, to get data, to update data or to delete data from
database.
The browser can handle only get request. Therefore, we have to have a tool
which can help us to handle all request methods(GET, POST, PUT, DELETE).
Examples of API
Postman is a very popular tool when it comes to API development. So, if you
like to do this section you need to download postman. An alternative of
Postman is Insomnia.
Structure of an API
An API end point is a URL which can help to retrieve, create, update or delete
a resource. The structure looks like this:
Example: [Link] Returns the
members of the specified list. Private list members will only be shown if the
authenticated user owns the specified list. The name of the company name
followed by version followed by the purpose of the API. The methods: HTTP
methods & URLs
The API uses the following HTTP methods for object manipulation:
Postman
Python
Flask
MongoDB
app = Flask(__name__)
In stead of displaying dummy data let us connect the flask application with
MongoDB and get data from mongoDB database.
#
MONGODB_URI='mongodb+srv://asabeneh:your_password@30daysofpython-
[Link]/test?retryWrites=true&w=majority'
client = [Link](MONGODB_URI)
db = client['thirty_days_of_python'] # accessing the database
if __name__ == '__main__':
# for deployment
# to make it work for both production and development
port = int([Link]("PORT", 5000))
[Link](debug=True, host='[Link]', port=port)
By connecting the flask, we can fetch students collection data from the
thirty_days_of_python database.
[
{
"_id": {
"$oid": "5df68a21f106fe2d315bbc8b"
},
"name": "Asabeneh",
"country": "Finland",
"city": "Helsinki",
"age": 38
},
{
"_id": {
"$oid": "5df68a23f106fe2d315bbc8c"
},
"name": "David",
"country": "UK",
"city": "London",
"age": 34
},
{
"_id": {
"$oid": "5df68a23f106fe2d315bbc8e"
},
"name": "Sami",
"country": "Finland",
"city": "Helsinki",
"age": 25
}
]
Getting a document by id
We can access signle document using an id, let's access Asabeneh using his
id. [Link]
app = Flask(__name__)
#
MONGODB_URI='mongodb+srv://asabeneh:your_password@30daysofpython-
[Link]/test?retryWrites=true&w=majority'
client = [Link](MONGODB_URI)
db = client['thirty_days_of_python'] # accessing the database
if __name__ == '__main__':
# for deployment
# to make it work for both production and development
port = int([Link]("PORT", 5000))
[Link](debug=True, host='[Link]', port=port)
[
{
"_id": {
"$oid": "5df68a21f106fe2d315bbc8b"
},
"name": "Asabeneh",
"country": "Finland",
"city": "Helsinki",
"age": 38
}
]
app = Flask(__name__)
#
MONGODB_URI='mongodb+srv://asabeneh:your_password@30daysofpython-
[Link]/test?retryWrites=true&w=majority'
client = [Link](MONGODB_URI)
db = client['thirty_days_of_python'] # accessing the database
}
[Link].insert_one(student)
return ;
def update_student (id):
if __name__ == '__main__':
# for deployment
# to make it work for both production and development
port = int([Link]("PORT", 5000))
[Link](debug=True, host='[Link]', port=port)
Updating using PUT
# let's import the flask
app = Flask(__name__)
#
MONGODB_URI='mongodb+srv://asabeneh:your_password@30daysofpython-
[Link]/test?retryWrites=true&w=majority'
client = [Link](MONGODB_URI)
db = client['thirty_days_of_python'] # accessing the database
}
[Link].insert_one(student)
return
@[Link]('/api/v1.0/students/<id>', methods = ['PUT']) # this decorator
create the home route
def update_student (id):
query = {"_id":ObjectId(id)}
name = [Link]['name']
country = [Link]['country']
city = [Link]['city']
skills = [Link]['skills'].split(', ')
bio = [Link]['bio']
birthyear = [Link]['birthyear']
created_at = [Link]()
student = {
'name': name,
'country': country,
'city': city,
'birthyear': birthyear,
'skills': skills,
'bio': bio,
'created_at': created_at
}
[Link].update_one(query, student)
# return Response(dumps({"result":"a new student has been created"}),
mimetype='application/json')
return
def update_student (id):
if __name__ == '__main__':
# for deployment
# to make it work for both production and development
port = int([Link]("PORT", 5000))
[Link](debug=True, host='[Link]', port=port)
app = Flask(__name__)
#
MONGODB_URI='mongodb+srv://asabeneh:your_password@30daysofpython-
[Link]/test?retryWrites=true&w=majority'
client = [Link](MONGODB_URI)
db = client['thirty_days_of_python'] # accessing the database
}
[Link].insert_one(student)
return
@[Link]('/api/v1.0/students/<id>', methods = ['PUT']) # this decorator
create the home route
def update_student (id):
query = {"_id":ObjectId(id)}
name = [Link]['name']
country = [Link]['country']
city = [Link]['city']
skills = [Link]['skills'].split(', ')
bio = [Link]['bio']
birthyear = [Link]['birthyear']
created_at = [Link]()
student = {
'name': name,
'country': country,
'city': city,
'birthyear': birthyear,
'skills': skills,
'bio': bio,
'created_at': created_at
}
[Link].update_one(query, student)
# return Response(dumps({"result":"a new student has been created"}),
mimetype='application/json')
return
@[Link]('/api/v1.0/students/<id>', methods = ['PUT']) # this decorator
create the home route
def update_student (id):
query = {"_id":ObjectId(id)}
name = [Link]['name']
country = [Link]['country']
city = [Link]['city']
skills = [Link]['skills'].split(', ')
bio = [Link]['bio']
birthyear = [Link]['birthyear']
created_at = [Link]()
student = {
'name': name,
'country': country,
'city': city,
'birthyear': birthyear,
'skills': skills,
'bio': bio,
'created_at': created_at
}
[Link].update_one(query, student)
# return Response(dumps({"result":"a new student has been created"}),
mimetype='application/json')
return ;
@[Link]('/api/v1.0/students/<id>', methods = ['DELETE'])
def delete_student (id):
[Link].delete_one({"_id":ObjectId(id)})
return
if __name__ == '__main__':
# for deployment
# to make it work for both production and development
port = int([Link]("PORT", 5000))
[Link](debug=True, host='[Link]', port=port)
💻 Exercises: Day 29
1. Implement the above example and develop this