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

Friday 25 September 2020

Part Two: Lesson Four: The while Loop

As we discussed with the for loops, computers are very good at doing repetitive tasks over and over again and doing that very quickly using iterations. The while loop can also be utilized to achieve this.

The while loop iteration method is used to perform iterations as long as a condition exists except another condition causes a break in the loop such as finding a solution or exhausting all items to loop over. It is therefore possible to have an infinite loop.

          count = 0

          while count  < 10:

                   print(count)

                   count = count + 1

          print(‘All done’)

In the code above, we initialised our count to start at 0. Then set the condition that while count is less than 10, Python should print the value of count. Then increment the value of count by 1 and run the loop again as long as count is less than 10.

Notice here the colon after the while statement and the indentation below it to ensure Python knows that the lines belong to the while loop.

A more compact way to increment the count is as follows:

          count += 1

Hence, the code now becomes

          count = 0

          while count  < 10:

                   print(count)

                   count +=  1

          print(‘All done’)

 

The iteration in the code above would run as long as the while condition evaluates to True that is it would loop continuously until count is no more less than 10.

An infinite loop may occur if the conditions do not include an endpoint. For example, in the code above if we do not have the line to increment count by 1 in each loop, then count would remain 0 perpetually and would be less than 10 indefinitely and the while loop would go on forever until the program is stopped manually.

count = 0

          while count  < 10:

                   print(count)

                  

          print(‘All done’)

The code above would result in an infinite loop.

We would put all we have learned up to this point to build some programmes next.

 

Part Two: Lesson Three: The for Loop

Computers are very good at doing repetitive tasks over and over again and doing that very quickly using iterations. The for loop is one way to achieve that.

Let us say we have a list of names and we would like to say a personalised greeting to each we could do that as follows:

          names = [‘Ali’, ‘Mike’, ‘Jay’, ‘Mary’, ‘Sarah’]

          print(‘hello’, ‘Ali’)

          print(‘hello’, ‘Mike’)

          print(‘hello’, ‘Jay’)

          print(‘hello’, ‘Mary’)

          print(‘hello’, ‘Sarah’)

          print(‘Thank you’)

This is quite an inefficient way to write the code especially if the items in the list are increased to say hundreds.

A more efficient way is to use a for loop. We would say for each item in the list, display the personalised greeting. It would look like this:

          names = [‘Ali’, ‘Mike’, ‘Jay’, Mary’, Sarah’]

          for n in names:

                   print(‘hello’,  n)

          print(‘Thank you’)

Here n is referred to as the iteration variable. We can use any variable here.

Notice the colon after the for statement and also the indentation that follows. This is essential so as to let Python know that the print statement is part of the for loop and would continue looping till all items have been iterated over. After the iteration completes then the ‘Thank you’ message is displayed because it is not part of the indentation. If we indent this line too then ‘Thank you’ would be displayed with each iteration.

Let us try printing numbers from a list of 1 to 10.

          numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

          for x in numbers:

                   print(x)

this prints numbers from 1 to 10.

An easier way to create a list of numbers are to use the range() function. Range 1 to 11 would provide numbers from 1 up to 10 but not including 11.

          numbers = range(1, 11)

          for x in numbers:

                   print(x)

We could include the intervals in between the numbers perhaps at steps of 2 by adding it as an argument to make the increment at 2 steps

          numbers = range(1, 11, 2)

          for x in numbers:

                   print(x)

This would print out only the odd numbers starting from 1 then 3 and so on.

Lastly, we could use the in statement with our for loop and range function to make it even more concise

          for x in range(1, 11, 2):

                   print(x)

We have now achieved the same result but using just 2 lines of code.

The for loop can be used with other collections like tuples and dictionaries as well.

In the next lesson, we would study the while loop.

Thursday 24 September 2020

Part Two: Lesson Two: if: ...else:

 In Part One, we mentioned that Python executes code line by line. However, the sequence of execution of the code can be altered by imposing some conditions in the code. One such condition is in the form of the if and else statements.

The if and else statements work in conjunction with the comparison operators [less than (<), greater than (>), equals to (==), not equals to (!=)] and logical operators (and, or, not). When the statement evaluates to a Boolean (True or False), the code is executed or not executed.

Let us look at some examples

    x = 5

    if x > 0:

        print(‘x is positive’)

    else:

        print(‘x is negative’)

In the code above a particular variable, x, is provided. The first condition is if the variable is greater than 0 (Boolean evaluates to True), then Python should display ‘x is positive’. The second condition is else the variable is not greater than 0 (Boolean evaluates to False), then Python should display ‘x is negative’.

Notice the colon (:) after the lines for the if and the else statements. This is vital without which we would have an error message.

Notice also, the indentation below the if and else statements. This is how to tell Python that those lines are part of the if block and part of the else block respectively.

If we run the code now we get an output from the if part of the code and the else part is not executed. We get ‘x is positive’.

Next, when we change the value of x to a negative number, say -5, the if part of the code is not executed but the else part would be executed. We get ‘x is negative’.

We could also request user input for the variable or even use a list. Let us modify the code to accept user input as follows

    x = int(input(‘Please enter a number: ‘)

    if x > 0:

        print(‘x is positive’)

    else:

        print(‘x is negative’)

Now, the user is prompted to provide a number which would be evaluated and the correct output would be displayed.

Let us introduce the elif statement (else if). This is used when evaluating more than 2 conditions. We can have as many elif statements as required. Let us modify our code to include a condition if our variable is 0.

    x = int(input(‘Please enter a number: ‘)

    if x > 0:

        print(‘x is positive’)

    elif x == 0:

        print(‘x is zero’)

    else:

        print(‘x is negative’)

Now if our input is 0, the elif section of the code is executed and the if and else sections are not executed. We get ‘x is zero’.

We can use logical expressions to combine conditions as well. We can modify our code to combine positive and 0 in one condition for example.

    x = int(input(‘Please enter a number: ‘)

    if x > 0 or x == 0:

        print(‘x is positive’)

    else:

        print(‘x is negative’)

The if statement would be executed if x is greater than 0 or if x is equal to 0.

We can try other combinations of comparison operators with logical operators with if, elif and else statements.

We would explore this flow of control in more detail in subsequent lessons and exercises.



Saturday 19 September 2020

Part Two: Lesson One: Collections

In part one we learned about variables whereby a value is assigned to it. Example x = 4. Here, x is the variable and 4 is the value currently assigned to it.

However, it is possible to assign more than one value at a time to a variable and this is where the concept of collections come in python 3. The type of collections are lists, tuples, sets and dictionaries. What they have in common is that they can store multiple values per variable and these values can be manipulated but they may differ in how this is done.

Let us discuss the most used of the collections first, that is lists. Please follow along by typing each of the lines below and running them in an IDE like PyCharm or on repl.it.

Lists

Lets have a variable

    x = 4

    print(x)

If we wanted to store four values from we would use a list using square brackets

    x = [1, 2, 3, 4]

    print(x)

Another way to create lists is to use the built-in function, list(). we can also create an empty list which we would populate later.

    x = list()

    x = []

A list can contain multiple types of values like strings, integers, floats and even other lists

    x = [1, 2, ‘Jay’, 0.4, (12, ‘dozen’)]

    usernames = [‘Jay’, ‘Ali’, ‘Mike’]

    print(x)

    print(usernames)

Here are some ways to manipulate lists. We can check the length or number of items in the list with len() function

    print(len(x))

    print(len(usernames))

We can access the index of an item in a list. The index are numbered from 0.

    print(x[0])

This would be 1.

    print(x[1])

This would be 2.

    print(x[-1])

This would give the last value.



We can access a range of values

    print(x[0:2])

This would 1, 2 but not including the third index ‘Jay’.

Other options are

    print(x[:3])

This would count from index 0 up to index 2.

    print(x[1:])

This would count from index 1 to the last index.

    print(x[:])

This would give all the items in the list

It is possible to add items to a list and to also remove items from a list using methods

    x.append(5)

    print(x)

This would add 5 to the end of the list

    x.insert(1,6)

    print(x)

This would insert 6 at index 1 in the list

    x.remove(5)

    print(x)

This removes 5 from the list

    print(x.pop())

This removes the last item in the list

Other methods used with lists include sort, reverse, max, min, sum.

Tuples

The main difference between lists and tuples is that lists can be modified, that is they are mutable whereas tuples are not mutable. Hence, they have less methods associated with them compared to lists.

Once a tuple is created you can not append to it.

    y = ()

    y = tuple()

These create empty tuples that can be populated later.

    passwords = (1234, 5678, 9001)

    print(passwords)

We would not be able to append or update tuples.

Sets

Sets are an unordered collection and there are no duplicates in sets

    name = set()

The above create empty set to be populated later

Sets are usually applied to collections where duplicates are not permitted.

Methods associated with sets are union, intersection, difference.

Dictionaries

Just like the normal dictionary we know, dictionaries are a type of collection that have keys and values. Examples below:

    name = dict()

    name = {}

these creates empty dictionaries to be populated later on.

    student = {‘name’: ‘Ali’, ‘age’: 22, ‘subjects’ : [‘English’, ‘Maths’]}

we can access a key like subjects as follows:

    print(student[‘subjects’])

We can also use .get method especially if are not sure a key is in the dictionary to avoid error messages

    print(student.get(‘name’)

we can add, update or delete keys and values as follows:

    student[‘name’] = ‘Jay’

the above updates the name to Jay instead of Ali.

    student[‘phone’] = 555222

this adds a new key ‘phone’ and a value 555222 to the student dictionary.

To delete we use the del command or the .pop method

    del student[‘age’]

or

    student.pop(‘name’)

Congratulations, we can now use and manipulate lists, tuples, sets and dictionaries.

In the next lessons we would put them to use.



Sunday 13 September 2020

Part One: 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 also learned enough to consider looking at other programming languages as well.

Here is a summary of what was learned so far:

You can now install Python 3 and an IDE of your choice to write and execute your codes.

You know what strings are and that they are enclosed in quotation marks (double or single). You know what the different types of numbers are; that is integers (int) and floating-point (float).

You know how to comment out parts of your code so it does not execute with the # key.

You know what variables are and how they are used to store a string or a number.

You can now use the built-in function input() to accept inputs from a user as strings, integers or floats. 

You can now also use the built-in function print() to display results of your code. You can print strings and/or numbers and you can also use the f’string technique.

You can add methods to your string by using the dot to make your strings lower case, upper case etc.

You can also use arithmetic manipulation on numbers to add, subtract, multiply etc.

You have also written a few programs to do some tasks like kilometre to miles conversion, calculate the area of a square, etc.

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

In Part Two we would learn about collections and flow control.

 

Thursday 10 September 2020

Part One: Exercise 5

 In this exercise, we would look at arithematic operations with Pyhthon 3. We could do additions, subtraction multiplication, division and so on.

We are going to write a little program that takes two numbers as input from the user and then performs and prints out the addition, the subtraction, the multiplication, the division, the integer division (ignores the remainder), the modulus (only returns the remainder), the exponent (the power).

We can compare the numbers to see if the are equal using the double equal sign so that Python returns a True or a False statement.

You can compare with my solution below:

print('*' * 50) #prints * 50 times

print('A PROGRAM TO PERFORM ARITHEMATIC OPERATIONS')

print('*' * 50)

print()         #prints a blank line

firstnumber = float(input('Please enter the first number: ')) #user enters the first number

print()      

secondnumber = float(input('Please enter the second number: ')) #user enters the second number

print()

 

addition = firstnumber + secondnumber  #adds the two numbers

subtraction = firstnumber - secondnumber  #substracts the two numbers

multiplication = firstnumber * secondnumber  #multiplies the two numbers

division = firstnumber / secondnumber  #divides the two numbers

integerdivision = firstnumber // secondnumber  #ignores the remainder

modulus = firstnumber % secondnumber  #returns only the remainder

power = firstnumber ** secondnumber  #first number raised to power second number

compare = firstnumber == secondnumber #checks if first number equals second number

print('-' * 30)

print(f'Addition is {addition}')

print('-' * 30)

print(f'Subtraction is {subtraction}')

print('-' * 30)

print(f'Multiplication is {multiplication}')

print('-' * 30)

print(f'Division is {division}')

print('-' * 30)

print(f'Integer Division is {integerdivision}')

print('-' * 30)

print(f'Modulus is {modulus}')

print('-' * 30)

print(f'Raised to Power is {power}')

print('-' * 35)

print(f'Is the 1st and 2nd number equal? {compare}')

print('=' * 35)

 

Notice that I used float for the inputs. This is to account for the fact that the user might enter decimal numbers and also not to get errors with division.