Python: Introduction

Selection

Iteration

Learning Outcomes

On completion of this section you shall know:

Go to top

Introduction

In all aspects of life we make decisions. Examples are if the buses are running we shall go into town, otherwise we shall study. In programming we have to make decisions as well or to be more precise we shall tell the computer how to make decisions. We have already met a decision when we were studying while loops. The line while strNameOfCustomer != "":

In Listing 4 of the page Iteration can be seen as a decision making construct. Its logic could be paraphrased in English as 'If the variable strNameOfCustomer is not blank then go into the body of the loop. This similarity however is somewhat tenuous and although there are similarities between the while loop structure and decision making, all programming languages have decision making constructs. We shall introduce Python's decision making constructs by writing a program for a guessing game.

Go to top

Guess the number

For our first introduction to selection/decision making we shall create a guessing game where the program generates a random number in the range 0 - 100 and the user is given six chances to guess that number. This game relates directly to computer science, especially the binary search algorithm. We will eventually discuss how we search the number, but first we shall look at how random numbers are generated in Python.

Listing 1
                    
                    import random
                    intMysteryNumber=random.randint(0,100)
                    print(intMysteryNumber)
                    
                

The very short program above simply generates a random number in the range 0 - 100 and displays that number.

Python itself has no facilities for generating random numbers - or a lot of other mathematical functions. However it has a wide range of libraries it can call upon to perform processing that it cannot do itself. One of those libraries is called random. Thus using import random as the first line in the code gives Python access to the functions of that library. One of those functions is randint().

As its name implies randint() generates a random integer number. At line 2 the function is passed two values: 0 and 100. This is telling it to generate a random number between 0 and 100. Similarly if it was passed 80 and 250 then it would generate a random number between80 and 250.

Naturally, whichever number it generates is stored in the variable intMyMysteryNumber.

All that this program does with the mystery number is to display it on the console at line 3. Listing 2, however, will make much more use of it.

Now let us look at how we can use the random numbers to create our guessing game. The algorithm above gives us the steps.

The first step is to create that actual random number and store it in a variable so we can use it later. The next command is the start of a loop that is to iterate 6 times.

The first step inside the body of the loop is to ask the user to enter an integer number which is then stored in a variable

Now we meet our first if construct. The user's number is compared to the random number. If they are the same then the next two indented commands are executed. The first of those prints out "You're a genius!" and the second one exits from the loop.

The reason for this exit is that if the user has already guessed the number correctly, there is no point in asking them to make further guesses, and the way to solve this is to break out of the loop.

On the other hand if the user's number and the random number are not the same, then the body of the if construct, i.e. telling the user they are a genius and exiting from the loop, will be skipped and control will go to the next if construct.

This second if construct checks whether the random number is greater than the one entered by the user. If it is then the user is prompted that the number they are searching for is higher than the one they entered. However if the random number is lower than that entered by the user the if part is skipped and the else part is activated. Here the user is informed that the random number is lower than the one they entered.

Listing 2
                        import random
                        intMysteryNumber=random.randint(0,100)
                        for intCounter in range(6):
                            intGuess=int(input("Guess the number: "))
                            if intGuess == intMysteryNumber:
                                print("You are a genius")
                                break;
                            if intMysteryNumber > intGuess:
                                print("The number is higher")
                            else:
                                print("The number is lower")
                    

Listing 2 above implements the algorithm using Python code and our description of the steps of the algorithm should apply exactly to the corresponding commands in the code.

Fig 1

The Scratch program above is also a step by step implementation of the algorithm.

Demo of Binary Search

This video demonstrates how, using the logic of the binary search algorithm, the user discovers that the mystery random number is 68.

Go to top

The if construct

The logic of the guessing game above may be somewhat taxing for a beginner programmer, but we included it first as it gave us an opportunity to have some fun with if and if..else constructs. In this section, however, we shall use more mundane but more easily comprehensible examples of the use of the if construct,

Listing 3
                    
                        #Expression Example 1                            
                        strItemDescription = input("Enter description of item: ")                           
                        floatPrice = float(input("Enter price of one item: "))                            
                        intAmountSold = int(input("Enter amount sold: "))                      
                        floatSaleValue = floatPrice * intAmountSold
                        print("#################")                            
                        print("Sale Details")                            
                        print("#################")                            
                        print("Item Description: ", strItemDescription)                            
                        print("Price: ",floatPrice)                            
                        print("Amount Sold: ", intAmountSold)                            
                        print("Total Sale Value: ", floatSaleValue)
                    
                    

Listing 3 above is an exact copy of Listing 1 from the Expressions page. It is copied here for reference purposes only because we are going to modify it to form the first example of an if construct. Listing 4 below is the modified version.

Listing 4
                    
                        #Expression Example 1
                        floatDiscount = 0.0
                        strItemDescription = input("Enter description of item: ")                           
                        floatPrice = float(input("Enter price of one item: "))                            
                        intAmountSold = int(input("Enter amount sold: "))                      
                        floatSaleValue = floatPrice * intAmountSold
                        if floatSaleValue > 100:
                            floatDiscount = floatSaleValue * 0.1
                        floatCustomerBill = floatSaleValue - floatDiscount
                        print("#################")      
                        print("Sale Details")                 
                        print("#################")                       
                        print("Item Description: ", strItemDescription)                            
                        print("Price: ",floatPrice)         
                        print("Amount Sold: ", intAmountSold)                     
                        print("Total Sale Value: ", floatSaleValue)
                        print("Discount: ",floatDiscount)
                        print("Customer Bill: ",floatCustomerBill)                        
                    
                    

Listing 4 is a modification of Listing 3. In Listing 3 the sale value was calculated by multiplying the amount sold by the price of one item. There are no discounts applied here.

In Listing 4, however, a discount is applied. The criteria for the discount is that the value of the sale must be more than 100. If the sale is less than 100, no discount is applied.

In order to implement the discount we need two more variables, one to store the value of the discount and another to store the value of the customer's bill, which will be the total sale, less the discount.

At line 2 the variable floatDiscount, which will hold the value of the discount is initialised to zero.

The calculation of the discount occurs at lines 7 and 8. At line 7 the variable floatSaleValue is tested for being larger than 100. If this is true then at line 8 floatSaleValue is multiplied by 10% (same as being divided by 10) and the value is stored in the variable floatDiscount.

Of course if floatSaleValue has a value of 100 or less then the condition at line 7 will be false and thus line 8 will be skipped. The result of this is that floatDiscount will retain its original value of zero

At line 9 we meet the other new variable, floatCustomerBill. The value of floatDiscount is subtracted from floatSalesValue and the result is stored in floatCustomerBill.

Note that at line 9 floatCustomerBill is always updated the same way. If the value of the sale is less than 100 then floatDiscount will be zero and therefore floatCustomerBill will have the same value as floatSalesValue. On the other hand if the sale value os more than 100, then floatDiscount will be 10% of the sales value and thus floatCustomerBill will be floatSalesValue less floatDiscount.

Fig 2

In Fig 2 above we see two runnings of Listing 4. In the first one the sale value is less than 100 therefore the discount is zero and the customer bill is the same as the total sale value. In the second running, however, the total sale value is 200 and thus the discount is 10% of this, i.e 20. Consequently the customer bill is 200 less 20 which is 180.

Go to top

The if..else construct

For our example of the if..else construct we shall once again recycle the code in Listing 3. In our example of Listing 4 we applied a discount only if the sale value was more than one hundred, otherwise no discount was applied. In this case the if construct suited us just fine.

In our next example we shall be applying a discount regardless of the value of the sale. However if the value of the sale is 100 or less then the discount will be 8% whereas if the value of the sale is more than 100, the discount will be 15%.

                    
                        #Expression Example 1
                        floatDiscount = 0.0
                        strItemDescription = input("Enter description of item: ")
                        floatPrice = float(input("Enter price of one item: "))
                        intAmountSold = int(input("Enter amount sold: "))
                        floatSaleValue = floatPrice * intAmountSold
                        if floatSaleValue < 100:
                            floatDiscount = floatSaleValue * 0.08
                        else:
                            floatDiscount = floatSaleValue * 0.15
                        floatCustomerBill = floatSaleValue - floatDiscount
                        print("#################")
                        print("Sale Details")
                        print("#################")
                        print("Item Description: ", strItemDescription)
                        print("Price: ",floatPrice)
                        print("Amount Sold: ", intAmountSold)
                        print("Total Sale Value: ", floatSaleValue)
                        print("Discount: ",floatDiscount)
                        print("Customer Bill: ",floatCustomerBill)
                    
                    

Lines 1 - 8 of Listing 5 are identical to the same lines of Listing4 and, therefore, there is no need to discuss them. Also lines 12 - 20 should be familiar also. We shall therefore concentrate solely on lines 7 - 10.

Line 7 tests if the sale value is less than 100. In this case a value either is less than 100 or is not less than 100. The value cannot be less than 100 and greater than 100 at the same time. Similarly it must be always either less than 100 or not less than 100. Translating this logic to lines 7 - 10, the test at line 7 is always either true or false. If the test is true then line 8 will be executed and line 10 will be ignored, whereas if the test at line 7 is false then line 8 is ignored and line 10 is executed. In practical terms it means that if the value of the sale is less than 100 the discount is calculated as 8% at line 8, otherwise it is calculated as 15% at line 10. Either line 8 or line 10 is always executed but both of them are never executed in the same run

Fig 3

Fig 3 shows two runs of Listing 5. In the first run the total sale value was 90, i.e. less than 100. For this reason the discount was calculated at line 8% of 90, i.e. 7.2. In the second run the total sale value was 180, i.e. greater than 100 and thus the discount was calculated at line 10 as 15% of 180, i.e. 27.

Go to top

Summary

Selection, or decision making is a concept that allows a program to perform one of several options depending on the value of a particular variable. In listing 2 there were two sets of decision making. At line 4 the simple if statement activated lines 6 and 7 if the user correctly guessed the mystery number, while the if..else construct figcaptioning lines 8 - 11 displays the message "The number is higher" if the mystery number is higher than the user's guess, otherwise it prints "The number is lower".

In listing 4 we have a simple if construct figcaptionning lines 7 and 8. In this case line 8 will only be activated if the sales value is greater than 100, otherwise it will not be activated.

In Listing 5 the if..else construct figcaptions lines 7 - 10. If the sales value is less than 100 then at line 8 the discount is calculated as 8% of the sales value, otherwise the discount is calculated at 15% of the sales value at line 10.

Go to top

Revision

Multi-choice

Fill in the Blanks

Go to top

Exercise

Exercise1

The first three columns of the above table correspond to the three inputs for the program in Listing 5. With lines 6 - 11 as a guide and using pen and paper or a calculator, work out, for each set of inputs the values of the three outputs. The first set of outputs are provided as an example.


Exercise 2

Write a program that will collect data about a book. The data required include:

The various input data items must be stored in appropriately named variables

From the values of Price and Amount sold the revenue generated by the book is calculated.

If Amount sold is greater that 5000 then author's royalties are calculated as 20% of the revenue generated, otherwise they are calculated as 10% of the same revenue.

Go to top

Assignment

You are required to write a program that will collect details of an employee. The program will store each data item in an appropriately named variable. The data required are:

Once data entry is complete the Gross Pay is calculated by multiplying Hourly Rate by Hours Worked. Once the value of Gross Pay is calculated, Tax is calculated. If Gross Pay is less than 500 then tax is calculated as 25% of the Gross Pay, otherwise it is calculated as 30% of the gross. Net Pay is calculated by subtracting Tax from Gross Pay. Both input value data and calculated values must be printed with appropriate labels.

Go to top