Saturday, 26 December 2020

Part Four: Conclusion to Object Oriented Programming (OOP)

Congratulations on completing Part Four, it is a bit more of an advanced topic and it is the final part of our course. You have learned a lot and on your way to becoming a programmer with Python 3.

Here is a summary of what was learned in Part Four:

·        We have learned about types (objects) and classes in Python 3.

·        We have learned that we have been working with in-built types throughout the course.

·        We have also learned how to create our own user-defined classes in Python 3.

·        We created the Person class and used the __init__ method.

·        We learned that we can add as many methods (functions) under our user-defined classes.

·        We created the Mammal class and using the concept of class inheritance created subclasses Dog class and Cat class.

·        We created the Employee Payment Platform System (EPPS) using Object Oriented Programming (classes).

Wednesday, 9 December 2020

Part Four: Example 4: Employee Payment Platform System (EPPS)

 In this example, we are going to create a very basic template of a government employee payment system that would be used to pay three different kinds of workers. The classes we would consider in this example are mainstream government workers, university workers and oil workers.


The first class to be created would be that of the mainstream workers because it contains all the attributes common to all the three classes of workers. 
Next, we create the university class of workers which would inherit all the attributes of the mainstream workers and in addition would have the attribute ‘allowance’ which is peculiar to only this class of workers. 
Finally, we would create the oil worker class which would also inherit all attributes from the mainstream worker class but would have the peculiar attribute ‘offshore’ attributed to this class of workers only.
 
Below is the code to execute the Employee Payment Platform System (EPPS). 

 

print('Employee Payment Platform System (EPPS)')
print('------------------------------------------')


class Employee:
    def __init__(self, name, age, rank):
       self.name = name
       self.age = age
       self.rank = rank

    def pay(self):
        print('pay')


class University(Employee):
    def allowance(self):
        print('allowance')


class Oil(Employee):
    def offshore(self):
        print('offshore')


print('')
employee1 = Employee('Mike', 34, 'Manager')
employee1.pay()

print('')
print('--------------------')
university1 = University('Ali', 28, 'Dean')
university1.pay()
university1.allowance()

print('')
print('--------------------')
oil1 = Oil('Jay', 45, 'Supervisor')
oil1.pay()
oil1.offshore()

 

When we run the code we have the following output:

 

Employee Payment Platform System (EPPS)

------------------------------------------

 

pay

 

--------------------

pay

allowance

 

--------------------

pay

offshore

 

 From the code above, all employees have common parameters (name, age, rank) and a common method (function) ‘pay’.

However, the university class inherits all those attributes from the employee class and in addition have the peculiar method, ‘allowance’ attributed to this class only.

Similarly, the oil worker class inherits all the attributes from the employee class and in addition have the peculiar attribute ‘offshore’.

We can then add our employees based on the class they belong and they would automatically get all the payment they are entitled to.

If required, at any time, we can add, remove, modify any of the attributes in any of the classes and the changes would affect only the targeted employees.

 

 

 

 

 

Monday, 7 December 2020

Part Four: Example 3: class Inheritance

 We can create a class that would have all the common attributes then create subclasses that would have peculiar attributes in addition to the common attributes in the main class.

Example is the class Mammal below. The main class has the attribute walk which is common to the Mammal class. 
However, in the subclass Dog there is the peculiar attribute bark in addition to the common attribute walk.
Also, in the subclass Cat there is the peculiar attribute meow in addition to the common attribute walk.
 
The code is given below:
 
 

class Mammal:
   def walk(self):
      print('walk')

class Dog(Mammal):
   def bark(self):
      print('bark')

class Cat(Mammal):
   def meow(self):
      print('meowing')

dog1 = Dog()
dog1.walk()

cat1 = Cat()
cat1.meow()

When we run the code we have the following output:

 
walk
meowing 

Part Four: Example 2: class Person

 In this example, we would add some more methods (functions) to our person class. We would add the methods to walk and speak such that it can be invoked when we run the code as shown below.

 

class Person:
   def __init__(self, name, age):
      self.name = name
      self.age = age

   def walk(self):
      print(self.name + ' is walking...')

   def speak(self):
      print('Hello my name is ' + self.name + ' and I am ' + str(self.age) + ' years old')

ali = Person('Ali', 22)
jay = Person('Jay', 18)

print(ali.name + ' ' + str(ali.age))
ali.speak()
ali.walk()

print(jay.name + ' ' + str(jay.age))
jay.speak()
jay.walk()

 

When we run the code we have the following output:

 

Ali 22

Hello my name is Ali and I am 22 years old

Ali is walking...

Jay 18

Hello my name is Jay and I am 18 years old

Jay is walking...  

 

Wednesday, 11 November 2020

Part Four: Introduction to Object Oriented Programming (OOP)

 

So far in this course, we have learned a lot of concepts about programming in Python. We have learned about various data types such as strings, integers, floats, Booleans. We have learned about variables and how they are used to store the various data types. We have learned about built-in functions such as print() and input() and how they can be used to manipulate our variables and our data types. We also learned about collections such lists, tuples, sets and dictionaries and how they are used to store more than one variable at a time to be manipulated and processed using our functions. We also learned how to define our own functions, that is user-defined functions where we group our lines of code into a function to be executed.

All these are known as objects which we can display by printing the type. Examples below:

          print(type(5))

          print(type(7.9))

          print(type(True))

          print(type(‘ali’))

print(type([1, 2, 3, 4, 5])

We would the following output

          <class 'int'>

<class 'float'>

<class 'bool'>

<class 'str'>

<class 'list'>

 

As can be seen, the class of each of the objects before is displayed. We have int, float, bool, str, list as the various objects. These are all built-in types (classes)

In Python, it is possible to construct our own user-defined classes (types) also. We do this by starting with the class definition. Then under that, we define the attributes of the class and the methods to be used. This essentially provides us with a template for the class to work with.

Let us consider some practical examples. We could create a class called Person. This Person could have attributes like name and age. This would be our template which we would use to build on. When we run this, then we would have to provide a particular name and the particular age.

Creating the Person class

This is how our code would look like

          class Person:

                   def __init__(self, name, age):

                             self.name = name

                             self.age = age

Let us explain the block of code above. The keyword class is used in Python when we are about to create a class. The class we are creating here is Person (the first letter is capitalised by convention). Next, we have the function with the __init__ method. This is a special method known as an initialiser for the class which tells us which data must be supplied when the instance of class Person is created and how the data is stored and in our case with the class Person, that data is name and age.

There is also the special variable, self, which is always the first parameter passed to the method. We do not provide the data for this parameter, it is left for Python to do but we would supply the name and age ourselves.

So we can now create our Person class with the following codes

          p1 = Person(‘Ali’, 23)

          p2 = Person(‘Jay’, 34)

We have now stored data for 2 people in the Person class with their names and ages, where p1 and p2 have all the attributes of the class Person but are stored in separate locations in memory with different data.

To access an attribute from the Person class, we write the following code

          print(p1.name)

          print(p1.age)

          print(p2.name)

          print(p2.age)

And we have this output

          Ali

23

Jay

34

Or we could even make is more interesting with the code below

          print(p1.name, ‘is’, p1.age, ‘years old’)

          print(p2.name, ‘is’, p2.age, ‘years old’)

And we get the output as follows

          Ali is 36 years old

Jay is 21 years old

We can also update an attribute directly. For example, we could update the age of p1

          p1.age = 38

If we run the code again we get

          print(p1.name, ‘is’, p1.age, ‘years old’)

This is the output we get

          Ali is 38 years old

We could also print the type for Person as well as p1 or p2.

          print(type(Person)

          print(type(p1)

We would get the following output

<class 'type'>

<class '__main__.Person'>

Meaning Person is of class type (object) itself.


Another example coming up.

Saturday, 31 October 2020

Part Three: Conclusion

Congratulations on completing Part 3. You have learned a lot and on your way to becoming a programmer with Python 3.

Here is a summary of what was learned in Part Three:

·        We learned about functions in Python 3. We have the built-in functions like print() and input() but we can also have user-defined functions.

·        To create a user-defined function, we use the def keyword. We then specify all our lines of code for what the function is to perform under that.

·        We learned about using arguments in our functions. We could also specify default parameters for our functions. We can also use docstrings so as to have documentation on what the function does.

·        We wrote a better code to improve our calculator. We were able to achieve a better calculator app using functions.

 

Monday, 12 October 2020

Part Three: Functions: Exercise 1: A Better Calculator App

In this exercise, we would put to use all the knowledge gained from the beginning to build a calculator app using functions. The calculator app would do the following:

·        It would have separate functions for addition, subtraction, multiplication and division. It should also find power, modulus and also perform integer division.

·        The app would take inputs from the user.

·        The app would ask which operation the user wants to perform.

·        The app would perform the selected operation and print the result out.

·        The app would ask the user if they have finished using the app or not.

·        Doscstings are provided for the functions used. Comments too where appropriate.

You can compare your code to mine below.

 

print('Simple Calculator App')

 

def add(x,y):

    """Add two numbers"""

    return x + y

def subtract(x,y):

    '''Subtract two numbers'''

    return x - y

def multiply(x,y):

    '''Multiply two numbers'''

    return x*y

def divide(x,y):

    '''Divide two numbers'''

    return x/y

 

def modulus(x,y):

    '''Divide two numbers to get modulus'''

    return x%y

def power(x,y):

    '''Power of two numbers'''

    return x**y

def integer_division(x,y):

    '''Integer division on two numbers'''

    return x//y

 

def check_if_user_has_finished():

    """

    Checks that the user wants to finish or not.

    Performs some verification of the input."""

    ok_to_finish = True

    user_input_accepted = False

    while not user_input_accepted:

        user_input = input('Do you want to finish (y/n): ')

        if user_input == 'y':

            user_input_accepted = True

        elif user_input == 'n':

            ok_to_finish = False

            user_input_accepted = True

        else:

            print('Response must be (y/n), please try again')

        return ok_to_finish

   

def get_operation_choice():

    input_ok = False

    while not input_ok:

        print('Menu Options are:')

        print('1. Add')

        print('2. Subtract')

        print('3. Multiply')

        print('4. Divide')

        print('5. Modulus')

         print('6. Power')

        print('7. Integer Division')

        print('-----------------')

        user_selection = input('Please make a selection: ')

        if user_selection in ('1', '2', '3', '4','5','6','7'):

            input_ok = True

        else:

            print('Invalid Input (must be 1 - 7)')

    print('-----------------')

    return user_selection

 

def get_numbers_from_user():

    num1 = float(input('Input the first number: '))

    num2 = float(input('Input the second number: '))

    return num1, num2

 

def get_integer_input(message):

    value_as_string = input(message)

    while not value_as_string.isnumeric():

        print('The input must be an integer')

        value_as_string = input(message)

    return int(value_as_string)

   

finished =False

while not finished:

    result = 0

    menu_choice = get_operation_choice()

    n1, n2 = get_numbers_from_user()

    if menu_choice == '1':

        result = add(n1, n2)

    elif menu_choice == '2':

        result = subtract(n1, n2)

    elif menu_choice == '3':

        result = multiply(n1, n2)

    elif menu_choice == '4':

        result = divide(n1, n2)

    elif menu_choice == '5':

        result = modulus(n1, n2)

    elif menu_choice == '6':

        result = power(n1, n2) 

    elif menu_choice == '7':

        result = integer_division(n1, n2)   

    #Get the operation from the user

    #Get the numbers from the user

    #Select the operation

    print('Result:', result)

    print('====================')

    finished = check_if_user_has_finished()

    #Determing if the user has finished

   

print('Bye')