Python Programming Chapter 6: Iteration Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.

Slides:



Advertisements
Similar presentations
Overloading Having more than one method with the same name is known as overloading. Overloading is legal in Java as long as each version takes different.
Advertisements

Escape Sequences \n newline \t tab \b backspace \r carriage return
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
Python Programming Chapter 5: Fruitful Functions Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Python Programming Chapter 9: Tuples Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Lecture 2 Introduction to C Programming
Loops (Part 1) Computer Science Erwin High School Fall 2014.
Programming Logic and Design, Third Edition Comprehensive
Lists Introduction to Computing Science and Programming I.
Executes a statement or statements for a number of times – iteration. Syntax for(initialize; test; increment) { // statements to be executed } Initial.
Python Programming Chapter 1: The way of the program Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Computer Science 1620 Loops.
Python Programming Chapter 12: Classes and Objects Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2010/2011.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
Chapter 4: Conditionals and Recursion
Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure.
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
Python Programming Chapter 2: Variables, expressions, and statements Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Python Programming Chapter 3: Functions Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Chapter 2: Algorithm Discovery and Design
Introduction to Methods
Python. What is Python? A programming language we can use to communicate with the computer and solve problems We give the computer instructions that it.
While Loops and Do Loops. Suppose you wanted to repeat the same code over and over again? System.out.println(“text”); System.out.println(“text”); System.out.println(“text”);
Fundamentals of Python: From First Programs Through Data Structures
Programming For Nuclear Engineers Lecture 12 MATLAB (3) 1.
What is RobotC?!?! Team 2425 Hydra. Overview What is RobotC What is RobotC used for What you need to program a robot How a robot program works Framework.
CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7.
Python – Part 4 Conditionals and Recursion. Modulus Operator Yields the remainder when first operand is divided by the second. >>>remainder=7%3 >>>print.
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new.
Python November 28, Unit 9+. Local and Global Variables There are two main types of variables in Python: local and global –The explanation of local and.
FUNCTIONS. Function call: >>> type(32) The name of the function is type. The expression in parentheses is called the argument of the function. Built-in.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Fall Week 3 CSCI-141 Scott C. Johnson.  Say we want to draw the following figure ◦ How would we go about doing this?
Python Programming Chapter 7: Strings Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
CPS120 Introduction to Computer Science Iteration (Looping)
Oct 15, 2007Sprenkle - CS1111 Objectives Creating your own functions.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
CRE Programming Club - Class 4 Robert Eckstein and Robert Heard.
CPS120: Introduction to Computer Science Decision Making in Programs.
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
CPS120: Introduction to Computer Science Lecture 14 Functions.
For loops in programming Assumes you have seen assignment statements and print statements.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Math 15 Introduction to Scientific Data Analysis Lecture 8 Python Programming – Part 2 University of California, Merced.
Loops Robin Burke IT 130. Outline Announcement: Homework #6 Conditionals (review) Iteration while loop while with counter for loops.
CPS120 Introduction to Computer Science Iteration (Looping)
CS241 PASCAL I - Control Structures1 PASCAL Control Structures Modified Slides of Philip Fees.
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Python Mini-Course University of Oklahoma Department of Psychology Day 3 – Lesson 10 Iteration: Loops 05/02/09 Python Mini-Course: Day 3 - Lesson 10 1.
Python Basics  Functions  Loops  Recursion. Built-in functions >>> type (32) >>> int(‘32’) 32  From math >>>import math >>> degrees = 45 >>> radians.
ITERATION. Iteration Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that.
Chapter 7: Repetition Structure (Loop) Department of Computer Science Foundation Year Program Umm Alqura University, Makkah Computer Programming Skills.
Chad’s C++ Tutorial Demo Outline. 1. What is C++? C++ is an object-oriented programming (OOP) language that is viewed by many as the best language for.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Repetition Structures The long awaited …. Repetition Structures I repeat …
Python – Part 4 Conditionals and Recursion. Conditional execution If statement if x>0:# CONDITION print (‘x is positive’) Same structure as function definition.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
More about comments Review Single Line Comments The # sign is for comments. A comment is a line of text that Python won’t try to run as code. Its just.
Lesson #6 Modular Programming and Functions.
Loops BIS1523 – Lecture 10.
Lesson #6 Modular Programming and Functions.
Lesson #6 Modular Programming and Functions.
Lesson #6 Modular Programming and Functions.
CISC101 Reminders All assignments are now posted.
Class code for pythonroom.com cchsp2cs
Presentation transcript:

Python Programming Chapter 6: Iteration Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012

10/14/2015 Multiple Assignment As you may have discovered, it is legal to make more than one assignment to the same variable. A new assignment makes an existing variable refer to a new value (and stop referring to the old value). bruce = 5 print bruce, bruce = 7 print bruce The output of this program is 5 7, because the first time bruce is printed, its value is 5, and the second time, its value is 7. The comma at the end of the first print statement suppresses the newline after the output, which is why both outputs appear on the same line. Here is what multiple assignment looks like in a state diagram: Python Programming Chapter 6 - Saad Bani Mohammad

10/14/2015 Multiple Assignment (Cont...) With multiple assignment it is especially important to distinguish between an assignment operation and a statement of equality. Because Python uses the equal sign (=) for assignment, it is tempting to interpret a statement like a = b as a statement of equality. It is not! First, equality is commutative (تبادلي) and assignment is not. For example, in mathematics, if a = 7 then 7 = a. But in Python, the statement a = 7 is legal and 7 = a is not. Furthermore, in mathematics, a statement of equality is always true. If a = b now, then a will always equal b. In Python, an assignment statement can make two variables equal, but they don‘t have to stay that way: a = 5 b = a # a and b are now equal a = 3 # a and b are no longer equal The third line changes the value of a but does not change the value of b, so they are no longer equal. Python Programming Chapter 6 - Saad Bani Mohammad

10/14/2015 The while Statement Repeating identical or similar tasks without making errors is something that computers do well and people do poorly. We have seen two programs, nLines and countdown, that use recursion to perform repetition, which is also called iteration. Because iteration is so common, Python provides several language features to make it easier. The first feature we are going to look at is the while statement. Here is what countdown looks like with a while statement: def countdown(n): while n > 0: print n n = n-1 print "Blastoff!“ Since we removed the recursive call, this function is not recursive. Here is the flow of execution for a while statement: 1.Evaluate the condition, yielding 0 or If the condition is false (0), exit the while statement and continue execution at the next statement. 3.If the condition is true (1), execute each of the statements in the body and then go back to step 1. As an exercise, rewrite the function nLines from previous chapters using iteration instead of recursion. Python Programming Chapter 6 - Saad Bani Mohammad

5 The while Statement (Drawing Iteratively) Remember the circles from Chapters 4 and 5, we drew them using recursion Could also do this with a while loop… We can hold onto the shapes we’ve drawn in variables myLine = create_line( … ) and then delete or move them move( myLine, 10, 0 ) delete( myLine ) You can use this to create animations. Write your drawing code in a function and then call runGraphicsFn, with your function as the argument. See more of this in the next week’s exercises 10/14/2015 Python Programming Chapter 6 - Saad Bani Mohammad

10/14/2015 The while Statement (Tables) The following program outputs a sequence of values in the left column and their logarithms in the right column: x = 1.0 while x < 10.0: print x, '\t', math.log(x) x = x The string '\t' represents a tab character. As characters and strings are displayed on the screen, an invisible marker called the cursor keeps track of where the next character will go. After a print statement, the cursor normally goes to the beginning of the next line. The tab character shifts the cursor to the right until it reaches one of the tab stops. Tabs are useful for making columns of text line up, as in the output of the following program: Python Programming Chapter 6 - Saad Bani Mohammad

10/14/2015 The while Statement (2D Tables) A two-dimensional table is a table where you read the value at the intersection of a row and a column. A multiplication table is a good example. Let's say you want to print a multiplication table for the values from 1 to 6. A good way to start is to write a loop that prints the multiples of 2, all on one line: i = 1 while i <= 6: print 2*i, ' ', i = i + 1 print Again, the comma in the print statement suppresses the newline. After the loop completes, the second print statement starts a new line. The output of the program is: So far, so good. The next step is to encapsulate and generalize. Python Programming Chapter 6 - Saad Bani Mohammad

10/14/2015 Encapsulation and Generalization Encapsulation is the process of wrapping a piece of code in a function, allowing you to take advantage of all the things functions are good for. You have seen two examples of encapsulation: printParity and isDivisible from previous chapters. Generalization means taking something specific, such as printing the multiples of 2, and making it more general, such as printing the multiples of any integer. This function encapsulates the previous loop and generalizes it to print multiples of n: def printMultiples(n): i = 1 while i <= 6: print n*i, '\t', i = i + 1 print To encapsulate, all we had to do was add the first line, which declares the name of the function and the parameter list. To generalize, all we had to do was replace the value 2 with the parameter n. If we call this function with the argument 2, we get the same output as before. With the argument 3, the output is: With the argument 4, the output is: Python Programming Chapter 6 - Saad Bani Mohammad

10/14/2015 Encapsulation and Generalization (Cont...) By now you can probably guess how to print a multiplication table-by calling printMultiples repeatedly with different arguments. In fact, we can use another loop: i = 1 while i <= 6: printMultiples(i) i = i + 1 Notice how similar this loop is to the one inside printMultiples. All we did was replace the print statement with a function call. The output of this program is a multiplication table: Python Programming Chapter 6 - Saad Bani Mohammad

10/14/2015 Encapsulation and Generalization (Cont...) To demonstrate encapsulation again, let's take the previous code and wrap it up in a function: def printMultTable(): i = 1 while i <= 6: printMultiples(i) i = i + 1 This process is a common development plan. We develop code by writing lines of code outside any function, or typing them into the interpreter. When we get the code working, we extract it and wrap it up in a function. This development plan is particularly useful if you don't know, when you start writing, how to divide the program into functions. This approach lets you design as you go along. Python Programming Chapter 6 - Saad Bani Mohammad

10/14/2015 Local Variables You might be wondering how we can use the same variable, i, in both printMultiples and printMultTable. Doesn't it cause problems when one of the functions changes the value of the variable? The answer is no, because the i in printMultiples and the i in printMultTable are not the same variable. Variables created inside a function definition are local; you can't access a local variable from outside its " home" function. That means you are free to have multiple variables with the same name as long as they are not in the same function. The stack diagram for this program shows that the two variables named i are not the same variable. They can refer to different values, and changing one does not affect the other. Python Programming Chapter 6 - Saad Bani Mohammad

10/14/2015 Local Variables (Cont...) The value of i in printMultTable goes from 1 to 6. In the diagram it happens to be 3. The next time through the loop it will be 4. Each time through the loop, printMultTable calls printMultiples with the current value of i as an argument. That value gets assigned to the parameter n. Inside printMultiples, the value of i goes from 1 to 6. In the diagram, it happens to be 2. Changing this variable has no effect on the value of i in printMultTable. It is common and perfectly legal to have different local variables with the same name. In particular, names like i and j are used frequently as loop variables. If you avoid using them in one function just because you used them somewhere else, you will probably make the program harder to read. Python Programming Chapter 6 - Saad Bani Mohammad

10/14/2015 More Generalization As another example of generalization, imagine you wanted a program that would print a multiplication table of any size, not just the six-by-six table. You could add a parameter to printMultTable: def printMultTable(high): i = 1 while i <= high: printMultiples(i) i = i + 1 We replaced the value 6 with the parameter high. If we call printMultTable with the argument 7, it displays: Python Programming Chapter 6 - Saad Bani Mohammad

10/14/2015 More Generalization (Cont...) This is fine, except that we probably want the table to be square - with the same number of rows and columns. To do that, we add another parameter to printMultiples to specify how many columns the table should have. Just to be annoying, we call this parameter high, demonstrating that different functions can have parameters with the same name (just like local variables). Here's the whole program: def printMultiples(n, high): i = 1 while i <= high: print n*i, '\t', i = i + 1 print def printMultTable(high): i = 1 while i <= high: printMultiples(i, high) i = i + 1 Python Programming Chapter 6 - Saad Bani Mohammad

10/14/2015 More Generalization (Cont...) Notice that when we added a new parameter, we had to change the first line of the function (the function heading), and we also had to change the place where the function is called in printMultTable. As expected, this program generates a square seven-by-seven table: Python Programming Chapter 6 - Saad Bani Mohammad

10/14/2015 More Generalization (Cont...) When you generalize a function appropriately, you often get a program with capabilities you didn‘t plan. For example, you might notice that, because ab = ba, all the entries in the table appear twice. You could save ink by printing only half the table. To do that, you only have to change one line of printMultTable. Change printMultiples(i, high) to printMultiples(i, i) and you get Python Programming Chapter 6 - Saad Bani Mohammad

10/14/2015 Functions A few times now, we have mentioned "all the things functions are good for." By now, you might be wondering what exactly those things are. Here are some of them: Giving a name to a sequence of statements makes your program easier to read and debug. Dividing a long program into functions allows you to separate parts of the program, debug them in isolation, and then compose them into a whole. Functions facilitate both recursion and iteration. Well-designed functions are often useful for many programs. Once you write and debug one, you can reuse it. Python Programming Chapter 6 - Saad Bani Mohammad