Lecture 12: While Indef Loops (LOOP STRUC AND BOOLEANS), ch 7 and 8 code

¡Supera tus tareas y exámenes ahora con Quizwiz!

Utilizing While Loops

A "While" Loop is used to repeat a specific block of code an unknown number of times, until a condition is met. For example, if we want to ask a user for a number between 1 and 10, we don't know how many times the user may enter a larger number, so we keep asking "while the number is not between 1 and 10".

Counting Loop

A counting loop iterates a specific number of times. It is often used when the number of iterations is known in advance. count = 0 while count < 10: print(count) count += 1

Processing Loop

A processing loop iterates over a collection of data and performs some action on each element. It is often used for data manipulation and analysis. numbers = [1, 2, 3, 4, 5] index = 0 while index < len(numbers): numbers[index] = numbers[index] * 2 index += 1 print(numbers) # Output: [2, 4, 6, 8, 10]

Sentinel Loop A sentinel loop reads input until a specific value, called a sentinel, is entered. It is often used for input validation.

A sentinel loop reads input (keep processing data) until a specific value, called a sentinel, is entered. It is often used for input validation.-->sentinel val indicates end sentinel = -1 input = int(input("Enter a number (-1 to stop): ")) while input != sentinel: print("You entered:", input) input = int(input("Enter a number (-1 to stop): ")) sentinel value could just be value within our range -accidentally reserve -1 for sentinel , cannot put in list now -sentinel should not be value we're inputting, even entering letter not number that won't interfere with input

Infinite Loop

An infinite loop continues indefinitely until it is explicitly exited. It is often used for event-driven programming or when the loop condition is intentionally left blank. while True: # Do something indefinitely

cooling and heating day counter

As we don't know in advance how many days the user will input, we will use a whilewhile loop. To control the loop, we'll create a Boolean variable donedone which we'll initialize to false. Once the user signals that they're done entering data, we will then set donedone to True and end the loop We can use two accumulators to keep running totals for the numbers of heating and cooling degree-days. We use an if/elifif/elif structure to determine when to add to each running total.

lexicographic unicode ordering means ? comes before aaaa because

Bbbb because uppercase letters 65 to 90 , or 0041 starting lower at unicode also matches boolean expression "Hello" < "hello" command <myfile>.py-->direct file running import module first then call main to run, so not just running when imported, make call to main conditional If <cond> main() import math math.__name___ 'math'-->assign to string repping module's name, showing what math's name is when imported or __name__ directly run is '__main__'-->value of name

Boolean Algebra

Boolean algebra is a branch of mathematics that deals with logical statements and their relationships, such as evaluating the truth or falsity of statements and the relationships between them. T/F OF LOGICAL STATEMENTS, STATEMENT RELATIONS Boolean algebra is used in computer science, electrical engineering, and other fields to model logical operations, such as in digital circuits, programming languages, and decision-making processes, where it enables the design and analysis of systems and processes based on logical principles.

What is a While Loop?

In most computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.

while loop to find time to investment doubling aka condition = when investment is double, keeps asking user until double or greater balance tracking yr with iterator

Recall that each year, the balance of an account making rr interest is increased by r⋅(old balance)r⋅(old balance). That is, the balance after nn years, B(n)B(n), is given by annualized interest rate = So we just need to use this formula to keep iterating the balance until it is at least two times the principal amount. So if we stop when balance >= 2*principalbalance >= 2*principal, then we continue while balance < 2*principalbalance < 2*principal. This is the condition we use for our whilewhile loop. Note that in addition to keeping track of the balance in the account, we need to use an accumulator to keep track of how many iterations we've gone through -- i.e. how many years the account has been accumulating interest. It's this accumulator variable that we'll be printing out for the user. keep adding interest to balance until reached year start Principe any value, eval around inp state for interest bal=initial? year == 0 will trigger yrs to be printed when balance no longer below double principal amt

The line ? would not appear in the truth table for andand. This line would mean that

TFT would not appear True and False == True But of course we know that this is false because an and expression only evaluates to true IF BOTH are TRUE its operands are true.

break Statement

The break statement is used to exit a loop early. When a break statement is encountered in a loop, the loop is immediately terminated, and the program continues executing from the next statement following the loop.

continue Statement

The continue statement is used to SKIP over an iteration of a loop. When a continue statement is encountered in a loop, the current iteration of the loop is immediately terminated, and the program continues executing from the next iteration of the loop.

The line ? would not appear in the truth table for andand. This line would mean that

The line FTFFTF would not appear in the truth table for oror. This line would mean that False and True == False But of course we know that this is false because an or expression only evaluates to false if both of its operands are false.

Common Loop Patterns

There are several common loop patterns used in computer programming such as: - Counting Loop - Sentinel Loop - Infinite Loop - Validation Loop - Processing Loop

equiv to I = o while I <= 10: print(i) I = i + 1 ## next extra two steps to deal w loop variable ,

for I in range(11) print(i) need

Common Mistakes with While Loops

for loop iterate for us , but while loop is manual by DEFINING and INCREMENTING iterator A common mistake with while loops is forgetting to update the loop variable, which can result in an infinite loop or unintended behavior. An infinite loop is a programming construct where a set of instructions is repeated endlessly, resulting in the program becoming unresponsive and requiring manual intervention to terminate. In addition to infinite loops, an incorrect condition in a loop can cause errors such as unexpected termination or repeated iterations.

sentinel algorithm (data dif from input data, not processed as part data ) pre-loop at top makes such ? val not sentinel

get first it-->priming read, starts process, prime to see if value is sentinel will terminate loop right there while not sentinel process item get next item each val not sentinel

quadratic solver

gets ValueError of math domain error

indef loop , cond tested at ? loop , aka ? test loop

go until cond met while <cond(bool expr)>: #using while statement for indef loop <body> test at loop top, pre-test loop #need running total to keep program running?-->yes, keeps I = o from just being reassigned to 0each time as control returns to condition

two way decisions

if <cond>: <statementS> else <cond>: <statements>, control passing to statement following if-else either way

main r running right when prog invoked, not if imported

if __name__ '_ _main__': main()

nesting for 3 way decision

if dsicrim < 0 : print("No real roots!") else: #nest last two in else state if dsicrim == 0 : root = -b/ (2*a) and print double root at on next line else: regular root stuff elif would not make decisions complex branching off, if else nested in that if <cond1>: <ase1 statment> if <cond2>: again execute statements indented in heading of conditional statement again control going to to next state after entire ifelifelse, for any. number mutually exclusive code blocks

loop and half to sentinel pattern

if item sentinel: break before processing item (only process if answer to condition of it being sentinel is a no

input default value

if user hits enter key , the default string can be treated as Boolean meaning if ans != "": (empty string), then we dont' print vanilla in brackets which is the default statement without answer entered (just hitting enter) empty string would be false, then goes to else clause based on Bool condition deciding how to set string variable , replaced by Vanilla in else clause strings as Booleans selves, using or statements ans = input("what flavor do you want [vanilla]: ") flavor = ans or "vanilla"->equiv to if-else or flavor = input("what flavor do you want [vanilla]: ") or "vanilla"

decision tree for max val of three, problem

if x1 >= x2: if x1 >=x3: maxval = x1 (2 more decisions from first decision) will make exactly two comps in decision tree alg decision tree=complexity explosion

nonstandard loop

loop and a half, using while loop having condition of True, and using break statement to provide loop exit and and or bool operators use short-circuit evaluation and definitions to be usable for data types, other data types can be used where Boolean expr are expected

sequential approach for max three

maxval = 1 reassign each maxval one by one

event.loop2.py for color changing window

must handle click and key each in dif functions pass statement does nothing for mouse click , fill in spot where expecting statement if key != "" or if pt != None is checked, need to do something if got a key or got a point

getting user input as string, average4.py

non numer string and all others treated as data, empty string as "" input data item as string, xStr -->python is x = input("enter a num<enter> to quit >>") while not empty ##""empty not convert to num ##again sentinel checking if input not sentinel 2 convert xStr to a number, x = float(xStr)

For each of the below tables, first start by writing down all of the possible inputs in the leftmost region. Then work your way rightward one column at a time using the definitions of notnot, andand, and oror as well as the values already evaluated in the columns to the left of the one you're working on. making truth showing Boolean val of the following expressions not (P and Q) is false when?

not (P and Q)-->false if P and Q is true aka always true with and expression being false, so true whenever one or both P and Q are false

? operator is unary

not operator, operates opp fashion as Bool expression

nested loop

now any amt numbers on line in our file w numbers, must add line. in our file-processing loop , while loop still once per file line, for loop nested in while loop iterate as much as needed for one line while line != "': for xStr in line.split(",") total = total + float(xStr)

Validation Loop

A validation loop prompts the user for input UNTIL valid input is entered. It is often used for input validation input = int(input("Enter a number between 1 and 10: ")) while input < 1 or input > 10: input = int(input("Enter a number between 1 and 10: ")) print("You entered:", input)

continue Statement Flowchart

ONLY EXIT IF COND FALSE, JUST CONTINUE IF TRUE TO NEXT CONDITION WHERE NUMBERS NOT EVEN IN LIST (ONLY ODD GET TO PRINT)

Truth Tables

Truth tables are used to show the results of logical operations. A truth table for an operation shows the possible combinations of input values and the resulting output value. Truth tables can be used to simplify complex logical expressions and to verify the correctness of circuits and programs.

valid bool algebra rules

(False and x) == False Looking at the truth table defining and,, we see that the expression on the LHS will always evaluate to False, regardless of the value of x. Hence this is true. (True or False) == True This is just a special case of (a). So it is also true. same as below (True or x) == True Looking at the truth table defining oror, we see that the expression on the LHS will always evaluate to True, regardless of the value of xx. Hence this is true. not(a and b) == not(a) and not(b) This is false. Looking at deMorgan's law, we see that the expression on the RHS should contain an oror, not an andand.

For each of the below tables, first start by writing down all of the possible inputs in the leftmost region. Then work your way rightward one column at a time using the definitions of notnot, andand, and oror as well as the values already evaluated in the columns to the left of the one you're working on. making truth showing Boolean val of the following expressions (notP) and Q

(notP) and Q--> p is false always ALWAYS START EACH SCENARIO W ALL COMBO T/F FOR P AND Q when P true not P false, not P and Q false when not P and Q aren't both true (P must be false and Q must be true)-->the only condition where (notP) and Q is true

bool op combining two expressions, simple cond and a string

(response[0] == "y") or ("Y"):-->"Y"= nonempty string, always true either result of first response is true when the response is Y or y , entire or is true if one is true

n > 2 prime if whole num bw 2 and sqrt(N) evenly divides n, prog to see if prime , quit finding val evenly dividing n if not prime

*getting number in while loop *condition to exit is while not evenly divisible **calculate if divisible

boolean operator syntax

<expr> and <expr> <expr> or <expr>

rel ops

>= or != or <=

ch 8 discussion :(a) Definite loop vs Indefinite loop (b) For loop vs. While loop BASICALLY A (c) Interactive loop vs. Sentinel loop

Both are examples of loop structures which means that they cause the SAME code to repeat (iterate) SEVERAL times in a program both repeat code sev times The difference is that a definite loop structure iterates a specific number of times that is known (or can be figured out) BEFORE the code is RUN An indefinite loop will just continue iterating until its condition expression is false. This is OFTEN used to get an UNKNOWN number of INPUTS from the USER (b) For loop vs. While loop Both are examples of how Python implements loop structures. forfor is the usual loop used for a definite loop structure and whilewhile is the usual loop used for an indefinite loop structure... Both of these are examples of indefinite loop structures. An interactive will ask if the user wants to continue after getting each input while a sentinel loop will only repeatedly prompt the user for input but will allow the loop to end when a specific value (or set of values) called the sentinel value is input. USER MUST END INTERACTIVE, SENTINEL WILL KEEP PROMPTING , SENTINEL HAS CERT VAL ENDING IT d) Sentinel loop vs. End-of-file loop Sentinel loops are described in part (c). An end-of-file loop is an indefinite loop that will continue getting input from a filefrom a file UNTIL the end of the file is reached This basically works the same way as a sentinel loop except that now you're getting input from a file instead of the user and the sentinel value is some signal that the end of the file has been reached (usually when the input is the empty string). end file=sentinel getting user input .

Adding Additional Functionality to Loops

In addition to while loop patterns, utilizing statements like break or continue can add extra functionality to loops. These statements allow you to control the flow of the loop and can help you to achieve specific programming goals. break and continue add functionality

T/F Note that if you don't need to read all the way to the end of the file, you can just use a breakbreakstatement to exit the loop early. easiest looping thru file:

True. The counted loop pattern iterates a definitedefinite number of times so it is an example of a definitedefiniteloop. That is, we know at the outset exactly how many iterations a counted loop will go through False. An interactiveinteractive loop asks the user whether to continue on each iteration. A sentinelsentinel loop checks that a special value called the sentinel hasn't been reached on each iteration. True. The sentinel value is just a way to end the loop -- it's often something that can'tcan't even be processed. For example, you might be averaging numbers input by the user but use the string "quit""quit" as your sentinel. Obviously, you can't process that string as a number. False. The easiest way to iterate through the lines of a file is with the syntax for line in :

Summary of While Loop

While loops are essential programming constructs that allow for repeated execution of a block of code based on a given condition. They are highly versatile, as they can handle varying data sizes and adapt to changing conditions during runtime. Using while loops can improve the efficiency and functionality of code, making them a valuable tool for programmers.

Breakout Coding: Input Validation Advantages of Utilizing a While Loop

Whole loops can be better than for loops in certain cases because they allow forgreater control and flexibility in iterating over a collection of data. This is especially useful when the number of iterations is unknown (in advance) or may vary, aswhole loops can adapt to different data sizes without the need for manualadjustments. We can also filter input as we just saw

Combining break and continue Statements

You can use break and continue statements together to achieve more complex flow control in loops. For example, you might use a break statement to exit a loop early and a continue statement to skip over certain iterations.

Suppose in each of these that nn is assigned some positive integer -->while loop fragment getting following values

a) sum first n numbers sum = 0 number = 1 ##need a counter for numbers while number > 0: number = int(input('Enter a positive number: ')) if number > 0: sum = sum + number print("The sum of the numbers is", sum) b) first n odd numbers

A pre-test loop structure tests the condition before each iteration. A post-test loop structure tests the condition ? each iteration.

after EACH ITERATION

indef aka ? loop condition tested at ?

aka conditional loop while <condition>:-->sharing boolean with if statement <body> if cond false would be in range we want for example in 1 to 100 test at top b4 body exec if no i = i + 1 increments, then will keep printing zero , control staying at condition, infinite loop accidentally

unary operator

an operator that has only one operand P true means not P is false

interpret int as Booleans

any int nonzero is True empty sequence false bool type, any non empty seq is true

follow error type with an ?<variable> in except clause, gives the ? the actual exception object

as <variable>, assign variable to exception obj (a string) after turning excepton into string and looked at message to see what caused Value error

getting non neg num from user: post-test loop similar to ?

asking for other input if invalid , input validation does this until getting correct value get a number from the user until number is >= 0 condition test after loop body=post-test loop , must exec body at least once number = -1 illegal val to get into loop while num < 0 number = float(input("enter positive number") post-test loop similar to interactive or more direct use break statement while True: (infinite loop bc continues to true) number = float(input( if number >= 0: break --one line if-break possible can also add if number < 0: and print an error or if using break and want error warning if number >= 0: break else: print("num entered not positive") or just if number >= 0: break and print statement of error, loop and a half, exit in middle of loop can express sentinel as loop and a half , like certain keys to change color on drawing a graphics window , called event loop , each time thru event loop waiting for user printing on keyboard with line key = win.getKey()

if ans!="":

being treated as boolean ans = input ("flavor you want[vanilla]: ") if ans:-->this cond false w empty string , aka enter pressed flavor=ans else: flavor = "vanilla"-->default when enter pressed or flavor = ans or vanilla flavor = input("flavor you want [vanl]: ") or "vanilla"

prog comp decisions boil to ? expressions, and why? and operator in Boolean algebra used similarly to?

boil to boolean expr they obey algebraic laws a*0 = 0 a and false == false bc zero is false , and operator used similarly similar to multiplication, 0 and 1 corresponding to t/F or sim to adding they distribute over each other rows in truth tab each w distinct cases for the variables , and values of subexpressions in identity ideal: not rlly (notscoreA == 15 or scoreb==15) instead: while scoreA !==15 and same for b: keep play

The ? statement will cause a loop to immediately terminate. Note that a breakbreakstatement inside the inner loop of a nested loop structure will only break you out of the inner loop, not both. BREAK = OUT OF ? LOOP ONLY

break statement to terminate loop, break out of ONE LOOP

counted loop for average.py running tot sum needs?

dealing w n numbers using counted loop total = 0.0 accumulator for each loop iterator would put in num you have for counted loop design main: n = int(input("how many num you have? ")) total = 0.0 (where running tot starts) for I in range(n): another input for floating pt number total = total + x computer take care large amt num for us, wouldn't be good with for loop (num not entered yet)

max.py

def main(): n = int(input("how many num are there?") **setting max to first val maxval = float(input("Enter Number"), then comp n-1 following/succes vals for I in range (n-1): enter another float num called x if x > maxval: maxval = x contain largest val seen thus far for each iteration

avg 3 number need multiple conditions if any of three greater than other 2 , need keyword?

def main(): x1, x2, x3 = eval(input("Enter 3 values: ")) 3 way to find the maxval x1>= greater than others acceptable but bad syntax, not just inline or one line need multiple conditions if any of three greater than other 2 keyword and

graphical user interface, driven by?

driven by event loop draw GUI while True: get next event if event "quit signal": break process event clean up and exit sentinel the q key, basically sentinel loop and a half, interactive handling key presses until "q" key: while True: key = win.getKey()-->user prompt if key == "q" break process the key: if key == "r" win.setBackground("pink") elif for other colors win.close() getMouse() makes prob for any keyboard input -->modal input=locked into certain mode interaction, nonmodal needs both methods while True: key = checkKey()-->user prompt, no key pressed return empty string, examine key val without stopping to wait if key is quit signal: break if key is a valid key: process key click = checkKey() if click valid: process Click clean up and exit if no event on certain iteration(click or key) goes again prompting g

avergae6 .py sentinel version, what is the sentinel?

empty line at end of readline infile = open(filename, 'r') total = 0 count = 0 while line != "": total = total + float(line) count = count + 1 line = infile.readline(), reading In next number end of file loop

loop and half , avoids what? alg to avoid this

exit middle of loop while Tr: number = float(input("Enter pos num: ")) if number >= 0: break print("Num entered not positive") exit in middle loop body avoid priming of sentinel loop avoid priming with loop and half by: while Tr: get next item if next item is sentinel: break process next item

control structs using boolean conditions and is true when? bool expressions still have?

if, while, bool expressions eval to T/F False and True literals nested coordinate decision if p1.getX() == p2.get(X): if p1.getY() == p2.getY(): combining bool expressions to also show output in truth table and of two expr true when both expr are true, only either P and Q being false makes P and Q false adn true when P and Q true the or of two expr true when either expr are true, only either P and Q being false makes P and Q false adn false when P and Q both false precedence in opérations high to low = not, and, or (a or ((not b)) and c)-->use parenth for complex bool expressions if p1.getX() == p2.get(X) and p1.getY() == p2.getY(): # 2 simple conditions

quadratic.2py

import math print statement( " \n") a, b, and c float inputs if dsicrim >= 0 : discRoot = math.sqrt (discrim) both root eqns use discroot

quadratic3.py and quadratic4.py

import math def main(): print statement( " \n") a, b, and c float inputs full eqn discrim if dsicrim < 0 : print("No real roots!") else: discRoot = math.sqrt (full equation for discrim) and print two roots both root eqns use discroot-->one if statement, not giving statement if no real roots import math def main(): print statement( " \n") a, b, and c float inputs full eqn discrim if dsicrim < 0 : print("No real roots!") elif discrim == 0: root equation for double root else: discRoot = math.sqrt (full equation for discrim) and print two roots both root eqns use discroot-->one if statement, not giving statement if no real roots used decision structure to prevent neg error input,(for rare, possible errors), checking data b4 sqrt call exception handling for other errors when prog running rather than in each step, wrapping all steps you wanna try in the try statement

recursive Fibonacci

in vsc,

average2.py using counter

in. main total 0.0 count = 0 moredata = "Yes" #no list, just assume more data while moredata[0] == "y" #first letter input enter float number, store in variabel x total = Total + x count = count + 1 #end w prompt for more data moredata = input("got more num>" )) print(ave number is " , total/count) user not counting data Vals, but constant asking at each loop until press n

avergae5.py file loops , each file line= one num

infile = open(filename, 'r') total = 0 count = 0 for line in infile: total = total + float(line) count = count + 1

while response[0] == "y" or "Y"

infinite loop

interactive loop using ?

infinite loop for continuous user input, modifying to keep track of amt numbers with a counter

The infinite loop never finishes (?), runs indefinitely.

infinite never terminates

Let's say you want to continue getting INPUT from the user UNTIL some condition is reached. Then we'd use a loop structure with an INPUT statement ? the loop A ? read is when you get your initial value from the user before the loop begins. Priming reads are typically a part of the pattern for sentinel loops where we need the input variable to be initialized before we can test whether it contains the sentinel value.

inside FOR USER UNTIL CONDITION REACHED priming READ, variable getting input is given value of input before testing if has sentinel value

bool = ? type and ? operators

int type 1 or 0 to print as True or False literal short-circuit operators, T/F returned right when value known

MC A loop pattern that asks the user whether to continue on each iteration is called an

interactive loop INTER=INPUT ON EACH ITERATION Contrast this with a sentinel loop which is a loop pattern that continue until a special value -- called the sentinel value -- is input.

indefinite loop use: ? pattenrs

interactive loops add separate count accumulator to avg program to track amt in list stop at any time w user input, more data? set to yes while more data is yes get next items process next item ask if more data before anything initialize total and count , adding x to total and 1 to count output total/count moredata[0] looks at first user inp letter (y only for yes), once nope it gives u average , not need counting, interactive needs constant data prodding

loop accumulator purpose, in this case for a for loop n would be input of count of nums

keeping running sum , in this case for a for loop n would be input of count of nums input another num in while loop, output avt as this total (accumulator total adding x) each number added to Total when given by user-->num iteration still need to be known when loop called, but won't know til user input done

Bool express as decisions, not just as control structure

keeps going if user responds with y must be while response[0] == "y" or "Y" but not combined , would be always true

three bolean operators: and, or not and expression and or shown in ? both expr must be false, as shown in ?

operators and and or combine 2 bool expr and bool result shown in truth table truth table defining the or operator for or expresion not=unary, not P or not Q=the one expression

False. A whilewhile loop is a ?-test loop because it tests the condition before evaluating the body of the loop. A post-test loop would first evaluate the body once before testing the condition. Note that Python does not actually have a type of loop especially designed as a post-test loop: we have to be slightly creative to use a whilewhile loop to achieve the same effect.

pre test loop b4 loop body This means that the body of a whilewhile loop may not be executed at all if the condition is initially false, but a post-test loop will always execute the body of the loop at least once.

quadratic6.py, mult except statements like elifs

prog checking error occurring print(") try statement except Valueerror (except statement w two value errors) as randomstring excick **this except catching math domain or if invalid coeiffs given if str(ejnfje) == "math domain error": printing("no real roots") else: print"Invalid coif") except: $default if no error type matches print("\nSomething went wrong")

interactive loop

program parts repeated to user's wishes-->this loop is one use of indef loop sentinel loop=input until special val hit , but sentinel NOT processed

input validation vs post-test loop simulate post loop with ?

repeat get num from user until num is >= 0, loops till value acceptable , may not exec body number = -1 while num < 0: number = float(input), post test bc making alg go at least once, naturally comes w interactive loop with break statement if number >= 0: break, body with only one if statement makes this legal

ball game over volleyball game

scoreA==15 or scoreB==15 entire false only if both simp conds true or while not (scoreA==15 or scoreB==15): #keep playing-->negate game over cond add other ending game conditions a==15 or b==15 or (a==7 and b==0) and third cond where b is 7 (a>=15 or b>=15) and abs(a-b) >=2-->either scores 15 and lead by 2

A ? operator is one that may not evaluate one of its subexpressions. In Python, andand is a short-circuit operator. Here is an example showing that this is the case:

short-circuit

both def show boolean operators as? thus what returned by (response[0]=="y") or "Y"?

short-circuit operators, returned right when val is known or it being T/F, will not eval second expr under certain circumstance true when first is y, or "Y" when not first one-->second is nonempty string always returned as true

sentinel value prefernce, sentinel pseduocode

should be easily distinguishable from actual data values bc not processed as part of data, so couldn't process value in data if using as sentinel get first data it (first it b4 loop start--priming read starts process)-->loop test? while it not sentinel process item get next data item -->pattern avoid sentinel val processing, catches first val if sentinel by ending before loop starts -e.g. neg sentinel number for average test score program sentinel line = x(float(inp("enter number (negative to quit) >> ")) or could have non-numeric stirng(all entered as string but this one not converted to num), or sentinel=empty string, so typing blank line terminates input all input as xStr (aka input("Enter num (<enter to quit) >> ") while not empty: while xStr != "":--<checking input not sentinel before float conversion x = float(xStr) convert xStr to a number

Another Example of a While Loop

starting at a = 0 meets condition that less than 3 , true so prints, then incrementally add value of one to iterator

while loop executed repeatedly based on ?

think like repeating if statement executed repeatedly based on ? based on Boolean variable goes back checking condition A again, after getting down to B, until when A is false then finish loop exec, terminate program while A is true, do B, exit while values might change in while loop, changing conditions and possibly exiting program or possible infinite loop continue block exec until condition met, so unknown amount time while loop more versatile not known num iterations we need until achieving task e.g. how many times user will enter an incorrect number? don't know, keep inputting anyway until in appropriate range rein put set amt time from when for loop gets input or if incorrect input or by accident , don't need to keep asking to enter correct for while loop for loop has to restart only need else to exec when cond false, else not needed in while loop Iterate over value or Boolean condition flipped to execute to avoid indfinire loop , condition values must change in loop with conditions above For loop ask all 5 times even if entering right number, keep asking or restart prog with for loop if out of tries

True. This identity shows that andand distributes over oror. Interestingly, it's also true that oror distributes over andand.

thus a and (b or c) ==(a and b) or (a and c)

quadratic5.py

try: regular entering of coeiffs and discRoot except ValueError: print("No real roots") handler catches error python wants except clause with matching error type, will exec handler code which prints error based on error type

== condition operators evaluate to? any built-in data type interpreted as? e.g. see how any value viewed when used as Boolean expr by ? bool("")

type bool, but Pyth flexible about data type appearing in expression, rlly any built-in data type interp as Boolean expression ints and float zero = False, any nonzero=True convert to Bool type e.g. bool(0) to see how interpreted bool("")empty string and list bool([]) both false-->both empty sequences

sentinel for avg program (interactive as well, but difference)

user can safely enter negative num x = float(input(enter num(neg to quit) >> "))->these are the priming reads while x >= 0: add to both total of sum and count another prompt for float #prompt so user knows when to end data not needing to type behavior all the time

average5.py,

using file technique rather than interactive, assume num typed into file one line by one no read/line(s), just for line in infile: total = total + float(line) print("\n average of the nums is", total/count) readline() empty string at end-->our sentinel line = infile.readline() while line != "": may stop early w empty line?, no blank line has \n newline so loop continues -->end of file loop

FOR LOOP comparison

variable each val in sequence , body loop statement exec once per value n numbers for exec n times, should use counted (for) loop

not x

x is false, return True, otherwise return false, same as truth table logic

operator x and y func definition

x is false, return x (aka return false), (because entire expr thus not true), otherwise return y

x and y

x is false, return x, otherwise return y whatever false value of x is will be returned, or depend on y for truth/falsity of expression if x true

operator x or y func definition

x is true, return x (aka return whatever value was true), (because entire expr thus true), otherwise return y

x or y

x is true, return x, otherwise return y

starting val as input and Syracuse sequence from this , going to one for each start val? The main idea here is to use a while loop that keeps running as long as the number num is not equal to 1 (1 like base case or sentinel). Inside this loop, we use an if/else structure to test whether num is even or odd. If it's even, we divide it by 2 and reassign it to itself. If it's odd, we multiply by 3, add 1, and reassign it to itself. Note that the initialization of numnum occurred before the start of the loop by getting an integer from the user.

x/2 if x even, 3x + 1 if odd start = int(inp("Value: ") for I in range(len(start)) if x % 2 ==0: print return integer division //2 for num if num is zero , other condition if 3x + 1 is odd in else state another conditional: if num != 1 print(str(num, then comma then end) else: print(1) also in the while loop


Conjuntos de estudio relacionados

Learning: 1.2 Compare and contrast types of attacks.

View Set

Ricci Chapter 44 - Test Bank - 4th Edition

View Set

AUTONOMIC NERVOUS SYSTEM - PHYSIOLOGY

View Set