Chapter 6: Making Choices and Decisions

Congratulations, you’ve made it to the most interesting chapter. I hope you’ve enjoyed the course so far. In this chapter, we’ll look at how to make your program smarter, capable of making choices and decisions. Specifically, we’ll be looking at the if statement, for loop and while loop. These are known as control flow tools; they control the flow of the program. In addition, we’ll also look at the try, except statement that determines what the program should do when an error occurs. However, before we go into these control flow tools, we have to first look at condition statements.

Conditions Statements

All control flow tools involve evaluating a condition statement. The program will proceed differently depending on whether the condition is met. The most common condition statement is the comparison statement. If we want to compare whether two variables are the same, we use the == sign (double =). For instance, if you write x == y, you are asking the program to check if the value of x is equals to the value of y. If they are equal, the condition is met and the statement will evaluate to True. Else, the statement will evaluate to False. Other comparison signs include != (not equals), < (smaller than), > (greater than), <= (smaller than or equals to) and >= (greater than or equals to). The list below shows how these signs can be used and gives examples of statements that will evaluate to True. Not equals: 5 != 2 Greater than: 5>2 Smaller than: 2<5 Greater than or equals to: 5>=2 5>=5 Smaller than or equals to: 2 <= 5 2 <= 2 We also have three logical operators, and, or, not that are useful if we want to combine multiple conditions. The and operator returns True if all conditions are met. Else it will return False. For instance, the statement 5==5 and 2>1 will return True since both conditions are True. The or operator returns True if at least one condition is met. Else it will return False. The statement 5 > 2 or 7 > 10 or 3 == 2 will return True since the first condition 5>2 is True. The not operator returns True if the condition after the not keyword is false. Else it will return False. The statement not 2>5 will return True since 2 is not greater than 5.

If Statements

The if statement is one of the most commonly used control flow statements. It allows the program to evaluate if a certain condition is met, and to perform the appropriate action based on the result of the evaluation. The structure of an if statement is as follows: if condition 1 is met: do A elif condition 2 is met: do B elif condition 3 is met: do C elif condition 4 is met: do D else: do E elif stands for “else if” and you can have as many elif statements as you like. If you’ve coded in other languages like C or Java before, you may be surprised to notice that no parentheses ( ) are needed in Python after the if, elif and else keyword. In addition, Python does not use curly { } brackets to define the start and end of the if statement. Rather, Python uses indentation. Anything indented is treated as a block of code that will be executed if the condition evaluates to true. To fully understand how the if statement works, fire up IDLE and key in the following code. userInput = input(‘Enter 1 or 2: ‘) if userInput == “1”: print (“Hello World”) print (“How are you?”) elif userInput == “2”: print (“Python Rocks!”) print (“I love Python”) else: print (“You did not enter a valid number”) The program first prompts the user for an input using the input function. The result is stored in the userInput variable as a string. Next the statement if userInput == “1”: compares the userInput variable with the string “1”. If the value stored in userInput is “1”, the program will execute all statements that are indented until the indentation ends. In this example, it’ll print “Hello World”, followed by “How are you?”. Alternatively, if the value stored in userInput is “2”, the program will print “Python Rocks”, followed by “I love Python”. For all other values, the program will print “You did not enter a valid number”. Run the program three times, enter 1, 2 and 3 respectively for each run. You’ll get the following output: Enter 1 or 2: 1 Hello World How are you? Enter 1 or 2: 2 Python Rocks! I love Python Enter 1 or 2: 3 You did not enter a valid number

Inline If

An inline if statement is a simpler form of an if statement and is more convenient if you only need to perform a simple task. The syntax is: do Task A if condition is true else do Task B For instance, num1 = 12 if myInt==10 else 13 This statement assigns 12 to num1 (Task A) if myInt equals to 10. Else it assigns 13 to num1 (Task B). Another example is print (“This is task A” if myInt == 10 else “This is task B”) This statement prints “This is task A” (Task A) if myInt equals to 10. Else it prints “This is task B” (Task B).

For Loop

Next, let us look at the for loop. The for loop executes a block of code repeatedly until the condition in the for statement is no longer valid. Looping through an iterable In Python, an iterable refers to anything that can be looped over, such as a string, list or tuple. The syntax for looping through an iterable is as follows: for a in iterable: print (a) Example: pets = [‘cats’ , ‘dogs’ , ‘rabbits’ , ‘hamsters’] for myPets in pets: print (myPets) In the program above, we first declare the list pets and give it the members ‘cats’, ‘dogs’, ‘rabbits’ and ‘hamsters’. Next the statement for myPets in pets: loops through the pets list and assigns each member in the list to the variable myPets. The first time the program runs through the for loop, it assigns ‘cats’ to the variable myPets. The statement print (myPets) then prints the value ‘cats’. The second time the programs loops through the for statement, it assigns the value ‘dogs’ to myPets and prints the value ‘dogs’. The program continues looping through the list until the end of the list is reached. If you run the program, you’ll get cats dogs rabbits hamsters We can also display the index of the members in the list. To do that, we use the enumerate() function. for index, myPets in enumerate(pets): print (index, myPets) This will give us the output 0 cats 1 dogs 2 rabbits 3 hamster The next example shows how to loop through a string. message = ‘Hello’ for i in message: print (i) The output is H e l l o Looping through a sequence of numbers To loop through a sequence of numbers, the built-in range() function comes in handy. The range() function generates a list of numbers and has the syntax range (start, end, step). If start is not given, the numbers generated will start from zero. Note: A useful tip to remember here is that in Python (and most programming languages), unless otherwise stated, we always start from zero. For instance, the index of a list and a tuple starts from zero. When using the format() method for strings, the positions of parameters start from zero. When using the range() function, if start is not given, the numbers generated start from zero. If step is not given, a list of consecutive numbers will be generated (i.e. step = 1). The end value must be provided. However, one weird thing about the range() function is that the given end value is never part of the generated list. For instance, range(5) will generate the list [0, 1, 2, 3, 4] range(3, 10) will generate [3, 4, 5, 6, 7, 8, 9] range(4, 10, 2) will generate [4, 6, 8] To see how the range() function works in a for statement, try running the following code: for i in range(5): print (i) You should get 0 1 2 3 4

While Loop

The next control flow statement we are going to look at is the while loop. Like the name suggests, a while loop repeatedly executes instructions inside the loop while a certain condition remains valid. The structure of a while statement is as follows: while condition is true: do A Most of the time when using a while loop, we need to first declare a variable to function as a loop counter. Let’s just call this variable counter. The condition in the while statement will evaluate the value of counter to determine if it smaller (or greater) than a certain value. If it is, the loop will be executed. Let’s look at a sample program. counter = 5 while counter > 0: print (“Counter = “ , counter) counter = counter – 1 If you run the program, you’ll get the following output Counter = 5 Counter = 4 Counter = 3 Counter = 2 Counter = 1 At first look, a while statement seems to have the simplest syntax and should be the easiest to use. However, one has to be careful when using while loops due to the danger of infinite loops. Notice that in the program above, we have the line counter = counter – 1? This line is crucial. It decreases the value of counter by 1 and assigns this new value back to counter, overwriting the original value. We need to decrease the value of counter by 1 so that the loop condition while counter > 0 will eventually evaluate to False. If we forget to do that, the loop will keep running endlessly resulting in an infinite loop. If you want to experience this first hand, just delete the line counter = counter – 1 and try running the program again. The program will keep printing counter = 5 until you somehow kill the program. Not a pleasant experience especially if you have a large program and you have no idea which code segment is causing the infinite loop.

Break

When working with loops, sometimes you may want to exit the entire loop when a certain condition is met. To do that, we use the break keyword. Run the following program to see how it works. j = 0 for i in range(5): j = j + 2 print (‘i = ’ , i, ‘ , j = ’ , j) if j == 6: break You should get the following output. i = 0 , j = 2 i = 1 , j = 4 i = 2 , j = 6 Without the break keyword, the program should loop from i = 0 to i = 4 because we used the function range(5). However with the break keyword, the program ends prematurely at i = 2. This is because when i = 2, j reaches the value of 6 and the break keyword causes the loop to end. In the example above, notice that we used an if statement within a for loop. It is very common for us to ‘mix-and-match’ various control tools in programming, such as using a while loop inside an if statement or using a for loop inside a while loop. This is known as a nested control statement.

Continue

Another useful keyword for loops is the continue keyword. When we use continue, the rest of the loop after the keyword is skipped for that iteration. An example will make it clearer. j = 0 for i in range(5): j = j + 2 print (‘\ni = ’ , i, ‘ , j = ’ , j) if j == 6: continue print (‘I will be skipped over if j=6’) You will get the following output: i = 0 , j = 2 I will be skipped over if j=6 i = 1 , j = 4 I will be skipped over if j=6 i = 2 , j = 6 i = 3 , j = 8 I will be skipped over if j=6 i = 4 , j = 10 I will be skipped over if j=6 When j = 6, the line after the continue keyword is not printed. Other than that, everything runs as per normal.

Try Except

The final control statement we’ll look at is the try, except statement. This statement controls how the program proceeds when an error occurs. The syntax is as follows: try: do something except: do something else when an error occurs For instance, try running the program below try: answer =12/0 print (answer) except: print (“An error occurred”) When you run the program, you’ll get the message “An error occurred”. This is because when the program tries to execute the statement answer =12/0 in the try block, an error occurs since you cannot divide a number by zero. The remaining of the try block is ignored and the statement in the except block is executed instead. If you want to display more specific error messages to your users depending on the error, you can specify the error type after the except keyword. Try running the program below. try: userInput1 = int(input(“Please enter a number: “)) userInput2 = int(input(“Please enter another number: “)) answer =userInput1/userInput2 print (“The answer is ” , answer) myFile = open(“missing.txt” , ‘r’) except ValueError: print (“Error: You did not enter a number”) except ZeroDivisionError: print (“Error: Cannot divide by zero”) except Exception as e: print (“Unknown error: ” , e) The list below shows the various outputs for different user inputs. >>> denotes the user input and => denotes the output. >>> Please enter a number: m => Error: You did not enter a number Reason: User entered a string which cannot be cast into an integer. This is a ValueError. Hence, the statement in the except ValueError block is displayed. >>> Please enter a number: 12 >>> Please enter another number: 0 => Error: Cannot divide by zero Reason: userInput2 = 0. Since we cannot divide a number by zero, this is a ZeroDivisionError. The statement in the except ZeroDivisionError block is displayed. >>> Please enter a number: 12 >>> Please enter another number: 3 => The answer is 4.0 => Unknown error: [Errno 2] No such file or directory: ‘missing.txt’ Reason: User enters acceptable values and the line print (“The answer is ” , answer) executes correctly. However, the next line raises an error as missing.txt is not found. Since this is not a ValueError or a ZeroDivisionError, the last except block is executed. ValueError and ZeroDivisionError are two of the many predefined error types in Python. ValueError is raised when a built-in operation or function receives a parameter that has the right type but an inappropriate value. ZeroDivisionError is raised when the program tries to divide by zero. Other common errors in Python include IOError: Raised when an I/O operation (such as the built-in open() function) fails for an I/O-related reason, e.g., “file not found”. ImportError: Raised when an import statement fails to find the module definition IndexError: Raised when a sequence (e.g. string, list, tuple) index is out of range. KeyError: Raised when a dictionary key is not found. NameError: Raised when a local or global name is not found. TypeError: Raised when an operation or function is applied to an object of inappropriate type. For a complete list of all the error types in Python, you can refer to https://docs.python.org/3/library/exceptions.html. Python also comes with pre-defined error messages for each of the different types of errors. If you want to display the message, you use the as keyword after the error type. For instance, to display the default ValueError message, you write: except ValueError as e: print (e) e is the variable name assigned to the error. You can give it some other names, but it is common practice to use e. The last except statement in our program except Exception as e: print (“Unknown error: ” , e) is an example of using the pre-defined error message. It serves as a final attempt to catch any unanticipated errors.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top