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')

 

 

 

Friday 9 October 2020

Part Three: Functions: Arguments, default parameters, docstrings

We can also use default parameter values in our user-defined functions. Looking at our last example, we could assign a default value for the parameter b, say b = 5. This value would be used unless an argument is provided to overwrite it when the function is called. Example

def addition(a, b = 5):
    return a + b

print(addition(2))


This would give 7.

 


def addition(a, b = 5):
    return a + b

print(addition(2, 8))


This would give 10.

 

 We could have as many parameters as required. However, the default parameters always come after the positional parameters have been specified so we do not get error messages when we run our code.

 

def addition(a, b, c = 3, d = 4):
    return a + b + c + d

print(addition(2, 8))


This would give 17.

 

If we do not know how many parameters and hence, how many arguments the function would take, we could use the (*args). For example

 

def addition(*num):

   for a in num:
        return sum(num)

print(addition(1, 2, 3, 4, 5, 6, 7, 8))


This would be 36.

 

Lastly, let us discuss what docstrings are in relation to functions. They are optional documentation a bit similar to comments but they provide documentation for what your user-defined function does so others can read up on it especially for complex programs. They are enclosed within triple quotation marks. Example

 

def addition(*num):

            '''This function performs addition of all the arguments provided to it'''

 

   for a in num:
        return sum(num)

print(addition(1, 2, 3, 4, 5, 6, 7, 8))


When we now run

            print(addition.__doc__)


The docstring we included would be printed.

 

We could try it for inbuilt functions like print and input too.

            print(print.__doc__)

            print(input.__doc__)

We can now update our calculator program.

 

Tuesday 6 October 2020

Part Three: Functions: Introduction

 We have come across some built-in functions in our Python 3 programming journey. These functions include print() and input(). These functions were already defined and programmed somewhere within Python and we did not need to know what happens behind the scenes but whenever we invoked them, they work as defined.

In this part of the course, we are going to be looking at user-defined functions. That is functions we can create ourselves as programmers and which we can invoke anywhere in our program to carry out some tasks similar to how we would invoke a built-in function like print() or input().

When writing a function we start with the def keyword then followed by the function name then followed by a colon. Then the statements follow under that with indentations. For example

          def  function_name(parameters):

                   statement 1

                   statement 2                                                                                                 

                                           

                  

Let us try an example by writing a function to display the ‘Hello world’ message

 

def message():
    print('Hello world')

message()

when the code above is run, message() prints ‘Hello world’.

We can add more lines of code under the message function and that would be executed when message() function is called.

def message():
    print('Hello world')
    print('testing functions in Python')
    print('addition', 3 + 5)
    print('subtraction', 8 - 3)
    print('Thank you')

message()

When message() function is called in the code above, all the statements within the function are executed.

The advantage of this is you can define a function at the beginning of your program and then call it many times later in your program without having to write the whole code over and over again.

We could also return a value in our function and include a parameter. For example;

def square(x):
    return x ** x

print(square(2))

In the function above, x is the parameter introduced into the function and the function returns the square of x. So whenever the function is called, it returns the square of the parameter.

We can as well have multiple parameters in our function. Example;

def addition(a, b):
    return a + b

print(addition(2, 3))


The function above takes two parameters, a and b, and returns the sum of the parameters. In the example above two arguments, 2 and 3 were provided and the sum 5 was returned.

 

 

Monday 5 October 2020

Part Two: Conclusion

 If you have made it this far, CONGRATULATIONS. You have learned a lot and on your way to becoming a programmer with Python 3. You have completed Part Two.

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

·        You learned about collections in Python 3, that is Lists, Tuples, Sets and Dictionaries.

·        You are able to manipulate any of the collections and you know which one to apply for certain situations. For example, you can add more items or remove items to lists but you cannot do that with tuples. You cannot have a repetition of the same item in sets.

·        You can now control the flow in your programme using the if, elif and else statements.

·        You can execute loops in your program. You can use for loops and while loops.

·        You were able to apply if, elif and else statements to create a calculator that takes input from users and add, subtracts, multiply or divide 2 numbers.

·        You were able to make your kilometre to miles converter much better such that you could convert both using the same code.

·        You were able to design a rudimentary car game using while loop in addition to if-else statements.

·        You were able to design a simple password manager using lists.

If required you can go back and review the lessons discussed earlier and you could also watch the videos again.

In Part Three we would learn about Functions.

Sunday 4 October 2020

Part Two: Exercise 4: Password Manager

In this exercise, we create a simple password manager using lists in Python 3. Using lists allows us to add and/or remove passwords from the lists. We can use it for PINs as well.

When the user inputs a password or PIN that is in the list, the message ‘Access Granted’ is displayed.

Else if the password or PIN is not in the list, the message ‘Access Denied' is displayed.

 

You can compare with my codes below:

 

passwords = [9001, 9002, 9003]
p = int(input('Enter password>'))

if p in passwords:
    print('Access Granted')
else:
    print('Assess Denied!')

 

We can add to the list by using the .append method and the new password will be included to the list.

 

passwords = [9001, 9002, 9003]

passwords.append(9004)
p = int(input('Enter password>'))

if p in passwords:
    print('Access Granted')
else:
    print('Assess Denied!')


We can delete a password from the list using the .remove method. After removing a password, if we try to input it we would get the message ‘Access Denied’

 

passwords = [9001, 9002, 9003]

passwords.append(9004)

passwords.remove(9001)
p = int(input('Enter password>'))

if p in passwords:
    print('Access Granted')
else:
    print('Assess Denied!')


   We can do more creative things with the password manager when writing specific codes.