CS 110X Jan 24 2014
Expected reading: pages 201-208.
Expected interaction:
If-else
Relational,
equality ops
Clicker: Assessment
Revised Homework2 description. Be advised that the homework has changed.
Programming partners are to be finalized today.
We hold these truths to be self-evident, that all men are created equal.
Declaration of Independence
1 The Fact That A Thing Is Itself. Thus A is A
What if you were given a Python list of values, and
asked to count how many times the first element of the list appeared in the
rest of the list.
For example, given [1, 4, 3, 4] as a list, the answer would be zero
times; with [1, 2, 3, 1, 2, 3, 1] the answer would be three times.
1.1 if-then-else statement
You have seen the use of for as a control statement. That is, it determines how many times to execute a body of Python statements. But you may find it useful to decide to skip a bunch of Python statements, under certain circumstances. Alternatively, you might want to make sure that a certain body of statements executed when the time was right.
Assume you wrote a function that asked the user for a number and then printed the number, its square, and its inverse. The following is a suitable solution.
def compute(): n = input("Enter in a non-zero value ") square = n**2 print (str(n) + " " + str(square) + " " + str(1.0/n))
With input of n=0, however, the above program terminates in error:
Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> compute() File "C:\Users\Laptop\Dropbox\cs110x\Syllabus Objectives\HW1-solution\Q4.py", line 8, in compute print (str(n) + " " + str(square) + " " + str(1.0/n)) ZeroDivisionError: float division by zero
Clearly we need to be able to protect ourselves in case the user provides us with an invalid input.
In computer science, the control structure we need is known as if-then-else. It lets you determine when to execute certain code blocks, and when to avoid them.
Modify the program as follows:
def compute(): n = input("Enter in a non-zero value ") if n == 0: # if-body statements print ("0 is invalid input") else: # else-body statements square = n**2 print (str(n) + " " + str(square) + " " + str(1.0/n))
The if statement has a condition (n == 0) that must be True before a body of statements can be executed (known as the if-body). Should the condition evaluate to true, then the if-body executes. However, if the condition does not evaluate to True, then the else-body of statements is executed.
Try running this program multiple times with different input. I hope you can see that the behavior changes based upon the input, and you only need to write a single program to cause this action.
1.2 Comparison Operators
Of course, now I need to explain the odd looking == operator.
As you know the Python = operator assigns values to variables. Thus n=0 assigns n the value of 0.
If you want to inspect the value of n, to see its value, you need to use the == operator (affectionally known as equals-equals). Let’s look at the following transcript:
>>> n = 0 >>> n 0 >>> n == 0 True >>> n > 0 False >>> n >= 0 True
In the above transcript, you can see that I first set the value of n = 0. Note that the Python Shell window does not actually respond with any output. This actually is significant and demonstrates that n = 0 is strictly an assignment operator, and does not inspect the value in any way.
The n statement, by itself, is used in the Python Shell window as part of the "calculator mode", which allows you to inspect variables, which is why a line of output appears.
Now comes the first introduction of the n == 0 statement. This statement inspects the value of n and checks to see whether its value is the same as 0. To be quite precise, the == operator checks that the value of the left hand side is exactly equal to the value on the right hand side. The == operator evaluates to a Boolean value, that is either True or False.
A Boolean value is another basic type in Python (much like int, float, str).
Thus the == operator is a comparison operator. There are seven such comparison operators that you must learn. Each refers to a left-hand-side (LHS) and a right-hand-side (RHS).
(LHS == RHS) – Are two values exactly equal to one another
(LHS < RHS) – is LHS smaller than RHS
(LHS <= RHS) – is LHS smaller than or equal to RHS
(LHS > RHS) – is LHS greater than RHS
(LHS >= RHS) – is LHS greater than or equal to RHS
(LHS <> RHS) – is LHS not equal to RHS
(LHS != RHS) – is LHS not equal to RHS
The != operator looks odd; it is the "Not Equals" operator. This syntax is a carry over to the C programming language, which introduced this operator in the 1970s and nearly every programming language has adopted it also. So there are technically two ways to check that a value does not equal another value.
With these conditional operators in place, you can then write simple if-then-else statements that guide the execution of a program.
1.3 Grouping Boolean Values
Often you find yourself wanting to determine whether two comparison operators are both true; for example, to check if both x and y are 0.
To do this you need binary logical operators, used in any logic formula. Here LC refers to left conditional and RC refers to right conditional.
(LC and RC) – True if and only if both LC and RC are true
(LC or RC) – True if either LC or RC is true
For completion, the logical not operator is a unary operator:
(not COND) – True if and only COND is false
With these operators in hand, you can write statements such as:
>>> x = 5 >>> y = 8 >>> if x < 4 or y > 6: print ("ONE IS TRUE") ONE IS TRUE
There is also one other syntactic detail that is supported by Python. Often when you are comparing values, you want to check to see if a target value is between two other values. Here is the long way to complete this action:
>>> x = 6 >>> if x > 3 and x < 10: print ("IN BETWEEN") IN BETWEEN
And here is the (more familiar) short way:
>>> x = 6 >>> if 3 < x < 10: print ("IN BETWEEN") IN BETWEEN
They both work, and you should choose one based on your own individual style.
1.4 None value
So let’s get back to our problem description. How are we going to count the number of times the first element of the list appears in the rest of the list?
Well, you should know by now that we can use a definite loop to iterate over all elements in the list. But now it seems clearer that we want to do one sequence of steps the first time through the list (identify the element) and another sequence of steps for the other elements (count when they are the same).
First, let’s tackle the easier problem, that is, to count the number of times a fixed value appears in a list:
>>> x = [1, 2, 5, 4, 2, 1] >>> count = 0 >>> target = 1 >>> for e in x: if e == target: count = count + 1 >>> print (count) 2
What you can observe above is that we only increase count when the element e is equal to target (in this case, the value 1). As you recall from our lecture on a definite for loop, each time through the loop, the variable e will be set to each successive element. And you know that every element will be visited, so the above code will produce the correct result.
This solution brings us closer to our final goal.
If only we could write code that looks like the following
>>> x = [1, 2, 5, 4, 2, 1] >>> count = 0 >>> target = NOT-YET-SET >>> for e in x: if e == target: count = count + 1 if target == NOT-YET-SET: target = e >>> print (count) 2
Look at what the above would let you do. The first time though the loop, what would happen with the condition e == target? Clearly the answer must be False because how could e ever be equal to something that is NOT-YET-SET? But then, since the target variable is actually NOT-YET-SET, then target would be assigned e, the first value in the loop.
What the above demonstrates is that the first time through the loop, count can never be incremented, and target will be set to the first element in the loop.
Then for the remaining times through the loop, you can be guaranteed that count will only be incremented when element e equals the target value; also, target will never again be changed.
The None value is how Python refers to NOT-YET-SET. We are now done with our program. Here it is:
>>> x = [1, 2, 5, 4, 2, 1] >>> count = 0 >>> target = None >>> for e in x: if e == target: count = count + 1 if target == None: target = e >>> print (count) 2
Done!
To make sure you understand this code, be sure to "replay" the for loop, and pay attention to the values of e, count, and target.
1.5 break statement in for loop
Sometimes you want to iterate over a number of elements in a list, but then stop when you have reached the one that you want. Alternatively, if you select in advance that you want to try some sequence of statements 20 times, you might decide along the way to break out of the loop earlier than you had intended.
The break statement allows you to do just this.
For example, what if you didn’t know the number of steps needed for a computation, but you would know when you were done? As an example, what is the first Fibonacci number with 5 digits?
To solve this, we have to review two concepts already discussed. As you know, you can take an integer value and convert it to a string, using str(...). As you also know, you can determine the length of a string using len(...). If we put these together, a solution appears:
def printFibonacci(): twoPast = 1 last = 1 # Let’s hope we find the answer in first 100 fibonacci numbers. for i in range(100): current = twoPast + last if len(str(current)) >= 5: break # be sure you understand why these two # statements have to be in this exact order twoPast = last last = current print (str(current) + " has five digits.")
The break statement will terminate the for loop immediately, and the next statement to execute will be after the for loop.
1.6 Return Statement
In the examples we have routinely demonstrated the success of a computation by using print to output a value to the console window. Moving forward we will increasingly define functions to return a value that can be subsequently used in future computations. This is an important difference. You use print when you want to provide output to a human running the program. You define functions to return values so the functions can be used by other functions.
As a case in point, consider the following function:
def square(x): return x*x
The purpose of this function is to simply square a given value. As such it can be used by other functions:
def hypotenuse(a,b): return (square(a) + square(b)) ** 0.5
Since the value computed by the square function is returned, then square can be used within another function, in this case hypotenuse.
1.7 Debugging Challenge
The following program tries to print every other element in a list.
Can you find the defects?
Press To Reveal
Defects
1.8 Skills
CS-1: Know if statement
CS-2: Know else statement
CS-7. Know how to use break statement within loop
1.9 Self Assessment
A user wants to print just the third element in a list, should it exist
Use the following template. This code, of course, prints out every element in the list. How would you change this code to print just the third one?
def printThird(): theList = input("Enter a list [a, b, ..., z]: ") for x in theList: print (x)
1.10 Version : 2014/01/29
(c) 2014, George Heineman