BIL113E course designed as half-self-paced course. The course hours should mostly used for questions, assignments and brief introductions. For the Python section of this course we will be using Anaconda software. By installing Anaconda alone, you will have Python, IDE, Jupyter notebook, and more installed.
You can try and manipulate the codes on the notebook by yourself: Download Notebook.
We often use comments within our commands. Some explanations would be helpful as size if your code increases. You can use hashtag (#) for make an comment within your code.
# This is a comment
# These lines of code will not change any values
# Anything following the first # is not run as code
You should be familiar with the variables. They are the basis of knowledge within our code. We have four common types of variables:
my_integer = 50
print (my_integer)
print(type(my_integer))
IF you assign a value to a new variable (my_integer) Python automatically recognizes the type of the variable. By the way you learnt two more things:
my_float = 1.0
print(my_float, type(my_float))
Using dot(.) in the definition made variable's type float. By the way, You can print several things using comma(,) like the example above.
my_string = 'This is a string with single quotes'
print(my_string, type(my_string))
my_string2 = "This is a string with double quotes"
print(my_string2, type(my_string2))
my_string3 = '1'
print(my_string3, type(my_string3))
We have some points to remark:
my_string = 'It's a book'
As you see above we had a syntax error because wanted to define a string that contains single string: It's a book. We can define it in several ways:
string1 = 'It\'s a book'
print(string1)
string2 = "It's a book"
print(string2)
You can ignore the quotes mark within string using \, or you can defone it inside a double quote instead.
my_bool = True
print(my_bool, type(my_bool))
my_bool = False
print(my_bool, type(my_bool))
We can define the variables as True or False as well. True and False notations are case sensitive.
my_bool = True
print(not my_bool)
If I add $not$ notation before the $my\_bool$ it becomes $False$ as seen above.
You can transform the types of variables if possible. We use:
Some examples:
print(int(1.2))
print(int(1.0))
print(int(1.8))
print(int('12'))
You will have error if you try this:
print(int('sd'))
Because 'sd' string is inconvertible to integer.
print(float(1.2))
print(float(1))
print(str(2))
print(str(2 * 9))
You can utilize built-in math functions as seen in cell above:
print('Addition: ', 2 + 2)
print('Subtraction: ', 7 - 4)
print('Multiplication: ', 2 * 5)
print('Division: ', 10 / 2)
print('Exponentiation: ', 7**2)
print('Modulo: ', 15 % 4) # it will return the remainder after dividing 15 by 4 .
You can use math for variables either:
first_integer = 7
second_integer = 3
print(first_integer * second_integer)
print(first_integer ** second_integer)
print(first_integer / second_integer)
print(first_integer + second_integer)
print(first_integer - second_integer)
Some built-in math functions:
Some examples:
print(abs(-5*3))
print(round(first_integer / second_integer))
One of the most useful collection type in Python is the Lists. Example:
my_list = [1, 2, 3]
print(my_list)
print(my_list[0])
print(my_list[2])
The first item in the list is indexed as 0.
my_list.append('a string item')
print(my_list)
As you see we added a fourth item in the list with append function. You might have noticed that we add strings within the quote marks again. If you add numbers in quote marks they will be recognized as string not integer or float.
For all items or functions you can preview the possible functions. For example after typing my_list. click on Tab:
But note the we have already defined my_list variable as a list beforehand.
You can do add, remove, sort, reverse... the list. So for details you should find the documentations. Just google python 3 list functions. One advantage of Python is that you can easily find documents and find solutions to your problems on the internet.
Useful document for list operations. Data Structures
You can do some other operations on the lists:
print(my_list * 2)
print(my_list + [4,2,7,'2'])
my_list2 = my_list[:-1] + [4,2,7] + [2] * 5
print(my_list2)
my_list2.sort()
print(my_list2)
print('Total number of 2s in the list: ' , my_list2.count(2))
We created a new list, my_list2, combination of three lists. We excluded the last item of the my_list because it is not an integer and cannot be sorted. We also used the count function to find how many 2s exist in the list.
print(my_list2[-5:-1]) # from the last 5th item to the last 1st item
print(my_list2[1:9]) # from the index 1 to the index 9 (be careful that index and the order are different)
print(my_list2[-5:]) # from the last 5th item to the end
print(my_list2[:2]) # from the beginning to the index 2. But index 2 is not included.
my_animals = ['dog', 'cat', 'elephant', 'monkey']
transformed_string = ' '.join(my_animals)
print(transformed_string)
A tuple is a data type similar to a list in that it can hold different kinds of data types. The key difference here is that a tuple is immutable. We define a tuple by separating the elements we want to include by commas. It is conventional to surround a tuple with parentheses.
my_tuple = ('I', 'have', 30, 'cats')
print(my_tuple)
print(type(my_tuple))
We will not use tuples as much as lists. One thing you should remember is that they are immutable, so can't change the values of a tuple. There will be an error: TypeError: 'tuple' object does not support item assignment
.
my_tuple[0] = 'He'
Some properties of the tuples can be seen below:
print(my_tuple[0])
print(my_tuple[1])
print(my_tuple[2])
print(my_tuple[3])
my_other_tuple = ('make', 'that', 50)
print(my_tuple + my_other_tuple)
str1, str2, str3, str4 = my_tuple
print(str1)
print(str2)
print(str3)
print(str4)
A set
is a collection of unordered, unique elements. It works almost exactly as you would expect a normal set of things in mathematics to work and is defined using braces ({}
).
things_i_like = {'dogs', 7, 'the number 4', 4, 4, 4, 42, 'lizards', 'man I just LOVE the number 4'}
print(things_i_like)
print(type(things_i_like))
animal_list = ['cats', 'dogs', 'dogs', 'dogs', 'lizards', 'sponges', 'cows', 'bats', 'sponges']
animal_set = set(animal_list)
print(animal_set) # Removes all extra instances from the list
print(len(things_i_like))
print(len(animal_set))
We have learnt a very useful function len()
. It returns how many items does a list, dictionary, set or other relevant objects have. You can use it for the lists as well:
print(my_list)
print('my_list have' , len(my_list), 'items')
We have some logical operators used in Python similar to the daily words. For example:
print('cats' in animal_set)
print('cats' in animal_list)
print('cats' in my_list)
print(('cats' in animal_list) and ('cats' in my_list))
print(('cats' in animal_list) or ('cats' in my_list))
print(animal_set | things_i_like) # You can also write things_i_like | animal_set with no difference
print(animal_set & things_i_like) # Common elements in both sets.
Another essential data structure in Python is the dictionary. Dictionaries are defined with a combination of curly braces ({}
) and colons (:
). The braces define the beginning and end of a dictionary and the colons indicate key-value pairs. A dictionary is essentially a set of key-value pairs. The key of any entry must be an immutable data type. This makes both strings and tuples candidates. Keys can be both added and deleted.
In the following example, we have a dictionary composed of key-value pairs where the key is a genre of fiction (string
) and the value is a list of books (list
) within that genre. Since a collection is still considered a single entity, we can use one to collect multiple variables or values into one key-value pair.
my_dict = {"High Fantasy": ["Wheel of Time", "Lord of the Rings"],
"Sci-fi": ["Book of the New Sun", "Neuromancer", "Snow Crash"],
"Weird Fiction": ["At the Mountains of Madness", "The House on the Borderland"]}
print(type(my_dict))
print(my_dict)
As an index we use the index name not numbers as lists:
print(my_dict['High Fantasy'])
print(my_dict['Sci-fi'])
print(my_dict['Weird Fiction'])
You can add new items to the dictionary:
my_dict["Historical Fiction"] = ["Pillars of the Earth"]
print(my_dict)
Well, this part of the lecture is the essential section for aim of this course: Introduce the data science operations.
Remember our string variables:
print(my_string)
print(my_string2)
print(my_string3)
one_string = my_string + my_string2 + my_string3
print(one_string)
We need to add space between them:
one_string = my_string +' '+ my_string2 +' '+ my_string3
print(one_string)
That's better.
Like lists, sets or dictionaries strings have index as well:
print(one_string[0])
print(one_string[1])
print(one_string[2])
print(one_string[3])
We can do similar operations:
print(one_string[:10])
print(one_string[10:])
my_string = 'Supercalifragilisticexpialidocious'
print ('The first letter is: ', my_string[0]) # Uppercase S
print ('The last letter is: ', my_string[-1]) # lowercase s
print ('The second to last letter is: ', my_string[-2]) # lowercase u
print ('The first five characters are: ', my_string[0:5]) # Remember: slicing doesn't include the final element/index!
print ('Reverse it!: ', my_string[::-1])
print('Count of the letter i in Supercalifragilisticexpialidocious: ', my_string.count('i'))
print('Count of "li" in the same word: ', my_string.count('li'))
One of the most common operations we will use with string is replacing: replace('old', 'new')
For example we can replace all spaces with \n
and see what will happen:
print(one_string.replace(' ', '\n'))
\n
implies new line. So each word is written in a new line. Or:
print(one_string.replace(' ', '|'))
You can use replace to remove some patterns:
print(one_string.replace('is', ''))
May be it is better if we do it like:
print(one_string.replace(' is ', ' '))
Other common function is split()
. It transforms a string into a list:
transformed = one_string.split()
print(type(transformed))
print(transformed)
split()
function splits spaces and new lines \n
by default. You can split with other parameters:
print(one_string.split('is'))
As you see all is
patterns are removed and splited from that points. New list's lenght is:
print(len(one_string.split('is')))
my_string = "I can't hear you"
print(my_string.upper())
my_string = "I said HELLO"
print(my_string.lower())
my_string = "{0} - you can add anything between them - {1}".format('Marco', 'Polo')
print(my_string)
print('There are %s cats in my %s' % (13, 'apartment'))
print(1, 5 == 5)
print(2, 5 != 5)
print(3, 5 <= 5)
print(4, 5 >= 5)
print(5, 5 > 5)
print(6, not 5 > 5)
print(7, not 5 == 5)
print(8, 5 is 5)
print(9, 5 is 6)
Of course you can use variables withing the logical operators:
m = 20
n = 30
print(m < n)
print(m is n)
statement_1 = 10 > 2
statement_2 = 4 <= 6
print("Statement 1 truth value: {0}".format(statement_1))
print("Statement 2 truth value: {0}".format(statement_2))
print("Statement 1 and Statement 2: {0}".format(statement_1 and statement_2))
Let's say we have two statements $P$ and $Q$:
P | Q | not P |
P and Q |
P or Q |
---|---|---|---|---|
True |
True |
False |
True |
True |
False |
True |
True |
False |
True |
True |
False |
False |
False |
True |
False |
False |
True |
False |
False |
P = True
Q = False
print(not P)
print(P and Q)
print(P or Q)
print((P or Q) and (not Q) or P)
We generally use boolean statements with if
statement:
if P and Q:
print('If P and Q statement is True then print function will work')
Nothing happened. See why:
if P and Q:
print('If P and Q statement is True then print function will work')
else:
print('Because P and Q = ', P and Q)
General syntax is as follows:
# This is the basic format of an if statement. This is a vacuous example.
# The string "Condition" will always evaluated as True because it is a
# non-empty string. he purpose of this code is to show the formatting of
# an if-statement.
if "Condition":
# This block of code will execute because the string is non-empty
# Everything on these indented lines
print(True)
elif False:
print('Another statement that will not show up')
else:
# So if the condition that we examined with if is in fact False
# This block of code will execute INSTEAD of the first block of code
# Everything on these indented lines
print(False)
# The else block here will never execute because "Condition" is a non-empty string.
Some notes about the synyax:
if:
, elif:
or else:
the code should be in for spaces or one tab. You should have noticed the space from lefthand side.if
andelse
elif
(elseif).i = 4
if i == 5:
print("All lines in this indented block are part of this block")
print('The variable i has a value of 5')
else:
print("All lines in this indented block are part of this block")
print('The variable i is not equal to 5')
i = 2
if i == 1:
print('The variable i has a value of 1')
elif i == 2:
print('The variable i has a value of 2')
elif i == 3:
print('The variable i has a value of 3')
else:
print("I don't know :(")
i = 10
if i % 2 == 0:
if i % 3 == 0:
print('i is divisible by both 2 and 3! Wow!')
elif i % 5 == 0:
print('i is divisible by both 2 and 5! Wow!')
else:
print('i is divisible by 2, but not 3 or 5. Meh.')
else:
print('I guess that i is an odd number. Boring.')
i = 5
j = 12
if i < 10 and j > 11:
print('{0} is less than 10 and {1} is greater than 11! How novel and interesting!'.format(i, j))
print('my_string: ', my_string)
if 'a' in my_string or 'e' in my_string:
print('Those are my favorite vowels!')
value = input('Enter a values: ')
value = float(value)
if value < 0:
print('It is negative')
elif value > 0:
print('It is positive')
else:
print('It is zero')
i = 5
while i > 0: # We can write this as 'while i:' because 0 is False!
i -= 1
print('I am looping! {0} more to go!'.format(i))
Be careful you can create infinite loops like:
i = 0
while True:
i += 1
print('I am looping! {0} more to go!'.format(i))
You can use break
function to stop a loop.
i = 5
while True:
i -= 1
print('I am looping! {0} more to go!'.format(i))
if i < -10:
break
We generally use for
loops rather than while
loops:
for i in range(5):
print('I am looping! I have looped {0} times!'.format(i + 1))
range(start = 0, end, by = 1)
function:
print(range(5))
print(range(0,5))
print(range(2,10))
print(range(2,10, 2))
print(list(range(5)))
print(list(range(0,5)))
print(list(range(2,10)))
print(list(range(2,10, 2)))
We can iterate through items of a list, dictionary, set or string:
print(my_list)
# we can write list items
for i in my_list:
print(i)
We some times requires indexes not items themselves:
print(my_list)
# we can write list items
for i in range(len(my_list)):
print('Index: ', i , 'List item: ', my_list[i])
for i in 'this is a string':
print(i)
for i in 'this is a string':
print(i , end = ' | ')
my_list = {'cats', 'dogs', 'lizards', 'cows', 'bats', 'sponges', 'humans'} # Lists all the animals in the world
mammal_list = {'cats', 'dogs', 'cows', 'bats', 'humans'} # Lists all the mammals in the world
my_new_list = [] # empty list
for animal in my_list:
if animal in mammal_list:
# This adds any animal that is both in my_list and mammal_list to my_new_list
my_new_list.append(animal)
print(my_new_list)
for i in range(5):
if i == 4:
break
print(i)
for i in my_dict:
print(i,'movies:',', '.join(my_dict[i]))
Fibonacci function is as follows:
$$ F(n)= \begin{cases} 0 & n>0 \\ 1 & n=1 \\ F(n-1) + F(n-2) & x>1 \\ \end{cases} $$
number = input("# of Fibonacci: ")
number = int(number)
fib = [1,1] # First two fibonacci numbers
for i in range(number-2):
fib.append(fib[i] + fib[i+1])
for n in fib:
print(n, end=', ')
A function is a reusable block of code that you can call repeatedly to make calculations, output data, or really do anything that you want.
def hello_world():
""" Prints Hello, world! """
print('Hello, world!')
hello_world()
for i in range(5):
hello_world()
Variables in the loops and functions are not global. You will have error if you call them:
NameError: name 'in_function_string' is not defined
def see_the_scope():
in_function_string = "I'm stuck in here!"
see_the_scope()
print(in_function_string)
def multiply_by_five(x):
""" Multiplies an input number by 5 """
return x * 5
n = 4
print(n)
print(multiply_by_five(n))
def calculate_area(length, width):
""" Calculates the area of a rectangle """
return length * width
print(calculate_area(2,30))
def sum_values(*args):
sum_val = 0
for i in args:
sum_val += i
return sum_val
print(sum_values(1, 2, 3))
print(sum_values(10, 20, 30, 40, 50))
print(sum_values(4, 2, 5, 1, 10, 249, 25, 24, 13, 6, 4))
def has_a_vowel(word):
"""
Checks to see whether a word contains a vowel
If it doesn't contain a conventional vowel, it
will check for the presence of 'y' or 'w'. Does
not check to see whether those are in the word
in a vowel context.
"""
vowel_list = ['a', 'e', 'i', 'o', 'u']
for vowel in vowel_list:
if vowel in word:
return True
# If there is a vowel in the word, the function returns, preventing anything after this loop from running
return False
my_word = 'catnapping'
if has_a_vowel(my_word):
print('How surprising, an english word contains a vowel.')
else:
print('This is actually surprising.')
Try to define two functions to calculate slope of line passing through two points in 2-dimensional space.
\begin{align} p_1 &= (x_1,y_1) \\ p_2 &= (x_2,y_2) \\ Slope(p_1,p_2) &= \frac{y_2 - y_1}{x_2 - x_1} \end{align}
def point_maker(x, y):
""" Groups x and y values into a point, technically a tuple """
return x, y
a = point_maker(0, 10)
b = point_maker(5, 3)
def calculate_slope(point_a, point_b):
""" Calculates the linear slope between two points """
return (point_b[1] - point_a[1])/(point_b[0] - point_a[0])
print("The slope between a and b is {0}".format(calculate_slope(a, b)))
Lecture notes are improvised. Notebook structure and some codes are taken from Quantopian lectures.