Python Programming Guide
Python Programming Guide
JUBRAN AKRAM
A tutorial AT
Contents
1   Introduction                                                                                                                                                                   3
    1.1 Programming language . . . . . . . . . . . . . . . . . . . . .                                                     .   .   .   .   .   .   .   .   .   .   .   .   .   .   3
         1.1.1 Python programming . . . . . . . . . . . . . . . . . .                                                      .   .   .   .   .   .   .   .   .   .   .   .   .   .   3
    1.2 Installing python . . . . . . . . . . . . . . . . . . . . . . . . .                                                .   .   .   .   .   .   .   .   .   .   .   .   .   .   5
    1.3 Code editor and Interactive development environment (IDE)                                                          .   .   .   .   .   .   .   .   .   .   .   .   .   .   5
3 Data types/structures 10
4   Strings                                                                                                                                                                        12
    4.1 Access substrings . . . . . . . . . . . . . . . . . . . . . . .                                            .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   12
    4.2 Split and join strings . . . . . . . . . . . . . . . . . . . . .                                           .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   13
    4.3 Find the lowest and highest index of a substring . . . . .                                                 .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   14
    4.4 Find and replace a substring . . . . . . . . . . . . . . . . .                                             .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   14
    4.5 How many times a substring appeared in a given string?                                                     .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   14
    4.6 Edit the case in a string . . . . . . . . . . . . . . . . . . . .                                          .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   14
    4.7 Format a string . . . . . . . . . . . . . . . . . . . . . . . .                                            .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   15
5   Operators                                                                                                                                                                      16
    5.1 Arithmetic operators . . . . . . . . . .                       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   16
    5.2 Comparison operators . . . . . . . . .                         .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   17
    5.3 Equality operators . . . . . . . . . . .                       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   17
    5.4 Logical/Boolean operators . . . . . . .                        .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   17
    5.5 Operator precedence (PEMDAS rule) .                            .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   18
                                                                       1
    6.7    Unpack a sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
7   Dictionaries                                                                                                                                                                 25
    7.1 Create dictionaries . . . .      .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   25
    7.2 Access values . . . . . . .      .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   26
    7.3 Add/remove and update            .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   27
    7.4 Dictionary operators . . .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   28
8   Sets                                                                                                                                                                         30
    8.1    Create sets . . . . . . . . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   31
    8.2    Add elements or another set       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   31
    8.3    Remove elements . . . . . .       .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   32
    8.4    Set operations . . . . . . . .    .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   32
9 if-elif-else 34
10 Loops                                                                                                  38
   10.1 While loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
   10.2 For loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
11 Comprehensions 44
12 Functions                                                                                        47
   12.1 Anonymous functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
13 Import modules                                                                                      50
   13.1 Import modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
14 Decorators 52
15 Read/write files                                                                                 54
   15.1 Third-party modules/libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
17 Classes                                                                                       60
   17.1 Four principles of object-oriented programming . . . . . . . . . . . . . . . . . . . . . 62
18 Summary 66
                                                                     2
Chapter 1
Introduction
This tutorial is made from my Python Programming for Everyone video series which is available
on YouTube link. It is not only suitabe for a complete beginner who wants to learn python pro-
gramming, but also for experienced programmers. Using many examples, it explains the basics as
well as some useful tricks to write python codes more effectively.
                                                  3
Figure 1.1: Web search results on top 10 programming languages that are more desirable to learn in 2020.
                                                   4
  Figure 1.2: Programming languages types and levels (source: www.learncomputerscienceonline.com)
                                                  5
a debugger to write programs efficiently. Some examples of the IDEs include Spyder, Eclipse,
PyCharm and Visual Studio Code.
You can choose to work either in a code editor or an IDE and will still be able to follow the exam-
ples.
Summary
In this chapter, we learned that python is an interpreted, high-level and general-purpose pro-
gramming language. We then discussed what are the interpreted, high-level and general-purpose
programming languages. We then described different ways of installing python on our machines.
Finally, we explained the difference between a code editor and an IDE.
                                                6
    Chapter 2
    2.1      Comments
    As programs get bigger and more complicated, they become more difficult to read. Comments are
    very useful for organizing and explaining the programs and also for keeping notes for yourself
    and for others to follow your program easily, thus improving the code readibility.
    There are two types of comments: 1. single-line comments 2. multi-line comments
We can also start a single-line comment on the right of the code written on a given line.
                                                     7
    We can also write multiline comments in triple quotes. These are similar to multi-line strings but
    can be used as comments in python programming. The Style Guide for Python Code states that
    each script should start with a docstring that explains the script’s purpose.
[5]: ' This is a \nmulti-line comment. you can write as\nmany lines as you want to
     ...'
    2.2    print()
          The print() function allows showing messages or results on the screen or another stan-
          dard output device.
    Let’s look at a simple example, in which we wish to print “Hello World!” on the screen. To do
    this, we write “Hello World” in quotes as the argument of the print function. The arguments are
    written inside the parenthesis of a function.
    Hello, World!
    We can also write “Hello World” as a string variable, let’s say greeting, and use it as an argument
    of the print function.
    Hello, World!
    We can also use any number as the argument
    2.5
    Now let’s say we want to print multiple texts at the same time, for example, “Hello” and “How
    are you?”. The print() function will show both items together with a space as the separator.
                                                    8
[10]: print('Hello', 'how are you?', sep=', ')
      print('Hello', 'how are you?', sep='\n')
     Summary
     In this chapter, we learned about how to write single-line and multi-line comments in python. We
     also learned how to use print() function to show messages or results on the screen effectively.
                                                      9
    Chapter 3
Data types/structures
    Data types are simply variables that we use to reserve some space in memory. Commonly used
    data types in python are as follows:
                                                     10
      dir(data_object), horizontal_line, sep='\n')
print(help(dict.update))
update(...)
    D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
    If E is present and has a .keys() method, then does: for k in E: D[k] =
E[k]
    If E is present and lacks a .keys() method, then does: for k, v in E: D[k]
= v
    In either case, this is followed by: for k in F: D[k] = F[k]
None
Change the data_object in the above example to a tuple, list or set and see their class methods
and properties.
Summary
In this chapter, we learned about the basic data types/structures used in python programming.
We also learned how to find the class of a given data structure, if unknown. In addition, we
learned how to find more details on the properties and methods in a specific object class.
                                              11
    Chapter 4
Strings
[4]: str_1 = 'Hello' # each character can be accessed using its respective indices
      ,→i.e. str_1[index]
str_1[0]
[4]: 'H'
[5]: 5
                                                     12
      print(str_1[-1])          # last index
      print(str_1[::2])         # all values at indices with an interval of 2 [0, 2, ..
       ,→upto the length of    the sequence]
      print(str_1[1:5:2])       # start at 1 and then increment by 2 [start:stop:step]
     el
     Hel
     lo
     o
     Hlo
     el
[18]: ','.join(str_1.split(','))
[19]: '-'.join(str_1.split(','))
                                                    13
          'store in a list']
[23]: str_1.find('o') # first time the character 'o' appears in str_1 is at index 4
       ,→(H->0, e->1, l->2, l->3, o->4)
[23]: 4
[22]: str_1.rfind('o') # last time the character 'o' appears in str_1 ist at index 16
[22]: 16
[24]: str_2 = "Hello Jubran, are you playing soccer this summer?"
      str_2.replace('soccer','rugby') # this will replace soccer with rugby in str_2
[25]: str_2.count('o')
[25]: 3
                                                   14
     Python Programming Is Fun!
     pYTHON PROGRAMMING IS FUN!
[31]: '1,000,000'
     Summary
     In this chapter, we learned about how to use strings and format texts in python.
                                                    15
    Chapter 5
Operators
    There exists a wide variety of operators. Here, we will only discuss the following operators:
      1. Arithmetic operators
      2. Comparison operators
      3. Equality operators
      4. Logical or Boolean operators
    Other operators e.g. sequence, set and dictionary operators will be discussed in the later chapters.
    Addition: 40 + 15                     =          55
    Subtraction: 40 - 15                  =          25
    Multiplication: 40 * 15               =          600
    True division: 40 / 15                =          2.67
    float division: 40 // 15              =          2
    Modulo: 40 % 15                       =          10
    Exponentiation: 40 ** 2               =          1600
                                                    16
     5.2       Comparison operators
     The comparison operators allow us to see if one variable is greater or smaller than another vari-
     able.
[11]: print(f'{num_1}      is   greater   than   {num_2}:   {num_1 > num_2}')
      print(f'{num_1}      is   greater   than   or equal   to {num_2}: {num_1 >= num_2}')
      print(f'{num_1}      is   smaller   than   {num_2}:   {num_1 < num_2}')
      print(f'{num_1}      is   smaller   than   or equal   to {num_2}: {num_1 <= num_2}')
      print(num_1 < num_2 or num_1 > 20)                     # atleast one statement should be true
       ,→for a true output
     True
     True
     False
                                                        17
     5.5     Operator precedence (PEMDAS rule)
     Python follows PEMDAS rule. PEMDAS is an acronym for paranthesis, exponents, multiplication,
     division, addition and subtraction. As per this rule, anything within paranthesis is evaluated first,
     then the exponents, and then multiplication and divisions (both have the same level, it does not
     matter if multiplication is done first or division), followed by addition and subtraction (both have
     the same level).
[14]: exp_1 = (2 + 3)**2          # in this anything inside the parenthesis is
       ,→evaluated first, which equals 5 and then the exponent
      print (exp_1, exp_2)        # exp_1 = 25, whereas exp_2 = 11, so it's important
       ,→to follow the correct operator precedence
25 11
     Summary
     In this chapter, we learned about arithmetic operators, comparison operators, equality operators,
     and boolean operators. These will be used a lot in routine computations and conditional pro-
     gramming. In addition, we learned about the PEMDAS rule, which python follows for operator
     precedence.
                                                      18
    Chapter 6
---------------------------------------------------------------------------
            <ipython-input-3-34aad2d0de11> in <module>
              1 tuple_1 = ('apples', 'bananas', 'oranges', 'grapes')
        ----> 2 tuple_1[1] = 'avacados'
                                                      19
              TypeError: 'tuple' object does not support item assignment
     ooooops! cannot change items in tuples as they are immutable data structures.
     Now you must be thinking that why do we use tuples then? Tuples are good for storing parame-
     ters that we do not want to change in your program. Tuples use less memory as compared to the
     lists and creating a tuple is faster than creating a list.
     []
     []
     ['apples', 1.5, 2, [1, 3, 5], {'a': 1, 'b': 4}]
print(list_1)
                                                    20
[17]: list_1.pop()                             # use the pop() method to remove the last item
       ,→in the list
[17]: 'raspberries'
[19]: list_1.remove('oranges')
      print(list_1)
     ['apples', 'blueberries']
     Finally, we can use the clear() method to remove all items from the list. This will result in an empty
     list.
[21]: list_1.clear()
      print(list_1)
[]
print(list_1)
[1, 2, 4, 6, 7, 9]
[9, 7, 6, 4, 2, 1]
                                                      21
[25]: list_1.reverse()             # flips the order of list items
      print(list_1)
[1, 2, 4, 6, 7, 9]
[1, 3, 5, 2, 4]
[2, 4, 2, 4, 2, 4, 2, 4]
     True
     True
     We can also use the slicing feature
1 5
[30]: print(list_1[:2], list_1[-2:]) # first two and last two items of list_1
[1, 3] [3, 5]
     ()
     ()
     ('apples', 1, 2, [1, 2, 3], {'a': 1, 'b': 4})
     We can convert a tuple to a list using the list() constructor, and a list to a tuple using the tuple()
     constructor.
                                                      22
[32]: list(tuple_3)
     {'a': 1, 'b': 4}
     now what if we only want to get the first item as one variable and the remaining items as another
     variable
[34]: a, b = tuple_3
---------------------------------------------------------------------------
               <ipython-input-34-abd212451719> in <module>
           ----> 1 a, b = tuple_3
     ooooooops! a ValueError: too many values to unpack —- we can correctly do this using an asterisk
     ( * ) before b
[35]: a, *b = tuple_3
      print(b)
[36]: a, *_ = tuple_3
      print(a)
     apples
     What if we are interested in getting the first two items and the last items only?
                                                      23
apples
1
{'a': 1, 'b': 4}
Summary
In this chapter, we learned how to create lists and tuples, and add, or remove items in the list or
concatenate different lists. In addition, we learned about the sequence operators and unpacking
sequences.
                                                24
    Chapter 7
Dictionaries
          A dictionary is a collection of key/value pairs, with the requirement that the keys are
          unique.
    A dictionary is created by placing all the key:value pairs inside the braces{}.
    Dictionaries are often called maps, hashmaps, lookup tables or associative arrays in other pro-
    gramming languages. These are mutable data structures, meaning we can easily add or remove
    items and update their values. Since the keys of a dictionary are required to be unique, adding
    a key–value item whose key is the same as an existing key will simply update the key’s current
    value with the new value.
    From Python 3.7, dictionaries preserve the insertion order by default. Updating the keys does not
    affect their order and if we delete a key and add it again, it will be inserted at the end.
    We use keys to access their associated data values in the dictionaries. In the case of lists, we
    used numeric indices to access data, however dictionaries have no notion of index position and
    therefore, cannot be sliced.
    Why are dictionaries useful? Instead of searching for a value in the entire list, we can extract any
    value from a dictionary using its associated key, thus we can efficiently search, insert, and delete
    any object associated with a given key.
                                                     25
     value_1 = [2, 'apple', [1, 2, 3], (2, 5)]
     dict_4 = dict(zip(key_1, value_1))
     # using fromkeys() method, which requires keys as input, and a default value to
      ,→initialize each key, if not given, None
    {}
    {}
    {'a':   1, 'b': 4}
    {'a':   2, 'b': 'apple', 'c': [1, 2, 3], 'd': (2, 5)}
    {'a':   None, 'b': None, 'c': None, 'd': None}
    {'a':   0, 'b': 0, 'c': 0, 'd': 0}
[4]: (2, 5)
[5]: dict_1['e']
---------------------------------------------------------------------------
              <ipython-input-5-911708c4fe99> in <module>
          ----> 1 dict_1['e']
KeyError: 'e'
    ooooops! KeyError — we can avoid this using the get() method. If the key is not available, it will
    return None. We can also customize the default value.
[7]: print(dict_1.get('e'))
None
not available
                                                   26
     7.3    Add/remove and update
[10]: dict_1 = {'a': 2, 'b': 'apple', 'c': [1, 2, 3], 'd': (2, 5)}
      # adding new values
      dict_1['e'] = 3.2
      print(dict_1)
     {'a': 2, 'b': 'apple', 'c': [1, 2, 3], 'd': (2, 5), 'e': 3.2}
     We can also use the update() method to update values of existing keys and add new key:value
     pairs
     {'a': 4, 'b': 'apple', 'c': [1, 2, 3], 'd': (2, 5), 'e': 3.2, 'f': 'soccer'}
     To remove a key, we can use the pop() method
[12]: dict_1.pop('f')
      print(dict_1)
{'a': 4, 'b': 'apple', 'c': [1, 2, 3], 'd': (2, 5), 'e': 3.2}
[13]: dict_1.pop('f')
---------------------------------------------------------------------------
               <ipython-input-13-99356867615f> in <module>
           ----> 1 dict_1.pop('f')
KeyError: 'f'
     ooooops! a KeyError . . . since we have already removed this key. To avoid this error, we can set a
     default message to display
To remove the last key:value pair from the dictionary, we can use the popitem() method
[15]: dict_1.popitem()
      print(dict_1)
                                                     27
     {'a': 4, 'b': 'apple', 'c': [1, 2, 3], 'd': (2, 5)}
     We can also use the del key to delete a key from the dictionary
[17]: dict_1.clear()
      print(dict_1)
{}
True
False
True
True
                                                    28
[24]: dict_items([('a', 1), ('b', 4)])
[25]: # to check the number of key:value pairs in the dictionary we can use the len()
       ,→method
len(dict_1)
[25]: 2
     Summary
     In this chapter, we learned how to create dictionaries, access values, add/remove or update key-
     values. In addition, we learned about different dictionary operators.
                                                   29
Chapter 8
Sets
                                                 30
    8.1     Create sets
[2]: # The only way to create an empty set is using the set() constructor. We cannot
      ,→use empty {} as this will create a dictionary.
     set_1 = set()
     print(set_1)
set()
[3]: a = {}
     type(a)
[3]: dict
    {1, 3, 5, 7}
    what just happened . . . . you can include repeated values, however set will only store unique
    elements.
    We can also use the set() constructor with iterables
[5]: set_3 = set('aeiou')
     print(set_3)
    {8, 2, 4, 6}
    don’t worry .. set is an unordered collection
set()
[8]: set_1.add(2)
     print(set_1)
{2}
                                                    31
[9]: set_1.add(4)
     print(set_1)
     {2, 4}
     To add another set, we use the update() method
[10]: set_1.update(set_2)
      print(set_1)
{1, 2, 3, 4, 5, 7}
{1, 2, 4, 5, 7}
{1, 4, 5, 7}
{4, 5, 7}
[14]: # union
      print(set_1.union(set_2))
      # another way
      print(set_1 | set_2)
     {1, 3, 4, 5, 7}
     {1, 3, 4, 5, 7}
[15]: # intersection
      print(set_1.intersection(set_2))
      # another way
      print(set_1 & set_2)
                                                  32
     {5, 7}
     {5, 7}
[16]: # difference
      print(set_1.difference(set_2))
      # another way
      print(set_1 - set_2)
     {4}
     {4}
     {4, 5, 7}
     True
     False
     True
     True
     Summary
     In this chapter, we learned about creating empty and non-empty sets, adding/removing elements
     and updating sets. In addition, we learned about different set operations.
                                                  33
Chapter 9
if-elif-else
                                                 34
    Figure 9.1: A flowchart to explain the decision-control instructions for the above example (buy a bag of
    chips from a convenience store).
[8]: percentage_score = 75
                                                      35
    Congratulations! You passed.
    Ternary operators allow us to write the above multi-line if-else statement in one line > statement
    if condition else statement
[9]: print("Congratulations! You passed.") if percentage_score >= 40 else
      ,→print("Sorry, Try again.")
[5]: percentage_score = 65
     if 90 <= percentage_score <= 100:
         print("The letter grade is A+")
     elif 80 <= percentage_score <= 89:
         print("The letter grade is A")
     elif 75 <= percentage_score <= 79:
         print("The letter grade is B+")
     elif 70 <= percentage_score <= 74:
         print("The letter grade is B")
     elif 65 <= percentage_score <= 69:
         print("The letter grade is B-")
     elif 60 <= percentage_score <= 64:
         print("The letter grade is C+")
     elif 55 <= percentage_score <= 59:
         print("The letter grade is C")
     elif 50 <= percentage_score <= 54:
         print("The letter grade is C-")
     elif 40 <= percentage_score <= 49:
         print("The letter grade is D")
     else:
         print("The letter grade is F")
                                                   36
     Alternative Solution – instead of using the full interval notation, we will use “>=” in the condi-
     tions
[12]: percentage_score = 95
      if percentage_score >= 90:
          print("The letter grade is       A+")
      elif percentage_score >= 80:
          print("The letter grade is       A")
      elif percentage_score >= 75:
          print("The letter grade is       B+")
      elif percentage_score >= 70:
          print("The letter grade is       B")
      elif percentage_score >= 65:
          print("The letter grade is       B-")
      elif percentage_score >= 60:
          print("The letter grade is       C+")
      elif percentage_score >= 55:
          print("The letter grade is       C")
      elif percentage_score >= 50:
          print("The letter grade is       C-")
      elif percentage_score >= 40:
          print("The letter grade is       D")
      else:
          print("The letter grade is       F")
     Summary
     In this chapter, we learned about writing decision-control instructions in python using if-elif-else
     statements.
                                                     37
    Chapter 10
Loops
     while counter <= max_iter:       # the loop will print "Hello World!" as long as
      ,→counter is smaller than or equal to max_iter
    1        Hello   World!
    2        Hello   World!
    3        Hello   World!
    4        Hello   World!
                                                   38
    5         Hello   World!
    6         Hello   World!
    7         Hello   World!
    8         Hello   World!
    9         Hello   World!
    10        Hello   World!
     Example 2 Find out if an object(value) exists in a sequence.
     counter = 0
     while counter < len(random_num):               # condition: run the loop as long
      ,→as counter is smaller than length of sequence
counter += 1
                                                          39
[10]: random_num = [2, 7, 4, 5, 9, 3, 6]
      iter_num = iter(random_num)                      # get an iterator
      target_num = 10
           num = next(iter_num, None)       # next function only takes one element from
       ,→the sequence, each time it is called.
           if num is None:
               print("The object does not exist...")
               break
           elif num == target_num:
               print("The object exists...")
               break
     Let’s look at some examples of how for loops are used in python . . .
     Example 1 Find out if an object(value) exists or does not exist in a sequence.
      for num in random_num: # each iteration, num picks a value in random_num -- 1st
       ,→value at 1st iter -- 2nd value at 2nd iter, ...
                                                           40
[15]: random_num = [2, 7, 4, 5, 9, 3, 6]
      target_num = 3
           if num == target_num:
               print(f"The object exists at index {index}.")
               break
      else:
           print("The object does not exist...")
      print(50*"--")
      # 3b .......................................................................
      for index, num in enumerate(random_num, 3):
          print(index, num, sep='-->')
     7-->6
     6-->3
     5-->9
     4-->5
     3-->4
     2-->7
     1-->2
     --------------------------------------------------------------------------------
     --------------------
     3-->2
     4-->7
     5-->4
     6-->5
     7-->9
     8-->3
     9-->6
                                                   41
     Example 4 Print the element-by-element sum of three lists.
      list_sum = []
      for vals in zip(list_1, list_2, list_3):
           sum_vals = sum(vals)
           list_sum.append(sum_vals)
           print(f"{vals[0]} + {vals[1]} + {vals[2]} ------> {sum_vals}")
     2   +   1   +   9   ------>   12
     7   +   2   +   6   ------>   15
     4   +   4   +   8   ------>   16
     5   +   3   +   5   ------>   13
     9   +   7   +   4   ------>   20
     3   +   9   +   3   ------>   15
     6   +   6   +   7   ------>   19
     Example 5 Print the keys and their correspondig values from a dictionary
                                                    42
     print(count, "\t\t------>\t\t", list_1[count])
print(50*"--")
# starting from index = 4
for count in range(4, len(list_1)):
    print(count, "\t\t------>\t\t", list_1[count])
print(50*"--")
# print everything with an interval of 2
for count in range(0, len(list_1), 2):
    print(count, "\t\t------>\t\t", list_1[count])
0               ------>          2
1               ------>          7
2               ------>          4
3               ------>          5
4               ------>          9
5               ------>          3
6               ------>          6
--------------------------------------------------------------------------------
--------------------
4               ------>          9
5               ------>          3
6               ------>          6
--------------------------------------------------------------------------------
--------------------
0               ------>          2
2               ------>          4
4               ------>          9
6               ------>          6
Summary
In this chapter, we learned about the while and for loops using many examples. We also used
len(), iter(), next(), enumerate() and zip() functions. In addition, we have used the print() to show
different ways of presenting the text.
                                                 43
    Chapter 11
Comprehensions
     print(50*"--")
     # using list comprehensions---------------------------------------------------
     squares_1 = [val*val for val in list_1]
     [print(square, '\t=\t', square_1) for square, square_1 in zip(squares,
      ,→squares_1)]
    square of 2             ------>          4
    square of 7             ------>          49
    square of 4             ------>          16
    square of 5             ------>          25
    square of 9             ------>          81
    square of 3             ------>          9
    square of 6             ------>          36
    --------------------------------------------------------------------------------
    --------------------
                                                   44
    4       =         4
    49      =         49
    16      =         16
    25      =         25
    81      =         81
    9       =         9
    36      =         36
     print(50*"--")
     # using the list comprehensions--------------------------------------------
     dict_1 = dict(zip(list_2, list_1))
     print("Case: comprehensions -- just created a dictionary", dict_1, sep='\n')
     [dict_1.update({key: val}) for key, val in zip(update_key, update_val)]
     print("Case: comprehensions -- updated the dictionary", dict_1, sep='\n')
                                                 45
dict_1 = dict(zip(list_2, list_1))
# create a new dictionary with a square of values in list_1
dict_2 = {key:val*val for key, val in dict_1.items()}
print("original dictionary 1", dict_1, sep='\n')
print("new dictionary containing square values using comprehensions",
      dict_2, sep='\n')
original dictionary 1
{'a': 2, 'b': 7, 'c': 4, 'd': 5}
new dictionary containing square values using comprehensions
{'a': 4, 'b': 49, 'c': 16, 'd': 25}
Summary
In this chapter, we learned about how to make our python code more concise using comprehen-
sion constructs.
                                            46
    Chapter 12
Functions
    As programs get bigger and more complicated, they become more difficult to read and debug. To
    prevent redundant logic, manage code complexity and improve the code readability, the recom-
    mended practice is to write parts of code as functions that can be reused without writing the entire
    block of code.
         A function is a group of related statements that can be called together to perform a
         specific task.
    In python, a function is typically written as:
              def function_name(input=optional):
                  statement(s)
                  return output(optional)
    As you can see, a function may or may not take input parameters, and also may or may not return
    an output value.
    Example 1: Write a function to say Hello.
[1]: def say_hello():          # this function does not take any input parameters
          print("I'm a function and I say Hello.")       # this function also does not
      ,→return any output value
                                                     47
     Hello Jubran, how are you?
     Hello Jordan, how are you?
     Example 3: Write a function to convert temperature measurements from Fahrenheit to Celsius.
[8]: print(f'{fahrenheit_to_celsius(-32):.2f}')
-35.56
print(f'{celsius_temp:.2f}')
     -35.56
     Example 4: If a project has a earned value of $10,000 but actual costs were $9,500, find the cost
     performance index (CPI)
return earned_value/actual_cost
      else:
           print(f"CPI = {cpi:.2f}: project is over budget -- do something!")
50
[15]: print(rectangle_area(10))       #it will still work as the function will use the
       ,→default value for width, which is 3m
     30
     Example 6: Write a function with positional arguments.
                                                    48
[16]: def sum_of_squares(*args):                #it allows varying number of positinal
       ,→arguments
     84
     Example 7: Write a function with keyword arguments.
[24]: print(polynomial(5))
36
     Summary
     In this chapter, we learned about writing functions that help in managing code complexity and
     improving code readablity.
                                                  49
    Chapter 13
Import modules
    For easier maintenance, it is important to split a longer program into several files that can be im-
    ported later into a main program. Like functions, modules also help in improving code readability
    and managing code complexity.
           A module is a file containing Python definitions and statements.
    It’s easier to write modules in python. For example, I wrote the following code in a file and saved
    it as temp_calc.py. This is a module, which I can import for use, when required.
     def celsius_to_fahrenheit(temp_celsius):
         return 1.8*temp_celsius + 32
In addition to functions, we can also specify constants, variables, or classes in the modules.
    36.11°C
    we can also import a module explicitly by alias, for example
36.11°C
                                                     50
    we can also import particular items from a module
print(f'{fahrenheit_to_celsius(97):.2f}\u00b0C')
    36.11°C
    Let’s say we want to import all of the module contents into the local namespace.
    36.11°C
    When writing programs in Python, we often use/import many built-in modules such as math,
    datetime . . . or third-party modules such as numpy, matplotlib, pandas, . . . so you will be using
    these or similar commands a lot in your programs
    Summary
    In this chapter, we learned about writing modules in Python, as well as importing modules in our
    programs for use, when required.
                                                    51
    Chapter 14
Decorators
    Decorators are design patterns that augment the behavior of an existing object, thus decorating
    the original behavior.
    Let’s look at the following function
    36
    We can also use the map() function to do element-by-element computation for an input list
[4]: x = [1, 2, 3, 4, 5]
     y = map(compute_polynomial, x)
     print(list(y))
                                                     52
                  return [fun(arg) for arg in args]
              else:
                  raise TypeError("Missing arguments")
          return inner           # return the inner function
[7]: @list_mapper
     def compute_polynomial(x):
         return x**2 + 2*x + 1
[10]: @list_mapper
      def squares(x):
          return x**2
[11]: print(squares(*x))
     Summary
     In this chapter, we learned about decorators that augment the behavior of an existing object.
                                                    53
    Chapter 15
Read/write files
    Often times, we are required to read data from files (text, csv, json, . . . ) or save data to these files
    in our programs. Let’s see how to read/write files in python:
    Example 1 Write a text file, storing greetings to ten different persons and then read it.
     # with context manager, we don't need to worry about closing the file.
     with open('greetings.txt', 'w') as file:             # mode, w = write , a =
      ,→append, r= read
print(file.read())
                                                       54
          print(file.read(100))                                  # read first 100 characters only
print(file.readlines())
     ['Hello Jubran, how are you?\n', 'Hello Aamir, how are you?\n', 'Hello John, how
     are you?\n', 'Hello Michael, how are you?\n', 'Hello David, how are you?\n',
     'Hello Maryam, how are you?\n', 'Hello Christina, how are you?\n', 'Hello Maria,
     how are you?\n', 'Hello Jordan, how are you?\n', 'Hello Jasmine, how are
     you?\n']
     we can remove the newline character (\n) using splitlines() with read, if required . . .
print(file.read().splitlines())
     ['Hello Jubran, how are you?', 'Hello Aamir, how are you?', 'Hello John, how are
     you?', 'Hello Michael, how are you?', 'Hello David, how are you?', 'Hello
     Maryam, how are you?', 'Hello Christina, how are you?', 'Hello Maria, how are
     you?', 'Hello Jordan, how are you?', 'Hello Jasmine, how are you?']
     Example    2     Load    a   csv   file  (I   have     a    csv           file    downloaded   from
     https://people.sc.fsu.edu/~jburkardt/data/csv/biostats.csv).
                                                       55
     Elly       |              "F"        |              30   |                66        |
     124
     Fran       |              "F"        |              33   |                66        |
     115
     Gwen       |              "F"        |              26   |                64        |
     121
     Hank       |              "M"        |              30   |                71        |
     158
     Ivan       |              "M"        |              53   |                72        |
     175
     Jake       |              "M"        |              32   |                69        |
     143
     Kate       |              "F"        |              47   |                69        |
     139
     Luke       |              "M"        |              34   |                72        |
     163
     Myra       |              "F"        |              23   |                62        |
     98
     Neil       |              "M"        |              36   |                75        |
     160
     Omar       |              "M"        |              38   |                70        |
     145
     Page       |              "F"        |              31   |                67        |
     135
     Quin       |              "M"        |              29   |                71        |
     176
     Ruth       |              "F"        |              28   |                65        |
     131
                                                    56
     7    Hank              "M"          30                  71              158
     8    Ivan              "M"          53                  72              175
     9    Jake              "M"          32                  69              143
     10   Kate              "F"          47                  69              139
     11   Luke              "M"          34                  72              163
     12   Myra              "F"          23                  62               98
     13   Neil              "M"          36                  75              160
     14   Omar              "M"          38                  70              145
     15   Page              "F"          31                  67              135
     16   Quin              "M"          29                  71              176
     17   Ruth              "F"          28                  65              131
     saving a csv file is also a lot easier. . .
     Summary
     In this chapter, we learned about reading/writing text and csv files. Using third-party libraries
     such as numpy or pandas makes the reading/writing of files a lot easier.
                                                            57
    Chapter 16
    Matplotlib is a plotting library for the Python programming language and its numerical mathe-
    matics extension NumPy. Here, I’ll show a few examples only. For more details and examples,
    you can check https://matplotlib.org/
    Example 1 Plot a line graph for the polynomial y = x2 + 2x + 1
                                                  58
    Example 2 Generate 1000 uniformly distributed random numbers between 0 and 1 and plot their
    histogram.
    Summary
    In this chapter, we just briefly introduced Matplotlib, which is a key library for plotting and data
    visualization. For more examples and details, check https://matplotlib.org/
                                                    59
    Chapter 17
Classes
[1]: a = 2
     print(type(a))
<class 'int'>
    <class 'function'>
    since integers, floats, lists, functions,.. and so on, are objects in python, we can assign each of them
    to variables. This brings additional flexibility to python programming language. For example,
[4]: f = my_work
     f()
this is my work
---------------------------------------------------------------------------
                                                      60
                <ipython-input-6-2a7ab4279cec> in <module>
                  1 # now if we run my_work(), it'll generate error
            ----> 2 my_work()
     this is my work
            A class is kind of a template that allows including behavior(methods) and
            state(variables/data/attributes) to a particular object.
     When objects are created by a class, they inherit the class attributes and methods. Let’s see how
     we can write a simple class
               self.doors = args[1]
               self.tires = args[2]
           #------------------------methods/behavior-------------------------------
           def normal_brake(self):
               return "slowing down ..."
            def hard_brake(self):
                return "screeeeeeeeeech!"
            def turn_right(self):
                return "turning right"
                                                    61
            def turn_left(self):
                return "turning left"
            def use_front_wipers(self):
                return "cleaning windscreen ..."
           def make_noise(self):
               pass                         #in python, pass key is used as a placeholder
       ,→for future use
[43]: car                        #this invokes the __repr__() method and shows the text
       ,→to recreate the instance
[43]: Vehicle('red', 4, 4)
                                                     62
     Ummm. . . . . . .not sure what I mean. Let’s try to explain this by writing some code.
     Suppose we want to design a gasoline car model. Since a car belongs to the vehicle category, it
     should share the same basic attributes (it should have a color, a number of tires, and doors, . . . )
     and same behavior (it should be able to turn, stop, drive, . . . ). In this case, we can simply create
     another subclass Gasolinecar which will inherit the attributes and methods from the Vehicle class
[67]: class GasolineCar(Vehicle):        # GasolineCar is the derived class whereas
       ,→Vehicle is the base class --> Inheritance
               return "Vrrrrrooooooooom"
           def get_engine(self):         # getter method to display the private
       ,→variable (.__engine)
               print(self.__engine)
           def set_engine(self, engine): # setter method to change the private variable
               self.__engine = engine
Vrrrrrooooooooom
[50]: GasolineCar('red', 4, 4)
                                                      63
[68]: class ElectricCar(Vehicle):
           def __init__(self, *args):
               super().__init__(*args)
               self.__engine = 'motor'
           def make_noise(self): #same method as used in GasolineCar class, but
       ,→different function specific to this class ...
               return "I can only make artificial noise under certain conditions ..."
       ,→# ... (an example of polymorphism)
           def get_engine(self):
               print(self.__engine)
           def set_engine(self, engine):
               self.__engine = engine
[69]: c = ElectricCar('red', 4, 4)
[70]: print(c.hard_brake())
screeeeeeeeeech!
[71]: print(c.make_noise())
[72]: print(c.__engine)
---------------------------------------------------------------------------
             <ipython-input-72-7d6935b5390f> in <module>
         ----> 1 print(c.__engine)
[73]: # but we can access this private variable using the class method
      c.get_engine()
motor
[74]: # we can change this variable as well using the set method from the same class
      c.set_engine("new motor")
      c.get_engine()
new motor
                                              64
Summary
In this chapter, we learned about objects, classes and important features of object-oriented pro-
gramming (inheritance, polymorphism, encapsulation, abstraction).
                                               65
Chapter 18
Summary
This is all from this python programming tutorial, in which we covered the following topics:
  1. Introduction on python programming
  2. Comments and print()
  3. Data types/structures
  4. Strings
  5. Operators
  6. Lists and tuples
  7. Dictionaries
  8. Sets
  9. if-elif-else (conditional programming)
 10. Loops (while and for constructs)
 11. Comprehensions
 12. Functions
 13. Import modules
 14. Decorators
 15. Read/write text or csv files
 16. Plotting with Matplotlib
 17. Classes
I hope the material in this tutorial helps in writing python programs more effectively. Off-course
python is much more than this. However, these concepts will be applicable/helpful whatever
new package/library you use in your python programming assignment/project.
Let’s end this tutorial by writing the code for a guessing game, in which a user has to guess a
randomly generated number between 0 and 10 in 4 attempts.
                                               66
[14]: from random import randint
      def guess_this_number(max_attempts=4):
           '''Guess a random number(integer) between 0 and 10 in 4 attempts'''
           number=randint(0, 10)
           guess = int(input('enter a number between 0 and 10: '))
           for count in range(max_attempts):
               if count < max_attempts-1:
                   if guess < number:
                       guess = int(input(f'guess # {count+1} = {guess} is smaller,
       ,→please enter a bigger number: '))
                   else:
                       print(f'Congratulations! you guessed it right in {count+1}
       ,→attempts')
                       break
               else:
                   if guess == number:
                       print(f'Congratulations! you guessed it right in {count+1}
       ,→attempts')
                       break
           else:
               print(f'Sorry, play again! The correct number was {number}')
[19]: guess_this_number()
67