Control
Relational Operators
< less than > greater than <= less than or equal to >= greater than or equal to == equal to != not equal to ● Note that == is equality, = is assignment
Guessing Loop
>>> SECRET = 6 # CONSTANT >>> guess = int(input("? ")) # "priming read" >>> while guess != SECRET: # meaningful (readable) condition >>> print("Guess again!") >>> guess = int(input("? ")) # same as priming read >>> print("You got it!") ● This is THE standard while loop format we want you to learn. ● Note that the line before the loop header (condition) is the same as the last line of the body
Python if statement
>>> if boolean expression: >>> suite 1 >>> else: suite 2 ● evaluate the boolean (True or False) ● if True, execute all statements in the suite 1 ● if False, execute all statements in the suite 2
Using else in complex decisions
>>> if num > 0: print("You Entered " + str(num)) else: print("Invalid Number")
Example: avoid division-by-zero
>>> numerator = int(input("Enter a numerator: ")) >>> denominator = int(input("Enter a denominator: ")) >>> if denominator != 0 and numerator % denominator == 0: print("Okay") >>> else: print("Error")
Selection - if statement
>>>if boolean expression: >>> suite ● evaluate the boolean (True or False) ● if True, execute all statements in the suite
Selection - if-else statement
>>>if boolean expression: >>> suite1 >>>else: >>> suite2 The process is: ● evaluate the boolean ● if True, run suite1 ● if False, run suite2
Binary decision
A decision that is either (True) or (False), in hardware either zero (0) or one (1).
Boolean condition
An expression that is true or false. If the condition result is (True), the program executes one set of statements; if it is (False), the program executes a different set of statements.
Boolean expressions can be varied to be more readable
Consider this example: number = int(input("Enter number: ")) while not (number >= 1 and number <= 10): print("Error - number is outside the range 1-10") number = int(input("Enter number: ")) Which can be redesigned and simplified as: number = int(input("Enter number: ")) while number < 1 or number > 10: print("Error - number is outside the range 1-10") number = int(input("Enter number: ")) the second statement is also quicker to execute because: if number < 1, it does not evaluate the RHS condition; whereas the first statement evaluates both LHS and RHS conditions
Using elif in complex decisions
Elif(else if) is used for each branch other than the first if there is a condition to evaluate: >>>If score < 50: print("Fail") elif score <65: print("Pass") elif score <75: print("Credit") elif score <85: print("Distinction") else: print("HighDistinction")
Potential Problems (with your code)
Loop never starts: ● the control variable is not initialized as you thought (or perhaps you don't always want it to start) Loop never ends: ● the control variable is not modified during the loop (or not modified in a way to make the Boolean come out False) ∈ INFINITE LOOP
De Morgan's laws
NOT (number > 1 or number > 10) equivalent to number <= 1 AND number <= 10
Structure of decisions in coding
Structure: >>> if <condition>: <code goes here> elif <condition>: <code goes here> else: <code goes here> ● There is 1 initial if statement ● Program checks to see if the first if statement is true, if so it executes the instruction under it ● System will check each following condition until it finds one that evaluates to true, or comes to the bottom of the block ● We can have as many elifs (else if) as we need ● If we want some action to occur no matter what, we use a final else statement
Control in programming
There are two kinds of control that form the basis of all computer programming: 1. selection (making decisions) 2. repetition (performing an operation over and over).
Types of loops
Two 'categories' of iterations: -Definite (we KNOW how many times) -Indefinite (no way of knowing) ● 'while' loops for indefinite ● 'for' loops for definite
What does Equality mean?
Two senses of equality: ● two variables refer to different objects, each object representing the same value ● value equality ● two variables refer to the same object. Both objects have the same ID. ● reference equality --> The id() function used for this.
Choosing between while and for
Use: ● for loop for fixed (definite) repetition ● The number of iterations is a fixed value (e.g. do something n times) ● we know how many times it runs before it starts and what value the loop iterates over Examples: ● get user to enter 5 numbers ● once for every line in a file ● once for every value in a list ● while loop for variable (indefinite) repetition ● we don't know how many times it will run ● keep looping UNTIL some condition is met ● condition may never be met ● often used to validate USER INPUT ∈ if user input is valid, the while loop may never run
Developing a while loop
Working with the loop control variable: ● 'While' loops often evaluate a particular variable ● Initialize the variable, typically outside of the loop and before the loop begins. ● The condition statement of the while loop involves a Boolean using the variable. ● Modify the value of the control variable during the course of the loop to avoid an INFINITE LOOP
multiple assignments
a, b = 2, 3 -> first on right assigned to first on left, second on right assigned to second on left print(a, b) # prints 2 3 a, b = 1, 2, 3 ->Error counts on lhs and rhs must match
Swap using multiple assignment
a, b = 2, 3 print(a, b) # prints 2 3 a, b = b, a print(a, b) # prints 3 2 ● remember, evaluate all the values on the rhs first, then assign to variables on the lhs
Boolean operators
and, or & not
Python Selection
if boolean expression1: suite1 elif boolean expression2: suite2 (as many elif's as you want) else: suite_last
equal vs. same
● == compares values of two variable's objects, do they represent the same value ● 'is' operator determines if two variables are associated with the same value Example: a_float = 2.5 b_float = 2.5 c_float = b_float Namespace Object ID a_float 2.5 9933140 b_float 2.5 9933092 c_float b_float 9933092 a_float == b_float -> True a_float is b_float -> False b_float is c_float -> True
Break statement
● A break statement in a loop exits the loop ● It exists immediately, skipping whatever remains of the loop ● Use Break statement sparingly ● AVOID using while True ∈ INFINITE LOOP ∵ always true >>> while True: >>> suite >>> break # required to exit infinite loop ● better to use a control loop variable: >>> user_num = int(input("Enter a number: ") >>> while user_num < 0: >>> print("Number must be greater than zero") >>> user_num = int(input("Enter number: ") ● To avoid an INFINITE LOOP, you must re-test the Boolean condition on the last line of the 'while' loop suite ∈ update the condition!
Continue statement
● A continue statement, if executed in a loop, means to immediately jump back to the top of the loop and re-evaluate the conditional ● Any remaining parts of the loop are skipped for the one iteration when the continue was executed ● Continue statement has limited uses!
'Sentinel Loop'
● A sentinel loop is a loop that is controlled by a sentinel—a guard. The sentinel is a particular value used to terminate the loop. ● The Boolean expression will be in the form: while not sentinel value:. value = some value while value != sentinel value: # process value # get another value
Example of 'while True:'
● A while loop controlled by 'while True:' will loop forever, i.e. an infinite loop Example: >>> while True: >>> for x in range(6): >>> y = 2 * x + 1 >>> print(y) if y > 9: break 13579111357911135791113579111357911135791113579111357911135791113579111357911135791113579111357911135791113579111357911135791113579111357911....... ad infinitum until max memory
while True?
● Be judicious in your use of break statements ● When you read a loop header, you should know when the loop will terminate, but when you read "while True", you have to keep reading to find out --> what is the exit condition? ● True will never be false --> need to use a break to exit the loop (BAD) ● Do NOT use while True loops and/or break statements, unless they are the best solution ● break IS only a good option in some situations ● while True is good in even fewer situations ● better to use a meaningful (readable) condition
Repeating statements
● Besides selecting which statements to execute, a fundamental need in a program is repetition: ● repeat a set of statements under some conditions ● Requires a condition for when to stop ● With both selection and repetition, we have the two most necessary programming statements
Compound decisions
● Can combine decisions with boolean keywords: - And, Or, Not ● E.g. If temp >35 and temp < 40: ● Each side MUST be a full decision temp > 35 and < 40 is not possible
Compound Statements
● Compound statements involve a set of statements being used as a group ● Most compound statements have: ● a header, ending with a : (colon) ● a suite of statements to be executed ● if, for, while are examples of compound statements
Decisions in coding
● Every 'decision' involves a comparison: ● So what can be compared? -Number to number, number to words ● Each comparison will evaluate whether a statement is true or false >>> if age > 18: >>> do something ● Once the program finds a statement that is true it executes it, and jumps out of the if statement to the next code block
Chained comparisons
● In Python, chained comparisons work just like you would expect in a mathematical expression: ● Given number has the value 5 ● 0 <= number <= -> True ● 0 < number <= 5 > 1 -> False
The Accumulator Pattern
● One common programming "pattern" is to traverse a sequence, accumulating a value as we go, such as the sum-so-far or the maximum-so-far. ● That way, at the end of the traversal we have accumulated a single value, such as the sum total of all the items or the largest item. ● The anatomy of the accumulation pattern includes: 1. Initializing an "acccumulator" variable to an initial value (such as 0 if accumulating a sum). 2. Iterating (e.g., traversing the items in a sequence). 3. Updating the accumulator variable on each iteration (i.e., when processing each item in the sequence). Example: >>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> sum = 0 >>> for number in numbers: >>> sum = sum + number >>> print sum
Precedence & associativity
● Precedence & associativity (order) of relational operators: highest to lowest. Operator Description () parentheses (grouping) ** exponentiation +x, -x positive, negative *,/,%,// multiplication, division, remainder, quotient +,- addition, subtraction <, <=, >, >=, !=, == Comparisons not x Boolean NOT and Boolean AND or Boolean OR
Boolean variables
● Python explicitly represents the values of True and False in a type , called a Boolean ● The type Boolean has a value of True or False ● Boolean value True is stored as 1 in computer code ● Boolean value False is stored as 0 in computer code
Boolean operators vs. relationals
● Relational operations always return True or False ● Boolean operators (and, or & not) are different in that: ● They can return values(that represent True or False) ● They have short circuiting
Selection
● Selection is how programs make choices, and it is the process of making choices that provides a lot of the power of computing
Selection -'if-elif-else' Statement
● The 'elif' is simply shorthand for "else if"—a shorthand that also exists in some other languages. >>>if boolean expression: >>> suite1 >>>elif boolean 2 >>> suite2 >>>elif boolean 3 >>> suite2 >>>else: >>> suite4 The process is: ● evaluate the boolean ● if True, run suite1 ● if False, evaluate boolean 2 ● if True, run suite 2 ● if False, evaluate boolean 3 ● if True, run suite 3 ● if False, run suite 4
for loop and iteration
● The for statement iterates through each element of a collection (string, list, file etc.) >>> for element in collection: >>> suite ● the element is the target variable ● collection is an iterable with n items in it, e.g - list - dict - files
range function
● The range function represents a sequence of integers ● the range function takes 3 arguments: range(start, end, step) 1. the beginning of the range. Assumed to be 0 if not provided 2. the end of the range, but not inclusive (up to but not including the number). Required 3. the step of the range. Assumed to be 1 if not provided ● if only one arg provided, assumed to be the end value
Short-circuit evaluation is useful
● This turns out to be very important - especially if the RHS expression might cause the program to crash! The rules: ● If the LHS of an and expression evaluates to False, then the RHS is not evaluated ● If the LHS of an or expression evaluates to True, then the RHS is not evaluated
while loop
● Top-tested loop (pretest) ● test the Boolean before running ● test the Boolean before each iteration of the loop while boolean expression: suite
Chaining for assignment
● Unlike other operations which chain left to right, assignment chains right to left a = b = 5 print(a, b) # prints 5 5
General approach to a while
● outside the loop, initialize the Boolean ● somewhere inside the loop you perform some operation which changes the state of the program, eventually leading to a False Boolean and exiting the loop ● Have to have both! ● To avoid an INFINITE LOOP, you must re-test the Boolean condition on the last line of the 'while' loop suite ∈ update the condition!
What is True, and what is False?
● true - any nonzero number or nonempty object: 1, 100, "hello", [a, b] ● false - a zero number or empty object: 0, "",[], {} ● Boolean values called True and False, which are just subs for 1 and 0. However, they print nicely (True or False) ● Also a special value, None, less than everything and equal to nothing
Checking values are within or outside a range
● usually for error checking ● To determine if a value is within a range we use the 'and' operator and appropriate relational operators E.g. (age > 4) and (x < 19) ● But, to determine if that value is outside of a range we use the 'or' operator instead and opposite relational operators E.g. (age <= 4) or (age >= 19) ● can use NOT to flip the argument
While and For statements
● while is the more general repetition construct. It repeats a set of statements while some condition is True. ● or until some condition is False (opposite way of thinking about the same thing) ● for is useful for iteration, moving through all the elements of a data structure, one at a time.