Introduction to Python Programming

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.

Comments

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.

In [1]:
# This is a comment
# These lines of code will not change any values
# Anything following the first # is not run as code

Variables

You should be familiar with the variables. They are the basis of knowledge within our code. We have four common types of variables:

  1. Integer
  2. Float
  3. String
  4. Boolean: True or False

Integers

In [2]:
my_integer = 50
print (my_integer)
print(type(my_integer))
50
<class 'int'>

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:

  1. We use $print()$ function to see/print variable value. Syntax of the function is simple: $print(var\_name)$
  2. We use $type()$ function to learn the type of a variable. Syntax is very simple: $type()$. In order to see the value of the type(my_integer) we printed it:$ print(type(my\_integer))$

Floats

In [3]:
my_float = 1.0
print(my_float, type(my_float))
1.0 <class '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.

Strings

In [4]:
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))
This is a string with single quotes <class 'str'>
This is a string with double quotes <class 'str'>
1 <class 'str'>

We have some points to remark:

  1. You must use single or double quotes to define a string. It doesn,t matter which one you use.
  2. You should be careful about using definitive quotes within the string. check codes below
  3. If you define a integer or float within quotes it will be defined as string, not integer or float.
In [5]:
my_string = 'It's a book'
  File "<ipython-input-5-dbb28ec7469a>", line 1
    my_string = 'It's a book'
                    ^
SyntaxError: invalid syntax

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:

In [6]:
string1 = 'It\'s a book'
print(string1)
string2 = "It's a book"
print(string2)
It's a book
It's a book

You can ignore the quotes mark within string using \, or you can defone it inside a double quote instead.

Booleans

In [7]:
my_bool = True
print(my_bool, type(my_bool))
my_bool = False
print(my_bool, type(my_bool))
True <class 'bool'>
False <class 'bool'>

We can define the variables as True or False as well. True and False notations are case sensitive.

In [8]:
my_bool = True
print(not my_bool)
False

If I add $not$ notation before the $my\_bool$ it becomes $False$ as seen above.

Variable Transformations

You can transform the types of variables if possible. We use:

  1. $int()$: To integer
  2. $float()$: To Float
  3. $str()$: To string

Some examples:

In [9]:
print(int(1.2))
print(int(1.0))
print(int(1.8))
1
1
1
In [10]:
print(int('12'))
12

You will have error if you try this:

In [11]:
print(int('sd'))
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-11-d6bb4da966e4> in <module>()
----> 1 print(int('sd'))

ValueError: invalid literal for int() with base 10: 'sd'

Because 'sd' string is inconvertible to integer.

In [11]:
print(float(1.2))
print(float(1))
1.2
1.0
In [12]:
print(str(2))
print(str(2 * 9))
2
18

Basic Math

You can utilize built-in math functions as seen in cell above:

In [13]:
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 .
Addition:  4
Subtraction:  3
Multiplication:  10
Division:  5.0
Exponentiation:  49
Modulo:  3

You can use math for variables either:

In [14]:
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)
21
343
2.3333333333333335
10
4

Some built-in math functions:

  1. abs()
  2. round()
  3. max()
  4. min()
  5. sum()

Some examples:

In [15]:
print(abs(-5*3))
15
In [16]:
print(round(first_integer / second_integer))
2

Collections

Lists

One of the most useful collection type in Python is the Lists. Example:

In [17]:
my_list = [1, 2, 3]
print(my_list)
print(my_list[0])
print(my_list[2])
[1, 2, 3]
1
3

The first item in the list is indexed as 0.

In [18]:
my_list.append('a string item')
In [19]:
print(my_list)
[1, 2, 3, 'a string item']

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:

In [20]:
print(my_list * 2)
print(my_list + [4,2,7,'2'])
[1, 2, 3, 'a string item', 1, 2, 3, 'a string item']
[1, 2, 3, 'a string item', 4, 2, 7, '2']
In [21]:
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))
[1, 2, 3, 4, 2, 7, 2, 2, 2, 2, 2]
[1, 2, 2, 2, 2, 2, 2, 2, 3, 4, 7]
Total number of 2s in the list:  7

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.

In [22]:
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. 
[2, 2, 3, 4]
[2, 2, 2, 2, 2, 2, 2, 3]
[2, 2, 3, 4, 7]
[1, 2]
In [23]:
my_animals = ['dog', 'cat', 'elephant', 'monkey']
transformed_string = ' '.join(my_animals)
print(transformed_string)
dog cat elephant monkey

Tuples

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.

In [24]:
my_tuple = ('I', 'have', 30, 'cats')
print(my_tuple)
print(type(my_tuple))
('I', 'have', 30, 'cats')
<class '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.

In [25]:
my_tuple[0] = 'He'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-25-1ed78e20056d> in <module>()
----> 1 my_tuple[0] = 'He'

TypeError: 'tuple' object does not support item assignment

Some properties of the tuples can be seen below:

In [26]:
print(my_tuple[0])
print(my_tuple[1])
print(my_tuple[2])
print(my_tuple[3])
I
have
30
cats
In [27]:
my_other_tuple = ('make', 'that', 50)
print(my_tuple + my_other_tuple)
('I', 'have', 30, 'cats', 'make', 'that', 50)
In [28]:
str1, str2, str3, str4 = my_tuple
print(str1)
print(str2)
print(str3)
print(str4)
I
have
30
cats

Sets

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 ({}).

In [29]:
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))
{4, 'man I just LOVE the number 4', 7, 42, 'lizards', 'dogs', 'the number 4'}
<class 'set'>
In [30]:
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
{'cats', 'sponges', 'lizards', 'bats', 'cows', 'dogs'}
In [31]:
print(len(things_i_like))
7
In [32]:
print(len(animal_set))
6

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:

In [33]:
print(my_list)
print('my_list have' , len(my_list), 'items')
[1, 2, 3, 'a string item']
my_list have 4 items

We have some logical operators used in Python similar to the daily words. For example:

In [34]:
print('cats' in animal_set)
print('cats' in animal_list)
print('cats' in my_list)
True
True
False
In [35]:
print(('cats' in animal_list) and ('cats' in my_list))
False
In [36]:
print(('cats' in animal_list) or ('cats' in my_list))
True
In [37]:
print(animal_set | things_i_like) # You can also write things_i_like | animal_set with no difference
{'cats', 4, 'sponges', 'man I just LOVE the number 4', 7, 'lizards', 'bats', 42, 'cows', 'dogs', 'the number 4'}
In [38]:
print(animal_set & things_i_like) # Common elements in both sets.
{'lizards', 'dogs'}

Dictionaries

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.

In [39]:
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"]}
In [40]:
print(type(my_dict))
print(my_dict)
<class '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']}

As an index we use the index name not numbers as lists:

In [41]:
print(my_dict['High Fantasy'])
print(my_dict['Sci-fi'])
print(my_dict['Weird Fiction'])
['Wheel of Time', 'Lord of the Rings']
['Book of the New Sun', 'Neuromancer', 'Snow Crash']
['At the Mountains of Madness', 'The House on the Borderland']

You can add new items to the dictionary:

In [42]:
my_dict["Historical Fiction"] = ["Pillars of the Earth"]
print(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'], 'Historical Fiction': ['Pillars of the Earth']}

String Operations

Well, this part of the lecture is the essential section for aim of this course: Introduce the data science operations.

Remember our string variables:

In [43]:
print(my_string)
print(my_string2)
print(my_string3)
This is a string with single quotes
This is a string with double quotes
1
In [44]:
one_string = my_string + my_string2 + my_string3
print(one_string)
This is a string with single quotesThis is a string with double quotes1

We need to add space between them:

In [45]:
one_string = my_string +' '+ my_string2 +' '+ my_string3
print(one_string)
This is a string with single quotes This is a string with double quotes 1

That's better.

Like lists, sets or dictionaries strings have index as well:

In [46]:
print(one_string[0])
print(one_string[1])
print(one_string[2])
print(one_string[3])
T
h
i
s

We can do similar operations:

In [47]:
print(one_string[:10])
print(one_string[10:])
This is a 
string with single quotes This is a string with double quotes 1
In [48]:
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])
The first letter is:  S
The last letter is:  s
The second to last letter is:  u
The first five characters are:  Super
Reverse it!:  suoicodilaipxecitsiligarfilacrepuS
In [49]:
print('Count of the letter i in Supercalifragilisticexpialidocious: ', my_string.count('i'))
print('Count of "li" in the same word: ', my_string.count('li'))
Count of the letter i in Supercalifragilisticexpialidocious:  7
Count of "li" in the same word:  3

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:

In [50]:
print(one_string.replace(' ', '\n'))
This
is
a
string
with
single
quotes
This
is
a
string
with
double
quotes
1

\n implies new line. So each word is written in a new line. Or:

In [51]:
print(one_string.replace(' ', '|'))
This|is|a|string|with|single|quotes|This|is|a|string|with|double|quotes|1

You can use replace to remove some patterns:

In [52]:
print(one_string.replace('is', ''))
Th  a string with single quotes Th  a string with double quotes 1

May be it is better if we do it like:

In [53]:
print(one_string.replace(' is ', ' '))
This a string with single quotes This a string with double quotes 1

Other common function is split(). It transforms a string into a list:

In [54]:
transformed = one_string.split()
print(type(transformed))
print(transformed)
<class 'list'>
['This', 'is', 'a', 'string', 'with', 'single', 'quotes', 'This', 'is', 'a', 'string', 'with', 'double', 'quotes', '1']

split() function splits spaces and new lines \n by default. You can split with other parameters:

In [55]:
print(one_string.split('is'))
['Th', ' ', ' a string with single quotes Th', ' ', ' a string with double quotes 1']

As you see all is patterns are removed and splited from that points. New list's lenght is:

In [56]:
print(len(one_string.split('is')))
5

Other operations

In [57]:
my_string = "I can't hear you"
print(my_string.upper())
my_string = "I said HELLO"
print(my_string.lower())
I CAN'T HEAR YOU
i said hello
In [58]:
my_string = "{0} - you can add anything between them - {1}".format('Marco', 'Polo')
print(my_string)
Marco - you can add anything between them - Polo
In [59]:
print('There are %s cats in my %s' % (13, 'apartment'))
There are 13 cats in my apartment

Logical Operators and If Statement

In [60]:
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)
1 True
2 False
3 True
4 True
5 False
6 True
7 False
8 True
9 False

Of course you can use variables withing the logical operators:

In [61]:
m = 20
n = 30
print(m < n)
print(m is n)
True
False
In [62]:
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))
Statement 1 truth value: True
Statement 2 truth value: True
Statement 1 and Statement 2: True

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
In [63]:
P = True
Q = False
print(not P)
print(P and Q)
print(P or Q)
print((P or Q) and (not Q) or P)
False
False
True
True

We generally use boolean statements with if statement:

In [64]:
if P and Q:
    print('If P and Q statement is True then print function will work')

Nothing happened. See why:

In [65]:
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)
Because P and Q =  False

General syntax is as follows:

In [66]:
# 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.
True

Some notes about the synyax:

  • After if:, elif: or else: the code should be in for spaces or one tab. You should have noticed the space from lefthand side.
  • You cannot add any other codes between if andelse
  • You can add as many conditions as you want between if and else. So all other conditions will be written as elif(elseif).
In [67]:
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')
All lines in this indented block are part of this block
The variable i is not equal to 5
In [68]:
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 :(")
The variable i has a value of 2
In [69]:
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 is divisible by both 2 and 5! Wow!
In [70]:
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))
5 is less than 10 and 12 is greater than 11! How novel and interesting!
In [71]:
print('my_string: ', my_string)
if 'a' in my_string or 'e' in my_string:
    print('Those are my favorite vowels!')
my_string:  Marco - you can add anything between them - Polo
Those are my favorite vowels!

Exercise - Try this

In [73]:
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')
Enter a values: 10
It is positive

Loops

In [74]:
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))
I am looping! 4 more to go!
I am looping! 3 more to go!
I am looping! 2 more to go!
I am looping! 1 more to go!
I am looping! 0 more to go!

Be careful you can create infinite loops like:

In [ ]:
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.

In [75]:
i = 5
while True:
    i -= 1
    print('I am looping! {0} more to go!'.format(i))
    if i < -10:
        break
I am looping! 4 more to go!
I am looping! 3 more to go!
I am looping! 2 more to go!
I am looping! 1 more to go!
I am looping! 0 more to go!
I am looping! -1 more to go!
I am looping! -2 more to go!
I am looping! -3 more to go!
I am looping! -4 more to go!
I am looping! -5 more to go!
I am looping! -6 more to go!
I am looping! -7 more to go!
I am looping! -8 more to go!
I am looping! -9 more to go!
I am looping! -10 more to go!
I am looping! -11 more to go!

We generally use for loops rather than while loops:

In [76]:
for i in range(5):
    print('I am looping! I have looped {0} times!'.format(i + 1))
I am looping! I have looped 1 times!
I am looping! I have looped 2 times!
I am looping! I have looped 3 times!
I am looping! I have looped 4 times!
I am looping! I have looped 5 times!

range(start = 0, end, by = 1) function:

In [77]:
print(range(5))
print(range(0,5))
print(range(2,10))
print(range(2,10, 2))
range(0, 5)
range(0, 5)
range(2, 10)
range(2, 10, 2)
In [78]:
print(list(range(5)))
print(list(range(0,5)))
print(list(range(2,10)))
print(list(range(2,10, 2)))
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]
[2, 3, 4, 5, 6, 7, 8, 9]
[2, 4, 6, 8]

We can iterate through items of a list, dictionary, set or string:

In [79]:
print(my_list)
# we can write list items
for i in my_list:
    print(i)
[1, 2, 3, 'a string item']
1
2
3
a string item

We some times requires indexes not items themselves:

In [80]:
print(my_list)
# we can write list items
for i in range(len(my_list)):
    print('Index: ', i , 'List item: ', my_list[i])
[1, 2, 3, 'a string item']
Index:  0 List item:  1
Index:  1 List item:  2
Index:  2 List item:  3
Index:  3 List item:  a string item
In [81]:
for i in 'this is a string':
    print(i)
t
h
i
s
 
i
s
 
a
 
s
t
r
i
n
g
In [82]:
for i in 'this is a string':
    print(i , end = ' | ')
t | h | i | s |   | i | s |   | a |   | s | t | r | i | n | g | 
In [83]:
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)
['cats', 'bats', 'cows', 'dogs', 'humans']
In [84]:
for i in range(5):
    if i == 4:
        break
    print(i)
0
1
2
3
In [85]:
for i in my_dict:
    print(i,'movies:',', '.join(my_dict[i]))
High Fantasy movies: Wheel of Time, Lord of the Rings
Sci-fi movies: Book of the New Sun, Neuromancer, Snow Crash
Weird Fiction movies: At the Mountains of Madness, The House on the Borderland
Historical Fiction movies: Pillars of the Earth

Exercise - Fibonacci Numbers

  1. Ask user to how many fibonacci numbers does he/she wants.
  2. Then start to print fibonacci numbers as many as wanted. Like: 1, 1, 2, 3, 5, 8, 13, 21…

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} $$

In [86]:
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=', ')
# of Fibonacci: 50
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 1134903170, 1836311903, 2971215073, 4807526976, 7778742049, 12586269025, 

Functions

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.

In [87]:
def hello_world():
    """ Prints Hello, world! """
    print('Hello, world!')

hello_world()
Hello, world!
In [88]:
for i in range(5):
    hello_world()
Hello, world!
Hello, world!
Hello, world!
Hello, world!
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

In [89]:
def see_the_scope():
    in_function_string = "I'm stuck in here!"

see_the_scope()
print(in_function_string)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-89-fa2eb2799cc3> in <module>()
      3 
      4 see_the_scope()
----> 5 print(in_function_string)

NameError: name 'in_function_string' is not defined
In [90]:
def multiply_by_five(x):
    """ Multiplies an input number by 5 """
    return x * 5

n = 4
print(n)
print(multiply_by_five(n))
4
20

Area Calculator

In [91]:
def calculate_area(length, width):
    """ Calculates the area of a rectangle """
    return length * width
In [92]:
print(calculate_area(2,30))
60

Unknown number of arguments in a function

In [93]:
def sum_values(*args):
    sum_val = 0
    for i in args:
        sum_val += i
    return sum_val
In [94]:
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))
6
150
343

Has-A-Vowel Function

In [95]:
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
In [96]:
my_word = 'catnapping'
if has_a_vowel(my_word):
    print('How surprising, an english word contains a vowel.')
else:
    print('This is actually surprising.')
How surprising, an english word contains a vowel.

Slope of two points at two dimensional space

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}

In [97]:
def point_maker(x, y):
    """ Groups x and y values into a point, technically a tuple """
    return x, y
In [98]:
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)))
The slope between a and b is -1.4

Resources

Lecture notes are improvised. Notebook structure and some codes are taken from Quantopian lectures.