3 Pages

Ch02.Programs

Course: CS 381, Fall 2008
School: Oregon State
Rating:
 
 
 
 
 

Word Count: 3109

Document Preview

2 Chapter - Creating Python Programs While using python in an interactive fashion is easy and powerful, it becomes tiresome when you need to perform the same task more than once. Each time requires you to enter the commands all over again. Fortunately, there is an alternative. Python statements can be stored in a file. You can then direct the Python system to read and execute the commands from the file, rather...

Register Now

Unformatted Document Excerpt

Coursehero >> Oregon >> Oregon State >> CS 381

Course Hero has millions of student submitted documents similar to the one
below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.

Course Hero has millions of student submitted documents similar to the one below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.
2 Chapter - Creating Python Programs While using python in an interactive fashion is easy and powerful, it becomes tiresome when you need to perform the same task more than once. Each time requires you to enter the commands all over again. Fortunately, there is an alternative. Python statements can be stored in a file. You can then direct the Python system to read and execute the commands from the file, rather than from the console. Such a file is termed a Python program. # a simple python program There are a few differences between 5+2 commands that are typed at the console print 5 + 2 and those read from a file. To see these, name = raw_input(what is your name?) try typing the lines shown at right print hello , name directly into the Python system. Then enter the lines into a text file using your favorite text editor, such as Notepad or SimpleText. (If you use a wordprocessor, such as Word, make sure you save the document as a text file). Traditionally python programs are stored in a file with the extension .py. Name your file hello.py. Once you have created the file, start the python system and give the file name on the command line, as follows: python hello.py Can you see any differences in execution? Notice that simple expressions, such as the line 5+2, are displayed when Python is running an interactive session, but do not appear when input is coming from a file. The only output you see will come from the print statements. Experiment by making changes in the file hello.py and executing the resulting file. If you have not already done so, try making an error, such as misspelling a name or leaving out a value for the addition operator. What happens? How is the error message different from the error message you get in the interactive session? A python program consists of a sequence of python statements. The term code is often used to describe statements that have been organized into a program. In the previous chapter you encountered three forms of statement; the assignment statement, the print statement and the import statement. Two of these three are used in this sample program. In this chapter you will learn about several more forms of statement. Writing a Python program has many advantages over immediate execution. One, it allows you to execute the same series of statements over and over. For example, you might want to do the same calculation with different input values. Second, it allows for the possibility that one person (the programmer) might create a Python program that will then be executed by somebody else (the user). The user might not even know the Python programming language, or how to program, or know that the program they are using was written in Python. Third, you have undoubtedly noticed that it is difficult to write more than a few statements in Python without making mistakes. Common mistakes include using an incorrect name, an improper operator, leaving out punctuation, and so on. When Python statements are collected into a program, these errors can be corrected by editing Exploring Python Chapter 2 Creating Python Programs 1 the file. The revised program can then be easily executed, without the need to retype the statements. This process is termed debugging (that is, removing the errors, or bugs, from a program). Fourth, a Python program is an artifact, an object that can be shared with others. Good programmers learn by reading each others code, as much as from reading introductions such as this chapter. As you mature your programming skills, you should practice reading code as a form of literature, noticing what makes a program easy to read, and what features make programs more difficult to read. Conditionals A common task is to choose between print the exam had 40 points two or more alternative possibilities score = input(what was your score?) depending upon the outcome of a test. percent = score/40.0 This is termed a conditional. To see a print your percentage was,percent conditional being used in practice if percent >= 90.0: consider the program shown at right. print congratulations, you got an A The program prompts the user to enter a value, performs a simple calculation, and prints the result. In this case it is converting a test score (a number between 0 and 40) into a percentage. As a final step, however, the program tests the value stored in the variable named percent. If this value is larger than 90, an encouraging statement will be printed. If the value is not greater than 90, no statement will be printed. You should experiment by executing this program with various values and noticing the way it works. You can also try typing the same statements in an interactive session. An important feature to note is the use of spaces and tab stops. Up to now all our statements have started in the first column. In this program the pattern has changed. The statement following the if statement is indented by striking the tab character once. At this point, if you have embraced the experimental approach advocated in the previous chapter, a number of questions should be entering your thoughts. What happens if you forget to type the tab character? What happens if you use spaces instead of tabs? What happens if you type two tabs instead of one? Rather than telling you the answer, you should immediately go and try these alternatives and see the results for yourself. More than one statement can be controlled by a conditional. To do this, simply type each statement using the same indentation; that is, the same number of tab stops. When the indentation returns to the previous level the statements are no longer being controlled by the if. You can see this behavior by replacing the if statement with something similar to the statements shown at left. if percent >= 90.0: print congratulations, you got an A print you are doing well in this class print see you in class next week An if statement produces one of two outcomes. Either the condition is true, if percent >= 90.0: print congratulations, you got an A print you are doing well in this class else: Exploring Python Chapter 2 Creating Python Programs 2 print you did not get an A print see you in class next week in which case the indented statements are executed, or it is not true, in which case control moves to the next statement at the original level of indentation. Sometimes you would like to perform an action in the latter case, one that will not be executed if the if condition is true. This can be accomplished by an else statement, as shown at right. Again, you should experiment with the else statement, and notice how Python executes statements depending upon the result of the condition test. If statements can be nested inside each other. To do this, simply indent the new statement, adding one new tab for the new level of control. But you need to be careful. An else statement is matched to a preceding if by the indentation level. Compare the following two examples. Predict what the outcome of each will be, then execute the programs to test your prediction. if percent >= 90.0: if percent >= 95.0: print you get an A+! else: print you get an A if percent >= 90.0: if percent >= 95.0: print you get an A+! else: print you get an A Nested if statements and elif Often a series of tests can have a number of outcomes. One way to write this would be to use nested if statements. The following is an example: if percent >= 90.0 print congratuations, you got an A else: if percent >= 80.0: print you got a B else: if percent >= 70.0: print you got a C else: print you grade is less than a C This situation is common, and the nested statement solution is less than ideal since it tends to creep across the page and lining up the correct number of tabs can be a problem. To solve this Python uses the elif statement, which is a combination of else and if. The statement above can be written as follows: if percent >= 90.0 print congratulations, you got an A elif percent >= 80.0 print you got a B Exploring Python Chapter 2 Creating Python Programs 3 elif percent >= 70.0 print you got a C else: print your grade is less than a C While Loops Another common need is to execute a statement repeatedly. This is termed a loop. The simplest type of loop is a while loop. To illustrate a while loop consider the calculation of compound interest. If you have d dollars that is being compounded at p percent interest, the interest earned at the end of one year is d * p / 100.0. Assuming you compound the interest, the new balance will be the old balance plus the interest. To calculate the result for one year you could write a program such as the following: d = input(what is your initial balance?) p = input(what is the interest rate (as a number)?) d = d + d * p / 100.0 print your new balance after one year is, d Now you want to how determine much money you will have after five years. This can be computed as follows: d = input(what is your initial balance?) p = input(what is the interest rate (as a number)?) year = 1 while year <= 5: d = d + d * p / 100.0 print your new balance after year, year, is, d year = year + 1 print your final balance is, d Study the program carefully. Notice which statements are indented, and which statements are not. Again, try experimenting with variations. What will happen if (by mistake) you forget to indent the statement year = year + 1? What changes do you want to make if instead of 5 years you want to do the calculation for 7 years? What if you want to read the number of years from the user? Imagine that you do the latter, and the user enters the value 0 for the number of years. What will your program do then? The condition being tested by a while loop can be any true/false value. Here is another simple program. This program will read a series of values from the user, count the number of items, and print their average. The user indicates the end of the input by typing the special value -1. sum = 0.0 count = 0 num = input(enter your number:) Exploring Python Chapter 2 Creating Python Programs 4 while num != -1: sum = sum + num count = count + 1 num = input(enter your number:) print average is , sum / count What will happen if the user enters -1 the very first time, without entering any numbers? Predict the outcome in this case, then try the program and see if it matches your prediction. Is the result very helpful? Can you think of a way, using if statements, to produce a more helpful result in this case and still produce the same result in the normal case? Break, Continue and Pass Statements *1 It is not uncommon to want to end a loop in the middle of execution. The break statement allows you to do this. It breaks out of the current loop. For example, rather than writing two different calls in the input function, the average computing loop could be written as follows: sum = 0.0 count = 0 while True: num = input(enter your number:) if num == -1: break sum = sum + num count = count + 1 print average is , sum / count Compare carefully this version of the loop with the one given earlier. Can you see any advantages to this approach? Can you identify any drawbacks? The continue statement is similar to a break, only it immediately returns to the condition test of the loop (continuing execution of the loop). Finally, a pass statement does nothing at all. There are two common situations where this is useful. First, it is sometimes easier to express a positive condition than a negative one. This can then be written as a conditional statement that does nothing, following by an else that does real work: if a<b and x<3: pass # do nothing here else: doRealWork(x, y) 1 Sections marked with an asterisk indicate advanced or optional material that can be skipped on first reading. Exploring Python Chapter 2 Creating Python Programs 5 Pass statements are also sometimes used in the body of a function. We will have examples of this in a later chapter. For loops Loops that run through an arithmetic progression, such as 1, 2, 3, 4, 5, tend to be the most common. The loop given earlier that counted years from 1 to 5 was a simple example. For this particular case there is a simpler type of statement, termed a for statement. This could be written as follows: for year in range(1, 6): d = d + d * p / 100.0 print your new balance after year, year, is, d There is actually more going on here than meets the eye. The function range is behind the scenes constructing a list containing the elements 1, 2, 3, 4 and 5. (That is, values up to but not including the second argument). The for statement is then iterating over elements of the list. However, we were not going to talk about lists until Chapter x. And, in truth, most Python programmers think of this construct as an idiom without even recognizing that range is a function or that it is producing a list. Instead, it is simply a convenient way to write a loop that runs through a simple sequence. A for statement is, in the strictest sense, never necessary. That is, anything that can be done using a for can be done using a while. For example, the statement above could be written as follows: year = 1 while year < 6: d = d + d * p / 100.0 print your new balance after year, year, is, d year = year + 1 However, there are advantages of the for statement over the while. Notice that the while loop requires a separate statements to perform both the initialization of the variable year as well as the increment. If either of these statements are omitted the program will fail to work properly. Furthermore, the for statement makes it clear that the type of loop being produced is an arithmetic progession, something that is only discovered after careful anlysis of the while loop version. For these reasons the for statement should be preferred when it is appropriate. The range function can take one, two or three arguments. Try executing the following, substituting the expressions range(5) (as shown), range(2, 8), and range(2, 8, 3). Then write a short description of what the range function does when presented with one, two or three arguments. for i in range(5): Exploring Python Chapter 2 ...

Find millions of documents on Course Hero - Study Guides, Lecture Notes, Reference Materials, Practice Exams and more. Course Hero has millions of course specific materials providing students with the best way to expand their education.

Below is a small sample set of documents:

Oregon State - CS - 381
Test Cases for Homework 2The following test cases were used to test your solutions to excercises 1 and 2. If you have any questions, please contact me.Exercise 1Example trees: t1 = Leaf t2 = Node True Leaf t3 = Node 3 (Node 4 (Node 4 t4 = Node 3
Oregon State - CS - 480
CS 480/580 Midterm 1 Winter 2000The exam has 100 points total, 20 points for each of the five questions. (120 points for 580 students). Closed book, closed notes, closed neighbors.Name: 1. Here is just a portion of the grammar for our programming
Oregon State - CS - 556
CS 556 Computer VisionProgram #1: Edge Detection and the Hough Transform Due date: Monday, Oct. 20, 2003 Programming: This programming assignment consists of two major components, each of which contains smaller pieces. This assignment will be writt
Oregon State - CS - 151
Midterm Exam CS 151 Section 2 Spring 2003 - Gary WatsonName (Last, First):_ Student ID: _ Signature:_ Date: May 6, 2003Test Form No: 1 - You must record this number on your answer sheet. There are multiple versions of this test! Read This Befor
Oregon State - MATH - 634
Singular SimplicesDefinitions A singular n-simplex in a space X is a map : n X Cn (X ) is the free abelian group with basis the set of singular n-simplices of XChain Complex Computation [v0 , vn ] = (-1)i [v0 , vi , , vn ] =i =0 n
Oregon State - MATH - 635
Universal Coefficient Theorem PreviewRead pages 185-189 for cohomology overview, 190-197 for UCT. Our immediate goal is to define cohomology groups of a space X with coefficients in an abelian group G, H m (X ; G) and to prove: H n (X ; G) Hom(Hn (X
Oregon State - MATH - 635
UCT for HomologyRead: 218, 261-267 Theorem: Given a free chain complex C and an abelian group G, there is short exact sequence 0 Hn G Hn (C ; G) Hn1 G 0 The sequence is natural with respect to chain maps, but the splitting is not.DetailsMai
Oregon State - MATH - 635
Recall Cup Products:cp c q , p+q = c p , |[v0 , ,vp ] c q , |[vp , ,vp+q ] Bilinearity: p p p c1 + c2 c q = c1 q q cp c1 + c2 = c p Associativity: (c p c q ) c r = c pp c + c2 q c1 + c p qCohomology LevelTheorem inducesc , q c2q: H p (X ;
Oregon State - MATH - 636
Covering Dimension(All spaces are separable metric in this section.) Denition: The covering dimension of X , dim(X ) is n if every nite open cover of X has a nite open renement of order n + 1. dim(X ) = n if dim(X ) n and dim(X ) n 1. Denition:
Oregon State - MATH - 634
DefinitionsRead Chapter 0 Retract Deformation Retraction Homotopy Homotopy Equivalence Homotopy Type Contractible Null Homotpic Mapping Cylinder Mf associated with f : X YMth 634 Fall 20071/7CW ComplexesA space X is a CW complex if it is fo
Oregon State - MATH - 634
Homology of Good Pairs, RevisitedFirst, recall Hn (X , A)q inc/ Hn (X , V ) o qexcHn (X \ A, V \ A)qHn (X /A, A/A)inc/ Hn (X /A, V /A) o excHn (C , D )where (C , D ) = (X /A \ A/A, V /A \ A/A)Mth 634 Fall 20071/6Other Res
Oregon State - MTH - 611
M TH 611 A SSIGNMENT 5 Due: Wednesday June 12, 2002 Bent E. Petersen petersen@math.orst.eduLast AssignmentUse this page as cover sheet stapled onto your submission, or do all your work on this page if there is sufficient room. This final assignm
Oregon State - MTH - 611
M TH 611 A SSIGNMENT 3 Due: Monday April 29, 2002 Bent E. Petersen petersen@math.orst.eduContour IntegralsUse this page as cover sheet stapled onto your submission, or do all your work on this page if there is sufficient room.Name: Problem 1.
Oregon State - MTH - 611
M TH 611 N OTES :May 27, 2003 Summary Week 68Let be a connected set, let f be a function analytic in and suppose f (z) = 0 for each z . Then g is called a branch of the logarithm of f , or, less formally, a branch of log f (z), if1. g is
Oregon State - MTH - 611
M TH 611 N OTES :April 26, 2003 Summary Week 4We showed a function f analytic in an open disk D(a, R), R &gt; 0, is the sum of a convergent power seriesf (z) =n=0cn (z a)nin the disk. Note it follows that the series has radius of converg
Oregon State - MTH - 611
M TH 611 N OTES :April 21, 2003 Summary First 3 WeeksWe have obtained a number of results but here I will mention only the highlights. We started by discussing power series and the radius of convergence of a power series. We saw that the sum o
Oregon State - MTH - 254
Vector Calculus I Mth 254Archive Winter 1996 FilesSept 27, 1999 Rev. Sept 28, 1999Contents1 Railroad track right angle turn 2 Railroad track reverse direction 3 Example 1: Curvature of a parametric curve 4 Example 2: Curvature of a parametr
Oregon State - MTH - 256
Applied Differential Equations Mth 256Archive Spring 1997 Files Oct 8, 2000This archive contains the sample problems, two quizzes and the nal exam from Mth 256 Spring 1997. The original test instructions, headers and formatting have not been pre
Oregon State - MTH - 611
M TH 611 A SSIGNMENT 4 Due: Wednesday May 8, 2002 Bent E. Petersen petersen@math.orst.eduCauchy InequalitiesUse this page as cover sheet stapled onto your submission, or do all your work on this page if there is sufficient room.Name: Problem 1
Oregon State - BA - 378
Center for Research on Information Technology and OrganizationsI.T. in Business (University of California, Irvine)Year Paper The Productivity Paradox: Is it Resolved? Is there a New One? What Does It All Mean for Managers?Jason DedrickUniversi
Virginia Tech - AOE - 3054
1. ) = =&gt; = = 0.15 =&gt; = 24b) P = V i = 24 0.15 =&gt; = . 2. )Peak-to-Peak = 2Amplitude = 25 =10V 5 b) RMS = = = . 2 2 c) From section 3 of the electronics review, the amplitude of the signal when connected V2 is related to the amplit
Oregon State - CS - 533
CS533 Intelligent Agents and Decision Making Homework 3, Winter 20091. Prove that for any STRIPS planning problem that the length of the optimal relaxed plan from any state s to the goal g is an admissible heuristic for state s. (NOTE: This does not
Oregon State - CS - 321
CS321 Theory of Computation Quiz 6, Fall 2008Name: 1. [5pt] What is a conguration of a non-deterministic pushdown automaton (NPDA)? A conguration of an NPDA is a triple (q, w, u) where q is a state, w is the remaining input to be read in, and u
Cornell - TAM - 203
Your Name: Your TA:T&amp;AM 203Tuesday March 28, 2000Prelim 27:30 - 9:00+ PMDraft March 28, 20003 problems, 100 points, and 90+ minutes. Please follow these directions to ease grading and to maximize your score. a) No calculators, books or note
Oregon State - ECE - 441
ID 1Task Name All individual parts laid out on PCBDuration 2.3 daysStart Fri 1/11/08Finish Tue 1/15/08Jan 13, '08 Jan 20, '08 Jan 27, '08 Feb 3, '08 Feb 10, '08 Feb 17, '08 Feb 24, '08 Mar 2, '08 Mar 9, '08 Mar 16, '08 Mar 23, '08 Mar 30, '
Oregon State - ECE - 441
ID 2 14 15 16 17 19 22 25 26 27 28 29 30 31 32 38 39 41 44 47 48 49 50 51Task Name Test plan revision Order Parts Getting info from Freescale and Battery junction Preliminary Schematic Final Schematic Review Schematic/PCB test Order/Receive PCB Cod
Oregon State - ECE - 441
ID 2 14 15 16 17 19 22 25 26 27 28 29 30 31 32 38 39 41 44 47 48 49 50 51Task Name Test plan revision Order PartsDuration 4 days 0 days 1 day 5 days 5 days 7 days 6 days 4 days 5 days? 1 day 1 day? 2 days? 2 days? 2 days? 3 days 6 days? 1 day? 1
Oregon State - ECE - 441
ID 2 14 15 16 17 21 23 26 29 36 37 45 46 48 52 53 54 55 56Task Name Test plan revision Order PartsDuration 4 days 0 days 1 day 5 days 5 days 7 days 6 days 1 day? 5 days? 3 days 1 day? 3 days? 1 day? 1 day? 5 days? 1 day 0 days 0 days 5 days?Sta
Oregon State - ECE - 441
ID 1 2 3 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56Task Name All individual parts laid out on PCB Test plan revision Gantt chart update Finish initial Gantt ch
Johns Hopkins - V - 019
Since coming to power Wade has sought by all available means to control every political force.The high level of voter abstention from the legislative elections has cast doubt on the February presidential results and discredit on a parliament that h
Johns Hopkins - AMS - 391
Computers Math. PergamonPII: SOS98-1221(97)00126-OVol. 34, No. 2-4, pp. 245-251, 1997 Copyright@1997 Elsevier Science Ltd Printed in Great Britain. All rights reserved 08981221/97 $17.00 + 0.00Applic.HomoclinicPhenomenaA. L.SHIL'NIKOVin