CS 110X Jan 31 2014
Expected reading: 208-214
Expected interaction:
Multiple branches
Input
1 First Review
Have the user enter in a list of numbers all in the range from (and including) 1 up to (and including) 9. You want to print out the smallest prime number that they entered.
1.1 Multi-Way decision
You have seen the if statement used to conditionally execute Python statements. To fully understand if, we need to describe all of its behavior.
In the simple case, the if has a condition that must be True for a body of statements to execute, as below:
>>> x = [2, 4, 8, 5, 10] >>> if 2 in x: print ("Great") Great
The above code prints Great because the value 2 is in the list x.
Sometimes you want to decide among two exclusive possibilities; to expand on the earlier example:
>>> x = [2, 4, 8, 5, 10] >>> if 3 in x: print ("Great") else: print ("Sadness") Sadness
Here you only want one of two possibilities to execute, and the deciding point is still the initial condition 3 in x. This statement is known as the if-then-else.
Now reflect on the earlier question. In the range of 1 through 9, the allowed primes are 2, 3, 5 and 7.
You want to do something like "if 2 is there, it is smallest; else if 3 is there, print that is smallest; else if 5 is there, that is smallest..."
Note you are trying to chain together logical statements. How can we do this in Python?
1.2 Wrong way to solve this problem
Here is an incorrect way to solve the problem. Can you see why?
def wrongWay(): x = input ("Enter in list of numbers in 1-9 range [a,b,...,z] ") if 2 in x: print ("2 is smallest") if 3 in x: print ("3 is smallest") if 5 in x: print ("5 is smallest") if 7 in x: print ("7 is smallest")
The problem is that each of these statements gets the chance to execute. What if the user had entered the list [2,4,5,6]? Then both 2 and 5 would be output as the smallest prime.
What you need is someway to guarantee exclusive execution of a statement.
1.3 Poor Way To Solve This Problem
The problem is that I have a four-way exclusive decision. The smallest value is either 2, 3, 5 and 7.
What if I started like this:
def smallestPrime(): x = input ("Enter in list of numbers in 1-9 range [a,b,...,z] ") if 2 in x: print ("2 is smallest") else: # somehow handle remaining cases
Now you need to handle the 3 case, which you can do by nesting an if statement within the else clause:
def smallestPrime(): x = input ("Enter in list of numbers in 1-9 range [a,b,...,z] ") if 2 in x: print ("2 is smallest") else: if 3 in x: print ("3 is smallest") else: # somehow handle remaining cases...
The final code looks like this:
def smallestPrime(): x = input ("Enter in list of numbers in 1-9 range [a,b,...,z] ") if 2 in x: print ("2 is smallest") else: if 3 in x: print ("3 is smallest") else: if 5 in x: print ("5 is smallest") else: if 7 in x: print ("7 is smallest")
This is certainly unwieldy and hard to follow because of the indentation.
To solve this problem, we need the elif statement which allows you to chain together a sequence of logical decisions in order. The very first one whose condition is True executes its body. Here is the code.
def betterSmallestPrime(): x = input ("Enter in a list of numbers in 1-9 range [a,b,...,z] ") if 2 in x: print ("2 is smallest") elif 3 in x: print ("3 is smallest") elif 5 in x: print ("5 is smallest") elif 7 in x: print ("7 is smallest")
Python will execute each of the logical conditions in the order provided by the programmer. At the first True condition, the associated body of statements will execute, and all others in that if-elif chain will be ignored.
To complete this discussion, what if you wanted to print that there were no single digit primes at all in the input? Then you would include a trailing else statement at the end of the long chain of elif statements. Here, truly, is the final code:
def lastSmallestPrime(): x = input ("Enter in a list of numbers in 1-9 range [a,b,...,z] ") if 2 in x: print ("2 is smallest") elif 3 in x: print ("3 is smallest") elif 5 in x: print ("5 is smallest") elif 7 in x: print ("7 is smallest") else: print ("No single-digit prime in your input")
1.4 Common misconceptions
For homeworks HW2 and HW3 you have worked with functions that are defined to have a parameter.
For example, the following function prints the square of 5:
def square(): x = 5 print x*x
But what if you wanted to have this function print the square of 7? You would have to rewrite the function. This seems like a waste of time.
Rather, you should parameterize the square function to it can print the square value of any number. To do so, introduce a parameter in the function definition:
def square(x): print x*x
Doing so gives you the opportunity to invoke the square function whenever you want and provide the value to be used for x within that function.
>>> square(5) 25 >>> square(7) 49
Take this logic one step further when you consider having a function that takes a list as an argument.
def printTable(values): for val in values: print (str(val) + " " + str(val*val))
As you can see, this function prints out a table of squares for each element in values.
The function declares that a single argument is to be passed to the function and inside the function, values refers to the list that was used.
>>> printTable([1, 4, 5]) 1 1 4 16 5 25
In the above example, within the printTable function, the variable values will be defined to be [1,4,5] which was the argument to the function.
I have seen some students make the following mistake:
# DON’T DO THIS!!!! def printTable(values): values = [] for val in values: print (str(val) + " " + str(val*val))
They have told me they were doing so because they wanted to declare that values was going to be a list. However, this instead simply destroys whatever list had been passed into the function and instead starts the function with values equal to the empty list.
1.5 Review Proceeds now...
CS 110X Programming Skills
These skills are fundamental to solving real problems in any programming language. All lectures, homeworks, quizzes and exams are designed to assess your knowledge of these key skills and the give you the opportunity to demonstrate you have mastered these concepts.
Python Programming Syntax
PS-1: Assign value to variable
PS-2: Know that in Python the type of the value determines the type of the variable
PS-3: Know how to insert comments into code fragments and modules
PS-4: Understand syntax errors
PS-7: Understand concept of IndentationError
PS-8: Understand context in which variables are defined
PS-9: Understand how indentation identifies body of statements
PS-10: Understand nested indentation
PS-11. Understand operator precedence and use of parentheses for clarity
Python Functions
PF-1: Know how to define a function
PF-3: Know how to use return statement within function
Python Modules
PM-1: Understand how to define a function within a module
PM-2: Understand how to import a module
PM-3: Understand how to define a variable within a module
PM-7: Know about pylab module
PM-9: Know about numpy module
Control Structures
CS-1: Know if statement
CS-2: Know else statement
CS-3: Know elif statement
CS-4: Know how to nest if statements
CS-5: Know how to use range in definite for loop
CS-7. Know how to use break statement within loop
CS-9. Write definite for loop
CS-11. Understand logical and, or, not operators
CS-12. Understand comparative operators {<, <=, >, >=, ==, <>, !=}
String Manipulation
SM-2: Know how to convert floats and integers into string
SM-3: Know how to concatenate string literals
SM-4: Know how to read string input from keyboard
Input Output
IO-1: Know how to print information to the console window
Data Types
DT-1: Know basic data types of int, bool, char, float
DT-2: Know basic mathematical operators {-, +, *, /, **}
DT-3: Know how integer division truncates values
DT-6: Know how to insert an element into a list
DT-9: Know how to access and modify individual elements of a list
DT-10: Know how to iterate over elements of a list
Debugging Skills
DG-1: Identify an arithmetic defect
DG-2: Identify logic defect
DG-3: Identify syntax defect
DG-5: Demonstrate by-hand execution of small code fragments
1.6 Exam Format
When you come to the exam on Monday, you will not be able to use your laptop computer, textbook or even the clicker!.
You will be allowed to bring in a single piece of 8.5" x 11" paper on which (front and back) you have hand-written any concepts in the course. Take advantage of this opportunity. In many ways, this sheet of paper will become the best study guide you could hope for.
We have seen a number of question types so far. These are good indications of the kind of questions I ask.
The Debug Question – I will show you sample code and then ask you to identify four things wrong with it (there will be likely five). You are to circle the things that are wrong, and explain what should be there instead.
Sample Input – I will show you some code that asks for input from the user. Then I will ask you to come up with some input that will cause the program to produce specific output. Note: If input calls for a list then be sure to use [a,b,...,z] notation
Write small program – write a small program given the requirements I provide.
Specific Python Knowledge – I may ask a question about a specific Python statement and you should be able to answer it based upon your knowledge derived from the lectures, labs and homework assignments.
Review past sample exams as found in the Study Guide materials for the course.
1.7 Version : 2014/02/05
(c) 2014, George Heineman