12.07.2015 Views

3. Program Control

3. Program Control

3. Program Control

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Department of Computer ScienceDr. John S. Mallozzi<strong>3.</strong> <strong>Program</strong> <strong>Control</strong>Interactive programming, Repetition andthe for statement, Patterns, Conditionalstatements, Comparing values, The whilestatement, Sentinels and their patternsCopyright © 2010 by John S. Mallozzi


• Need for input• Input in Python• Evaluating input• An interactive program2


• When commands are saved in a program, the resultmay be very static• Example:<strong>Program</strong>Output• A program should be flexible enough to work for more thanone person• This can be accomplished using the idea of input• The user can be asked to enter information into theprogram• Using this input, the program’s output can be modified3


• Python has an input function called raw_input• A function is a pre-written algorithm that returns avalue• You can assign the result to a variable, or print it,etc.• To use a function like raw_input, you follow thename of the function with parentheses – you maytreat the result like any value• If you put a string into those parentheses, thestring will be printed as a prompt• Example:4


• The reason for the “raw” in raw_input is that whatis entered is treated as a string• What you enter is not evaluated in any way• Example: if you enter 2 + 3, the result is not the number5, but the string '2 + 3'• If you want evaluation, apply the function eval tothe result• Examples:5


The <strong>Program</strong>Running the <strong>Program</strong>Running the <strong>Program</strong> Again6


• Repetition• Idea of a loop• Definite loops• The for statement7


• Repeated action in a program is common• So far, we have no way to say: “Repeat thisaction” some number of times8


• In our example, we want to say something like:• Do 3 times: print '*'• Do 7 times on the same line: print '*' After this, you still have to end the line To stay on the line after printing, write a comma after thestatement; to skip to the next line, just say print alone (This is more complicated than printing a single string ofstars, but this way we don’t have to count the number ofstars, and – as we’ll see – it adds flexibility to the program )• A loop is a Python statement that causesrepetition• In Python, to have an action repeated a definitenumber of times, we use a “counting loop” ordefinite loop9


• Python does not have a simple statement of the form“Do the following n times”• The idea of a definite loop is that we use a variable tocount the repetitions• We specify to Python which values must be taken bythe variable• For now, the only specification we need is a range• If we want n repetitions (where n is some positiveinteger), we write range(n)• There are other uses of range, which we’ll look at later• To say “do the following n times,” writefor count in range(n):(you don’t have to use the name “count”)then give the instruction(s) you want repeated• …but there are syntax issues – you must writeeverything in a very particular way to avoid error10


• The general form – or syntax – of the for statement isfor counter_variable in range( repetitions ):statements• counter_variable can be any name you like, not already in use• repetitions can be either an integer or a variable whose valueis an integer• Statements can be any number (including 1) of statements• The statements will be executed repeatedly as a group,the number of times specified by repetitions• The colon (:) following the first line and the indentationof all the statements to be repeated are crucial! Theytell Python exactly what statement or group ofstatements to repeat11


• Looking for patterns• Accumulator pattern• Fencepost pattern13


• As you program, patterns appear – you windup doing very similar things in severaldifferent programs• If you identify the pattern, you can use it again• This is almost the same as reusing part of a program• The code is not quite the same, but the generalorganization is, and the algorithm is very close• As examples, we look at two loop patterns• Accumulator Pattern• Fencepost Pattern14


• If you want to add some numbers entered by auser, defining a new variable for each numberentered is too rigid• What if you want to add 100 numbers?• What if you are not sure how many numbers the userhas, and must ask?• Even if you know there are no more than threenumbers, the program is hard to write15


• To add a sequence of numbers input by theuser• You have to get the numbers one at a time• But you don’t want to use a different variable foreach number• So you keep a running total or cumulative total• Initialize total to zero• Loop Get next number Add it to the total• When the loop ends, the total is correct for allentered numbers16


Corporate Ethics on a Filtered Internet 119One possibility for a viable long-term solution would be for the industry consensus to begiven the status of law over time. This approach would help to address three of the primaryshortcomings of the industry self-regulation model. First, self-regulation can amount to thefox guarding the chicken coop. Second, self-regulation permits some actors to opt out ofthe system and to gain an unfair competitive advantage as a result. Last, the self-regulatorysystem could collapse or be amended, for the worse, at any time—and may or may not persistin an optimal form, even if such an optimal form could be reached initially.This mode of ratifying an industry self-regulatory scheme has instructive antecedents. Mostimmediately relevant, the Sullivan Principles—proposed initially by one man—eventually becameincorporated into U.S. law: the Anti-Apartheid Act in 1986 that embodied the SullivanPrinciples passed over President Reagan’s veto. 12 In the technology context, a series of proposedlaws in the United States—some more advisable as public policy than others—havehad a similar history. In the case of the Security Systems Standards and Certification Act of2001 (SSSCA), the Consumer Broadband and Digital Television Promotion Act of 2002(CBPTPA), and the Audio Home Recording Act of 1992 (AHRA), the industry came to consensusas to a feasible solution to a common problem, which the Congress then took up aspossible legislation. The analogy here is not to the merits of each proposal, each of whichsuffered from deep flaws. The analogy runs instead to the process of the industry workingthrough the details of a common problem, with lawmakers coming along thereafter to ratifythe agreement.The advantages of such a process are several. This approach would lead to a more stableregulatory regime, bringing with it the benefits of administrative, enforcement, and appellatemechanisms. Depending on what emerges from the process, the Congress or their colleaguesin other jurisdictions could decline to ratify the agreement if the industry had notmoved the bar high enough. This approach would also solve possibly the toughest problemof industry self-regulations, whereby industry outliers who do not opt in may enjoy an unfairadvantage, especially in a context like this one where the behavior is hard to codify as goodor bad. The function of ratifying the industry-led agreement ex post facto would be to level theplaying field for all relevant firms. Local firms might retain their advantage—they would haveonly the first-order regulation to contend with, not the second-order—but that is another problemof globalization altogether.International GovernanceProblems in cyberspace rarely have been solved through coordinated international action,though there is no inherent reason to believe that international cooperation or governancecould not play a meaningful role in resolving these ethical dilemmas. The United Nations hasnot been involved in extensive regulation of the online space. The primary U.N.-related entityto play a regulatory role in anything related to the Internet is the International TelecommunicationUnion (ITU), which has a long history in the coordination between states and private


• Multiply a sequence of numbers• Changes in pattern details• Initialize product to 1• Multiply product by next number• When loop ends, product is correct• Real pattern is the accumulator pattern• Initialize accumulator• Loop Get next item Perform operation to accumulate next item• When loop ends, accumulator has correct value for allentered items18


• Desired output is the “fence” above• We want a “post” on each end, with a “rail”between every two posts• To print the fence, we use a loop• But it’s hard to get the loop right20


To ease reading, we define a few names:First attempt:Result:Extra railSecond attempt:Result:Extra railThird attempt:Result:Missing post!21


• Now that we have it right, we remember the pattern:• First post is outside loop• Loop repeats one time fewer than number of posts (which is thesame as the number of rails)• In loop, first rail, then post22


• The user will choose a count, then our program willproduce a list of that many randomly chosen numbers,each between 1 and 100. The numbers must be printed,separated by commas• To solve this problem, we must• Learn how to produce numbers chosen at random• Figure out how to list numbers separated by commas• The first is easy, because it is in the Python library• The library module we need is called random• The function we want from this library is called randint• The second is just the fencepost pattern!• Each number is a “post”• Each comma is a “rail”23


• <strong>Program</strong>s making choices• The simple if statement• The if – else statement• The if –elif – else statement25


• Computers can be programmed to makedecisions• A decision is based on a logical test, or condition– an expression that evaluates to True or False• In Python, a decision is programmed using aconditional statement• The principal conditional statement in Pythonis called the if statement, because of the way itis written26


• This statement is given a condition and an action• It checks the condition• If the condition is true, it performs the action• Otherwise, it does nothing, and the execution of theprogram continues• Exampleif withdrawal_amount > balance:print 'Account overdrawn'• Follows as in English: If the amount being withdrawn islarger than the balance, then a message is printed that theaccount is overdrawn• Syntax: As with the for statement, the colon andthe indentation are important, in this case showingwhat is to be executed when the condition is true27


What if user enters invalidinput, like 0? Or -5? Or “two”28


Problem is noted, but program goes onanyway – no alternative action29


• This statement is given a condition and two actions• If the condition is true, it performs the first action• Otherwise, it performs the second action• Exampleif withdrawal_amount > balance:print 'Account overdrawn'else:balance = balance - withdrawal_amountFollows as in English: If the amount is larger thanthe balance, then a message is printed that theaccount is overdrawn. Otherwise, the amount issubtracted from the balance• Note, again, the colons and indentation – as before,crucial in telling Python what is wanted30


“Works,” but not ideal31


• When there are more than two alternatives,you use a new keyword, elif (which standsfor “else if”) for each alternative conditionif condition1:statements-when-condition1-trueelif condition2:statements-when-condition2-true…(as many additional elif alternatives as needed)else:statements-when –none-of-conditions-true32


Notereorganization:Expectedalternative is nowfirst – reads better== is used to testfor equality (= isused to make anassignment) –More on this soon33


Last result is unpleasant for users – not done yet! We’ll postponeconsideration of that problem34


• Comparing numerical values• Floating-point numbers• More complex comparisons• Boolean variables35


• In formingconditions,comparisons areoften used• Mathematicalsymbols areused whenpresent on thekeyboard(except for =,which is alreadyin use forassignment)• Otherwise, weuse symbolsformed usingseveral keysDescription Math PythonGreater than > >Greater than or equal ≥ >=Less than <


• Because floating-point numbers may be storedinaccurately, you must be careful when comparingthem for equality• It is usually not a good idea to use == for thiscomparison• When you make a choice based on whether or nottwo floating-point numbers are equal, you may besurprised because of this inaccuracy• Example:37


• When you want to compare floating-pointnumbers for equality, decide how close they have to beto be considered “the same”• Example• You might consider two numbers to be the same if theyare the same in the first 7 decimal places• This will happen if they differ by less than 0.00000005 (i.e.,5 in the eighth decimal place)• Mathematicians often use the Greek letter ε(epsilon) to denote a test value like this• Example:Meaning: Find the difference between the twonumbers, ignoring the sign, and see if it is lessthan ε38


• A Boolean variable (type bool) has value eitherTrue or False• You can replace a complicated condition with awell-named Boolean variable• Example• English: salary is at least $50,000 and savings are at least$100,000• Python:salary >= 50000 and savings >= 100000• Python using Boolean variables:First definesalary_is_high = salary >= 50000enough_savings = savings >= 100000and the expression becomessalary_is_high and enough_savings40


• Not all loops needed in programs are definite• We may not know how many times to execute the loop• Example: Given the annual rate of growth in apopulation, how many years will it take for thepopulation to double?• A statement suitable for indefinite loops has theformwhile condition :statements-to-repeat• Meaning: Check the condition. If it is true, executethe statements-to-repeat. Repeat.• Important: The statements-to-repeat must changethe condition or the repetition will never end41


The loopIndicates that statement continueson the next line42


• Variables years and initial_population must bedefined before the loop begins• If , for example, you tryyears = years + 1without initializing years before the loop, an error willoccur• You must check that the loop condition changes asthe loop is executed• For example, if you don’t use initial_population at all(omit the initialization and change all other occurrencesof initial_population to population), you get thewrong answer• For another example, if you use the conditioninitial_population < 2 * initial_populationyou get an infinite loop43


• As in the program, a loop may be inside aconditional statement• Or vice versa• Each of the for and while loops and theconditional if includes an indented block ofstatements• Each of those statements may be any statement,including a for, while, or if• Each of which contains an indented block ofstatements, which may contain any statement,including… …44


• Sentinels• A pattern for sentinels• Another sentinel pattern• A different kind of sentinel• Validating input45


• One important use of loops is to allow repeatedentry of data• Often, we don’t know how much data to expect• We really ought not ask the user to count thedata• We can ask the user to indicate the end of datain some special way• A special “end-of-data” value is called asentinel• Sentinels may be dealt with in several ways46


• We have to continue while the incoming valueis not the sentinel• Problem: we can't phrase the condition beforewe have an incoming value• Sentinel Pattern 1• Get a value• Loop: while value gotten isn't sentinel Work on value Get a valueGet first input value before loopReverse expected order47


Sentinel Pattern 1Accumulator Pattern48


• Instead of reversing the logic of the loop, you canuse a Boolean variableworking = True• The condition becomes whether or not thisvariable is truewhile working :…• No need to reverse logic, but must now reset thevariable based on input• Sentinel Pattern 2• Initialize a variable to be True• Loop: while variable is true (“working”) Get value If value isn't sentinel, work on value, otherwise set Booleanvariable to False49


(Some programmers prefer to start with a Booleanequal to False, then continue as long as it remainsFalse. Such a variable might be called done, forinstance)50


• A convenient value is not always available foruse as a sentinel• Sometimes all available values are needed forpossible input• In this case, you can use a string (such as'done') and delay the evaluation to a number• First check to see if the sentinel has been entered• If not, do the evaluation and proceed51


• When user input is required and the userenters an inappropriate value, we should lethim or her retry• To do this, we use a loop that will execute onlyif the user makes an error• Pattern (as in Sentinel Pattern 1)• Get value before loop• Execute loop only while value is not acceptable• Get subsequent values to check at bottom of loop• When loop finishes (or does not execute) value fromuser is correct• This process is called validating input53

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!