Loading...

Messages

Proposals

Stuck in your homework and missing deadline? Get urgent help in $10/Page with 24 hours deadline

Get Urgent Writing Help In Your Essays, Assignments, Homeworks, Dissertation, Thesis Or Coursework & Achieve A+ Grades.

Privacy Guaranteed - 100% Plagiarism Free Writing - Free Turnitin Report - Professional And Experienced Writers - 24/7 Online Support

In order to draw an octagon with turtle graphics, you would need a loop that iterates eight times.

17/11/2020 Client: papadok01 Deadline: 24 Hours

Copyright © 2018 Pearson Education, Inc.

C H A P T E R 4

Repetition Structures

Copyright © 2018 Pearson Education, Inc.

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
Copyright © 2018 Pearson Education, Inc.

Introduction to Repetition Structures

Often have to write code that performs the same task multiple times
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 and count-controlled loops

Copyright © 2018 Pearson Education, Inc.

The while Loop: a Condition-Controlled Loop

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

Copyright © 2018 Pearson Education, Inc.

The while Loop: a Condition-Controlled Loop (cont’d.)

Copyright © 2018 Pearson Education, Inc.

The while Loop: a Condition-Controlled Loop (cont’d.)

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

Copyright © 2018 Pearson Education, Inc.

Copyright © 2018 Pearson Education, Inc.

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

Copyright © 2018 Pearson Education, Inc.

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

Copyright © 2018 Pearson Education, Inc.

Copyright © 2018 Pearson Education, Inc.

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

range characteristics:
One argument: used as ending limit

Two arguments: starting value and ending limit

Three arguments: third argument is step value

Copyright © 2018 Pearson Education, Inc.

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

Copyright © 2018 Pearson Education, Inc.

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

Copyright © 2018 Pearson Education, Inc.

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)

Copyright © 2018 Pearson Education, Inc.

Calculating a Running Total

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

Copyright © 2018 Pearson Education, Inc.

Calculating a Running Total (cont’d.)

Copyright © 2018 Pearson Education, Inc.

The Augmented Assignment Operators

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

Copyright © 2018 Pearson Education, Inc.

The Augmented Assignment Operators (cont’d.)

Copyright © 2018 Pearson Education, Inc.

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

Copyright © 2018 Pearson Education, Inc.

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

Copyright © 2018 Pearson Education, Inc.

Input Validation Loops (cont’d.)

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

Copyright © 2018 Pearson Education, Inc.

Input Validation Loops (cont’d.)

Copyright © 2018 Pearson Education, Inc.

Nested Loops

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”

Copyright © 2018 Pearson Education, Inc.

Copyright © 2018 Pearson Education, Inc.

Nested Loops (cont’d.)

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_iterations_inner x

number_iterations_outer

Copyright © 2018 Pearson Education, Inc.

Turtle Graphics: Using Loops to Draw Designs

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)

Copyright © 2018 Pearson Education, Inc.

Turtle Graphics: Using Loops to Draw Designs

This for loop iterates eight times to draw the octagon:
for x in range(8):

turtle.forward(100)

turtle.right(45)

Copyright © 2018 Pearson Education, Inc.

Turtle Graphics: Using Loops to Draw Designs

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)

Copyright © 2018 Pearson Education, Inc.

Turtle Graphics: Using Loops to Draw Designs

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)

Copyright © 2018 Pearson Education, Inc.

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

Homework is Completed By:

Writer Writer Name Amount Client Comments & Rating
Instant Homework Helper

ONLINE

Instant Homework Helper

$36

She helped me in last minute in a very reasonable price. She is a lifesaver, I got A+ grade in my homework, I will surely hire her again for my next assignments, Thumbs Up!

Order & Get This Solution Within 3 Hours in $25/Page

Custom Original Solution And Get A+ Grades

  • 100% Plagiarism Free
  • Proper APA/MLA/Harvard Referencing
  • Delivery in 3 Hours After Placing Order
  • Free Turnitin Report
  • Unlimited Revisions
  • Privacy Guaranteed

Order & Get This Solution Within 6 Hours in $20/Page

Custom Original Solution And Get A+ Grades

  • 100% Plagiarism Free
  • Proper APA/MLA/Harvard Referencing
  • Delivery in 6 Hours After Placing Order
  • Free Turnitin Report
  • Unlimited Revisions
  • Privacy Guaranteed

Order & Get This Solution Within 12 Hours in $15/Page

Custom Original Solution And Get A+ Grades

  • 100% Plagiarism Free
  • Proper APA/MLA/Harvard Referencing
  • Delivery in 12 Hours After Placing Order
  • Free Turnitin Report
  • Unlimited Revisions
  • Privacy Guaranteed

6 writers have sent their proposals to do this homework:

Buy Coursework Help
Quality Homework Helper
Finance Homework Help
Writer Writer Name Offer Chat
Buy Coursework Help

ONLINE

Buy Coursework Help

Hi dear, I am ready to do your homework in a reasonable price.

$62 Chat With Writer
Quality Homework Helper

ONLINE

Quality Homework Helper

Hi dear, I am ready to do your homework in a reasonable price.

$62 Chat With Writer
Finance Homework Help

ONLINE

Finance Homework Help

I have a Master’s degree and experience of more than 5 years in this industry, I have worked on several similar projects of Research writing, Academic writing & Business writing and can deliver A+ quality writing even to Short Deadlines. I have successfully completed more than 2100+ projects on different websites for respective clients. I can generally write 10-15 pages daily. I am interested to hear more about the project and about the subject matter of the writing. I will deliver Premium quality work without Plagiarism at less price and time. Get quality work by awarding this project to me, I look forward to getting started for you as soon as possible. Thanks!

$55 Chat With Writer

Let our expert academic writers to help you in achieving a+ grades in your homework, assignment, quiz or exam.

Similar Homework Questions

Uci continental team salary - HRM/300T: Fundamentals Of Human Resource Management - Www yougetsignal com tools visual tracert - ASIGM 3 IOM REPORT - Cisco cme sip phone configuration - Micellization in physical chemistry - 879 duncans creek road woolomin - 30142 petersburg rd waverly va 23890 - Draw both enolates formed when the ketone - Red flag signs in child development ppt - Step Smart Case - Interpretive exercise - The median cubital vein is located in the ________ space - Electrical machines drives and power systems 5th edition - Ereserves penn state - Accounting - Essentials of business law 8th edition pdf - Edld 5311 fundamentals of leadership - Compound words pdf worksheets - Who is the tyrant 3000 miles away - Quadratic expressions and algebraic fractions - Nb_itn practice skills assessment pt ccna 3 - Defend the yellow river - Grant and Contract Proposal Writing – Week 1 - Leadership styles in remember the titans - How does macbeth kill banquomonaro pioneers settlers database - CPK Case Study UVA-F-1553 - Iodine clock reaction at home - Discussion for module 6: team management - Applied science - Most reactive metal in group 1 - The future of health care delivery - Find two unit vectors orthogonal to both given vectors - Telstra valentine's day billboard - Todd matchett confessions of a young criminal - Year 9 naplan spelling words - St jude international gala for hope - Map of zambia with towns - Groupon revenue recognition sec - Criminalistics question and answer - Unit test part 2 systems of equations - Paragraph 353b of the immigration rules - Literature review - Ideo case study harvard analysis - Outliers roseto - Famous athletes with pku - AstroloGy bAbA 7340613399 OnLinE reaL VashIKaraN sPecIaLIsT IN Nizamabad - Opponent process theory negative afterimages - Pbs destiny of the republic - Mis padres siempre ________ las llaves - One smooth stone video - Management and organization - Application Security - Cvg super fun unlimited 499 - Mcgellin v mount king mining - Market orientation advantages and disadvantages - Hess's law lab report discussion - Chemistry infographic for thallium - Mis. midterm - Australian motor vehicle certification board - Kip r irvine assembly language pdf - The steve jobs way by jon katzenbach - Bga ball grid array - Air flow switch installation - Crank sturgeon perpetual spring device - Informative speech outline on how to make a pizza - 1/4 5/8 pair coil bunnings - Strategic staffing decisions more important than others - News event - Charges and fields phet lab answer key - Telstra shared data plans - Math statistics - Gravimetric analysis precipitation method - Importance of feasibility study to an entrepreneur - POWEPOINT - What is the number of valence electrons in argon - Air preheater in boiler diagram - Gpu direct rdma example - Castagna genesis syrah 2009 - Chapter summary - Edpsych modules 3rd edition pdf - Picot question for qualitative research - Rough Draft Qualitative Research Critique and Ethical Considerations - The sixth extinction reading guide answer key - Output unit level costs - Chess math is fun - Aro pearsoncmg com - Radioactive dating game worksheet answers - 5.1 Please write a Devotional Reflection on Diversity - 6 week hypertrophy program pdf - Please read question in comment section. - Tms diesel weare new hampshire - Leggos italian style sausage agnolotti - Exercise 2 5 prepare t accounts lo2 5 lo2 7 - Limewater test for co2 equation - Walden university nursing specialty comparison matrix - Who is o brien in 1984 - Understanding Terms - Add a total row to this table and display the maximum value for the total spent column - Evidence-Based Practice Case Study.