Using the Target Variable Inside the Loop

Slides:



Advertisements
Similar presentations
Programming Logic and Design Eighth Edition
Advertisements

Objectives In this chapter, you will learn about:
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Computer Science 1620 Loops.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
Programming Logic and Design Fifth Edition, Comprehensive
Computer Science 111 Fundamentals of Programming I The while Loop and Indefinite Loops.
Chapter 4: Loops and Files. The Increment and Decrement Operators  There are numerous times where a variable must simply be incremented or decremented.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Programming Logic and Design Sixth Edition Chapter 5 Looping.
1 Loops. 2 Topics The while Loop Program Versatility Sentinel Values and Priming Reads Checking User Input Using a while Loop Counter-Controlled (Definite)
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 4 Looping.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
CS 100 Introduction to Computing Seminar October 7, 2015.
Programming with Loops. When to Use a Loop  Whenever you have a repeated set of actions, you should consider using a loop.  For example, if you have.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 5 Repetition.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Repetition Structures.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
Count Controlled Loops (Nested) Ain’t no sunshine when she’s gone …
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
9. ITERATIONS AND LOOP STRUCTURES Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC 110 – INTRO TO COMPUTING - PROGRAMMING For Loop.
1 Looping Chapter 6 2 Getting Looped in C++ Using flags to control a while statement Trapping for valid input Ending a loop with End Of File condition.
Introduction to Loop. Introduction to Loops: The while Loop Loop: part of program that may execute > 1 time (i.e., it repeats) while loop format: while.
REPETITION CONTROL STRUCTURE
Chapter 3 Assignment and Interactive Input.
Topics Introduction to Repetition Structures
CHAPTER 5A Loop Structure
Chapter 5: Control Structure
Review If you want to display a floating-point number in a particular format use The DecimalFormat Class printf A loop is… a control structure that causes.
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Topics Introduction to Repetition Structures
Lecture 07 More Repetition Richard Gesick.
Lecture 4B More Repetition Richard Gesick
Control Structures - Repetition
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
While Loops.
Control Structure Senior Lecturer
COMP 110 Loops, loops, loops, loops, loops, loops…
Chapter 4: Loops and Files
Topics Introduction to Repetition Structures
Chapter 6: Repetition Statements
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Loop Statements & Vectorizing Code
Topics Augmented Assignment Operators Sentinels Input Validation Loops
CSC115 Introduction to Computer Programming
Introduction to Repetition Structures
For loops Taken from notes by Dr. Neil Moore
Topics Sequences Lists Copying Lists Processing Lists
Topics Introduction to Repetition Structures
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Another Example Problem
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Loops.
Loop Statements & Vectorizing Code
Announcements Lab 3 was due today Assignment 2 due next Wednesday
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
The while Looping Structure
ICS103: Programming in C 5: Repetition and Loop Statements
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

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

# This program shows the numbers 1-10 # and their squares. # Print the table headings. print('Number\tSquare') print('--------------') # Print the numbers 1 through 10 for number in range(1, 11): square = number**2 print(number, '\t', square)

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

# This program uses a loop to display a # table of numbers and their squares. # Get the starting value. print('This program displays a list of numbers') print('and their squares.') start = int(input('Enter the starting number: ')) # Get the ending limit. end = int(input('How high should I go? ')) # Print the table headings. print() print('Number\tSquare') print('--------------') # Print the numbers and their squares. for number in range(start, end + 1): square = number**2 print(number, '\t', square)

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)

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

# This program calculates the sum of a series # of numbers entered by the user. max = 5 # The maximum number # Initialize an accumulator variable. total = 0.0 # Explain what we are doing. print('This program calculates the sum of') print(max, 'numbers you will enter.') # Get the numbers and accumulate them. for counter in range(max): number = int(input('Enter a number: ')) total = total + number # Display the total of the numbers. print('The total is', total)

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

The Augmented Assignment Operators (cont’d.)

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

# This program displays property taxes. TAX_FACTOR = 0.0065 # Represents the tax factor. # Get the first lot number. print('Enter the property lot number or enter 0 to end.') lot = int(input('Lot number: ')) # Continue processing as long as the user # does not enter lot number 0. while lot != 0: # Get the property value. value = float(input('Enter the property value: ')) # Calculate the property's tax. tax = value * TAX_FACTOR # Display the tax. print('Property tax: $', tax) # Get the next lot number. print('Enter the next lot number or enter 0 to end.')

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 (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

# This program calculates retail prices. mark_up = 2.5 # The markup percentage another = 'y' # Variable to control the loop. # Process one or more items. while another == 'y' or another == 'Y': # Get the item's wholesale cost. wholesale = float(input("Enter the item's wholesale cost: ")) # Validate the wholesale cost. while wholesale < 0: print('ERROR: the cost cannot be negative.') wholesale = float(input('Enter the correct wholesale cost:')) # Calculate the retail price. retail = wholesale * mark_up # Display the retail price. print('Retail price: $', format(retail, ',.2f')) # Do this again? another = input('Enter y for another item? ')

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”

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

# This program averages test scores. It asks the user for the # number of students and the number of test scores per student. num_students = int(input('How many students do you have? ')) num_test_scores = int(input('How many test scores per student? ')) # Determine each students average test score. for student in range(num_students): # Initialize an accumulator for test scores. total = 0.0 # Get a student's test scores. print('Student number', student + 1) print('-----------------') for test_num in range(num_test_scores): print('Test number', test_num + 1, end='') score = float(input(': ')) # Add the score to the accumulator. total += score # Calculate the average test score for this student. average = total / num_test_scores # Display the average. print('The average for student number', student + 1, \ 'is:', average) print()