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.

 

Friday, 2 October 2020

Part Two: Exercise 3: A Rudimentary Car Game

 In this exercise, we create a simple car game that takes in user input. The game would give instructions to the user. If the user inputs ‘start’ the game would tell the user that the car has started.

When the user inputs ‘stop’ the game will tell the user that the car has stopped.
The game would also tell the user that the car has already started if the user inputs ‘start’ while the car is already started and would also tell the user the car has already stopped if the user inputs ‘stop’ while the car is already stopped.
When the user inputs ‘quit’, the game would end.
 
We would require a while loop.
 
You can compare with my solution below:
 
    print('WELCOME TO CAR GAME')
    print()
    print('These are the instructions')
    print()
    print('Type "start" at the prompt to start the car')
    print('Type "stop" at prompt at the prompt to stop the car')
    print('Print "quit" at the prompt to end game')
    print()
    game = ' '
    started = False
    while game:
        game = input('Enter your option>>')
        if game.lower() == 'start':
            if started:
                print('Car already started')
            else:
                started = True
                print('Car is starting...')
                print('Car started')

        elif game.lower() == 'stop':
            if not started:
                print('Car already stopped')
            else:
                started = False

                print('Car is stopping...')
                print('Car has stopped')

        elif game.lower() == 'quit':
            print('Quitting Game...')
            print('Thanks for playing')
            exit(0)
 
First we print the title of the game, then followed by the instructions. Before starting our while loop, we declare and empty string called game, similar to how we create empty lists.
In the while loop we state that the variable, game, would be provided by the user. If the user enters ‘start’ the car will start but if the user enters ‘start’ again he is told the game has already started.
When the user enters ‘stop’ the car would stop and if he enters ‘stop’ again the game tells him the car has already stopped.
If he enters quit the game ends
The command exit(0) ensures that the program ends and exists the while loop.

Tuesday, 29 September 2020

Part Two: Exercise 2: A Simple Calculator with if, elif and else Statements

 In this exercise, we build a simple calculator to take in 2 numbers as input from the user. 

Then gives the user the choice to do addition, subtraction, multiplication or division. 
Also, the program should alert the user if they make an invalid entry.
This program should be accomplished using the else, elif and else statements.

You can compare with my solution below:
 
First of all I printed a heading similar to the one in the previous exercise saying this is ‘A Simple Calculator’.

Next the program asks the user to input the first number. After that, it then asks the user for the second number. The inputs are floats.
 
Next we give the user 4 options to choose from, 1. Addition 2. Subtraction 3. Multiplication 4. Division, then ask the user to choose one of the options.
 
The user is alerted if they input anything other than 1, 2, 3 or 4.

Next, we put in our if, elif and else statements. If the user chose option 1, we add, else if they chose option 2, we subtract, if option 3 we multiply and else if option 4 we divide.
 
I did in in 2 ways. You can look at my code below. 
 

print('A Simple Calculator')
print('*' * 20)
print()
x=float(input("Please enter a number : "))
y=float(input("Please enter another number : "))
print()
print("1) Add the two numbers")
print("2) Subtract the two numbers")
print("3) Multiply the two numbers")
print("4) Divide the two numbers")

choice = int(input("Please enter your choice: "))

print("The answer is: ")

if choice == 1:
    print(x+y)
else:
    if choice == 2:
        print(x-y)
    else:
        if choice == 3:
            print(x*y)
        else:
            if choice == 4:
                print(x/y)
            else:
                print("You did not enter a valid choice")

OR
 

print('A Simple Calculator')
print('*' * 20)
print()
x=float(input("Please enter a number : "))
y=float(input("Please enter another number : "))
print()
print("1) Add the two numbers")
print("2) Subtract the two numbers")
print("3) Multiply the two numbers")
print("4) Divide the two numbers")

choice = int(input("Please enter your choice: "))

print("The answer is: ")


if choice == 1:
    print(x+y)
elif choice == 2:
    print(x-y)
elif choice == 3:
    print(x*y)
elif choice == 4:
    print(x/y)
else:
    print("You did not enter a valid choice")



Using the elif statement seem to make the code more compact than relying on just the if and else statements alone.

 

Sunday, 27 September 2020

Part Two: Exercise 1: A Program to perform Kilometre to Miles Conversion and Vice Versa

In Part One we wrote a code to convert distances from kilometres to miles. We could alter the program to convert from miles to kilometres. Now that we have learned about if and else statements, we can update our code to perform both conversions in a single program.

This was the code we had before

print('A PROGRAM TO CONVERT KILOMETERS TO MILES')
print('*' * 45)
print()
km = float(input('Enter distance in kilometers: '))
mi = km * 0.621
print('-' * 35)
print(km,'Kilometers in miles is',mi,'miles')
print()
print(f'{km} kilometers in miles is {mi} miles')
 
We would improve the program by including some if and else statements to our code.
 
You can compare with my solution below:
 
First of all, we would want the user to choose to enter the distance in kilometres or miles. If the user chooses kilometres, then the program uses the condition to calculate the conversion to miles and if the user enters the distance in miles, then the program uses the condition to calculate the conversion to kilometres.

We would request the user to enter the distance. After the user enters the distance, we would add a line to ask the user if it is in kilometres or miles
 
Now we would set up the condition if the user enters k (lower case), then the code executes to convert from kilometres to miles and prints out the result.
Else If the user enter m (lower case), then the code executes to convert from miles to kilometres.
Else, if the user enters any other value, we should remind the user to enter either k or m.
 
Here is my code below:
 
 print('A PROGRAM TO CONVERT KILOMETRES TO MILES OR MILES TO KILOMETRES')
            print('*' * 65)
            print()
            dist = float(input('Enter distance: '))
            km_mi = input('Enter "k" for kilometres or "m" for miles: ')
 
            if km_mi.lower() == 'k':
                        print(dist,'Kilometers in miles is',dist * 0.621,'miles')
            elif km_mi.lower() == 'm':
                        print(dist,'Miles in kilometres is',dist / 0.621,'kilometres')
            else:
                        print('Wrong Input - Enter either "k" or "m" for distance')