Python Programming - Repetition Structures PDF
Document Details
Uploaded by Deleted User
2024
Reham Hamdy Abou-Zaid
Tags
Summary
This document is a chapter on repetition structures in Python programming. It covers various types of loops such as condition-controlled loops, count-controlled loops, and nested loops. It explains how to use the range function, calculate running totals, and use sentinels to terminate loops. The document also explains loop-based drawing using turtle graphics.
Full Transcript
Starting out with Python Fourth Edition Chapter 4 Repetition Structures Reham Hamdy Abou-Zaid, 2024 Topics Introduction to Repetition Structures The while Loop: a Condition-Controlled Loop The for Loop: a Count-Controlled Loop Calcula...
Starting out with Python Fourth Edition Chapter 4 Repetition Structures Reham Hamdy Abou-Zaid, 2024 Topics Introduction to Repetition Structures The while Loop: a Condition-Controlled Loop The for Loop: a Count-Controlled Loop Calculating a Running Total Sentinels Input Validation Loops Nested Loops Turtle Graphics: Using Loops to Draw Designs Introduction to Repetition Structures Programmers often have to write code that performs the same task multiple times Suppose you have been asked to write a program that calculates a percent sales commission for several salespeople. One approach would be to write the code to calculate one salesperson’s commission, and then repeat that code for each salesperson And this code goes on and on... Introduction to Repetition Structures Disadvantages to duplicating code Makes program large Time consuming May need to be corrected in many places Repetition structure: makes computer repeat included code as necessary Includes: condition-controlled loops (while) count-controlled loops (for) The while Loop: a Condition-Controlled Loop (1 of 4) while loop: while condition is true, do something Two parts: Condition tested for true or false value Statements repeated as long as condition is true In flow chart, line goes back to previous part General format: while condition: statements The while Loop: a Condition-Controlled Loop (2 of 4) In order for a loop to stop executing, something has to happen inside the loop to make the condition false Iteration: one execution of the body of a loop while loop is known as a pretest loop Tests condition before performing an iteration Will never execute if condition is false to start with Requires performing some steps prior to the loop The while Loop: a Condition-Controlled Loop (3 of 4) The while Loop: a Condition-Controlled Loop (3 of 4) The while Loop: a Condition-Controlled Loop (3 of 4) Infinite Loops Loops must contain within themselves a way to terminate Something inside a while loop must eventually make the condition false Infinite loop: loop that does not have a way of stopping Repeats until program is interrupted Occurs when programmer forgets to include stopping code in the loop Infinite Loops The loop has no way of stopping. (The only way to stop this program is to press Ctrl+C on the keyboard to interrupt it.) The for Loop: a Count-Controlled Loop Count-Controlled loop: iterates a specific number of times Use a for statement to write count-controlled loop Designed to work with sequence of data items Iterates once for each item in the sequence General format: for variable in [val1, val2, etc]: statements Target variable: the variable which is the target of the assignment at the beginning of each iteration The for Loop statement executes in the following manner: The for The variable is assigned the first value in the list, then the statements that appear in the block are executed. Then, variable is assigned the next value in the list, and the statements in the block are executed again. This continues until variable has been assigned the last value in the list. The for Loop statement executes in the following manner: Using the range Function with the for Loop The range function simplifies the process of writing a for loop range returns an iterable object Iterable: contains a sequence of values that can be iterated over Using the range characteristics: One argument: used as ending limit range(5): will be treated like range(0,5) start value is 0 (inclusive) stop value is 5 (exclusive) Two arguments: starting value and ending limit start value is 1 (inclusive) stop value is 5 (exclusive) Three arguments: third argument is step value start value is 1 (inclusive) stop value is 10 (exclusive) Increase by 2 Using the range characteristics: Using the Target Variable Inside the Loop Purpose of target variable is to reference each item in a sequence as the loop iterates Target variable can be used in calculations or tasks in the body of the loop Example: calculate square root of each number in a range Using the Target Variable Inside the Loop Using the Target Variable Inside the Loop Letting the User Control the Loop Iterations Sometimes the programmer does not know exactly how many times the loop will execute Can receive range inputs from the user, place them in variables, and call the range function in the for clause using these variables Be sure to consider the end cases: range does not include the ending limit Letting the User Control the Loop Iterations Generating an Iterable Sequence that Ranges from Highest to Lowest The range function can be used to generate a sequence with numbers in descending order Make sure starting number is larger than end limit, and step value is negative Example: range(10, 0, -1) This expression will produce the following sequence: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 Calculating a Running Total (1 of 3) Programs often need to calculate a total of a series of numbers Typically include two elements: A loop that reads each number in series An accumulator variable Known as program that keeps a running total: accumulates total and reads in series At end of loop, accumulator will reference the total Calculating a Running Total (2 of 3) Calculating a Running Total (3 of 3) The Augmented Assignment Operators (1 of 2) In many assignment statements, the variable on the left side of the = operator also appears on the right side of the = operator Augmented assignment operators: special set of operators designed for this type of job Shorthand operators The Augmented Assignment Operators (2 of 2) Operator Example Usage Equivalent To += x += 5 x = x + 5 −= y −= 2 y = y − 2 *= z *= 10 z = z * 10 /= a /= b a = a / b %= c %= 3 c = c % 3 //= x //= 3 x = x // 3 **= y **= 2 y = y**2 Sentinels Sentinel: special value that marks the end of a sequence of items When program reaches a sentinel, it knows that the end of the sequence of items was reached, and the loop terminates Must be distinctive enough so as not to be mistaken for a regular value in the sequence Example: when reading an input file, empty line can be used as a sentinel Sentinels Sentinels Input Validation Loops Computer cannot tell the difference between good data and bad data If user provides bad input, program will produce bad output GIGO: garbage in, garbage out It is important to design program such that bad input is never accepted Input Validation Loops *The clerk probably meant to enter 40, because there are not 400 hours in a week. The computer, however, is unaware of this fact, and the program processed the bad data just as if it were good data. Input Validation Loops Input validation: inspecting input before it is processed by the program If input is invalid, prompt user to enter correct data Commonly accomplished using a while loop which repeats as long as the input is bad If input is bad, display error message and receive another set of data If input is good, continue to process the input Input Validation Loops Input Validation Loops Input Validation Loops Input Validation Loops Input Validation Loops Nested Loops (1 of 3) Nested loop: loop that is contained inside another loop Example: analog clock works like a nested loop Hours hand moves once for every twelve movements of the minutes hand: for each iteration of the “hours,” do twelve iterations of “minutes” Seconds hand moves 60 times for each movement of the minutes hand: for each iteration of “minutes,” do 60 iterations of “seconds” Nested Loops (2 of 3) Nested Loops (3 of 3) Key points about nested loops: Inner loop goes through all of its iterations for each iteration of outer loop Inner loops complete their iterations faster than outer loops Total number of iterations in nested loop: number of iterations of inner loop X number of iterations of outer loop Nested Loops Using Nested Loops To Print Patterns Can you use Nested Loops to draw the following patterns? Check Programs 4-18, 4-19, and 4-20 pages (193-196) Turtle Graphics: Using Loops to Draw Designs (1 of 4) You can use loops with the turtle to draw both simple shapes and elaborate designs. For example, the following for loop iterates four times to draw a square that is 100 pixels wide: for x in range(4): turtle.forward(100) turtle.right(90) Turtle Graphics: Using Loops to Draw Designs (2 of 4) This for loop iterates eight times to draw the octagon: for x in range(8): turtle.forward(100) turtle.right(45) Turtle Graphics: Using Loops to Draw Designs (3 of 4) You can create interesting designs by repeatedly drawing a simple shape, with the turtle tilted at a slightly different angle each time it draws the shape. NUM_CIRCLES = 36 # Number of circles to draw RADIUS = 100 # Radius of each circle ANGLE = 10 # Angle to turn for x in range(NUM_CIRCLES): turtle.circle(RADIUS) turtle.left(ANGLE) Turtle Graphics: Using Loops to Draw Designs (4 of 4) This code draws a sequence of 36 straight lines to make a "starburst" design. START_X = -200 # Starting X coordinate START_Y = 0 # Starting Y coordinate NUM_LINES = 36 # Number of lines to draw LINE_LENGTH = 400 # Length of each line ANGLE = 170 # Angle to turn turtle.hideturtle() turtle.penup() turtle.goto(START_X, START_Y) turtle.pendown() for x in range(NUM_LINES): turtle.forward(LINE_LENGTH) turtle.left(ANGLE) The Break and Continue Statements The break and continue statements are used to alter the flow of loops: break exits the loop entirely continue skips the current iteration and proceeds to the next one The Break Statements The break statement terminates the loop immediately when it's encountered. Note: The break statement is usually used inside decision-making statements such as if...else. The Break Statement with for loop The break statement can be used with the for loop to terminate the loop when a certain condition is met. For example: Output: It terminates the loop when i is equal to 3. Hence, the output doesn't include values after 2. The Break Statement with while loop The break statement can be used with the while loop to terminate the loop when a certain condition is met. For example: Output: It terminates the loop when i is equal to 3. The Continue Statements The continue statement skips the current iteration of the loop and the control flow of the program goes to the next iteration. The Continue Statement with for loop The continue statement can be used with the for loop to skip the current iteration of the loop and jump to the next iteration. For example: Output: It skips the current iteration when i is equal to 3, and continues the next iteration. Hence, the output has all the values except 3. The Continue Statement with while loop The current iteration of the while loop can be skipped using the continue statement. For example: Output: It skips the current iteration when the number is even and starts the next iteration. Example: The Continue Statement Write a program that prints all the languages in the following list except for “Java” and “C” Languages list [‘Python’, ‘Java’, ‘C++’, ‘C’, ‘JavaScript’] Output: The pass Statements The pass statement is a null statement which can be used as a placeholder for future code. Suppose we have a loop or a function that is not implemented yet, but we want to implement it in the future. In such cases, we can use the pass statement. The pass statement is used inside the if statement. However, nothing happens when the pass is executed. The pass Statements Note: The difference between a comment and a pass statement in Python is that while the interpreter ignores a comment entirely, pass is not ignored. Suppose we didn't use pass or just put a comment as: Summary This chapter covered: Repetition structures, including: Condition-controlled loops Count-controlled loops Nested loops Infinite loops and how they can be avoided range function as used in for loops Calculating a running total and augmented assignment operators Use of sentinels to terminate loops Using loops to draw turtle graphic designs