Lecture 13 – range function, for…in loops COMPSCI 1 1 Principles of Programming.

Slides:



Advertisements
Similar presentations
Lecture 12 – Loops – while loops COMPSCI 1 1 Principles of Programming.
Advertisements

Chapter 04 (Part III) Control Statements: Part I.
Lecture 03 – Sequences of data.  At the end of this lecture, students should be able to:  Define and use functions  Import functions from modules 
James Tam Loops In Python In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 4 – C Program Control Outline 4.1Introduction.
Chapter 4 Repetitive Execution. 2 Types of Repetition There are two basic types of repetition: 1) Repetition controlled by a counter; The body of the.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
Structured programming
Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure.
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Lecture 11 – if … else, if... elif statements, nested ifs COMPSCI 1 1 Principles of Programming.
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Lecture 20 – Test revision COMPSCI 101 Principles of Programming.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Chapter 5 Control Structures: Loops 5.1 The while Loop The while loop is probably the most frequently used loop construct. The while loop is a conditional.
Chapter 4 C Program Control. Objectives In this chapter, you will learn: –To be able to use the for and do … while repetition statements. –To understand.
COMPSCI 101 Principles of Programming Lecture 25 – Nested loops, passing mutable objects as parameters.
Chapter 5: Control Structures: Iteration Visual Basic.NET Programming: From Problem Analysis to Program Design.
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.
Saeed Ghanbartehrani Summer 2015 Lecture Notes #5: Programming Structures IE 212: Computational Methods for Industrial Engineering.
Lecture 4: Calculating by Iterating. The while Repetition Statement Repetition structure Programmer specifies an action to be repeated while some condition.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Repetition Structures Repetition Structures allow you to write programs that will repeat program steps multiple times. –Also called Loops –Counter controlled.
Chapter 4: Control Structures II
Control Structures Repetition or Iteration or Looping Part II.
Ch. 10 For Statement Dr. Bernard Chen Ph.D. University of Central Arkansas Spring 2012.
Chapter 5: Control Structures II
Counter-Controlled Loops CSIS 1595: Fundamentals of Programming and Problem Solving 1.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Lecture 5: Stopping with a Sentinel. Using a Sentinel Problem Develop a class-averaging program that will process an arbitrary number of grades each time.
Introduction to Strings Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg 1.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 10 - JavaScript/JScript: Control Structures II Outline 10.1Introduction 10.2Essentials of.
Sections 5.1 – 5.4 © Copyright by Pearson Education, Inc. All Rights Reserved.
Overview Go over parts of quiz? Another iteration structure for loop.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Repetition Structures.
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
Lecture 15 – more on lists and for…in loops, the split() function COMPSCI 1 1 Principles of Programming.
1 CS 177 Week 6 Recitation Slides Review for Midterm Exam.
Topic: Control Statements. Recap of Sequence Control Structure Write a program that accepts the basic salary and allowance amount for an employee and.
Beginning C For Engineers Fall 2005 Lecture 3: While loops, For loops, Nested loops, and Multiple Selection Section 2 – 9/14/05 Section 4 – 9/15/05 Bettina.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
CSCI/CMPE 4341 Topic: Programming in Python Chapter 4: Control Structures (Part 2) Xiang Lian The University of Texas – Pan American Edinburg, TX
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Why Repetition? Read 8 real numbers and compute their average REAL X1, X2, X3, X4, X5, X6, X7, X8 REAL SUM, AVG READ *, X1, X2, X3, X4, X5, X6, X7, X8.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Lecture 14 – lists, for in loops to iterate through the elements of a list COMPSCI 1 1 Principles of Programming.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
Computer Program Flow Control structures determine the order of instruction execution: 1. sequential, where instructions are executed in order 2. conditional,
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
1 ICS103 Programming in C Lecture 7: Repetition Structures.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 3 - Structured Program Development Outline.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 23, 2005 Lecture Number: 11.
1 Chapter 4 - Control Statements: Part 1 Outline 4.1 Introduction 4.4 Control Structures 4.5 if Selection Structure 4.6 if/else Selection Structure 4.7.
Chapter 4 – C Program Control
Lecture 7: Repeating a Known Number of Times
Topic: Functions – Part 2
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Iterations Programming Condition Controlled Loops (WHILE Loop)
Chapter 8 The Loops By: Mr. Baha Hanene.
Topics Introduction to Repetition Structures
Introduction to Repetition Structures
15-110: Principles of Computing
The structure of programming
REPETITION Why Repetition?
Presentation transcript:

Lecture 13 – range function, for…in loops COMPSCI 1 1 Principles of Programming

 At the end of this lecture, students should:  understand the Python range() function and use it to define a sequence of values  understand the for…in loop structure used with the range() function  be able to define a for…in loop to implement counter-controlled repetition  be able to convert a for…in loop (with a range function) into a while loop and vice versa Learning outcomes 2CompSci Principles of Programming

def get_legal_user_num(lower, upper): prompt = "Enter a number (" prompt += str(lower) + "-" + str(upper) + "): " number = int(input(prompt)) while number upper: number = int(input(prompt)) return number def main(): print(get_legal_user_num(0, 6)) print(get_legal_user_num(10, 20)) print(get_legal_user_num(1, 2)) main() def get_legal_user_num(lower, upper): prompt = "Enter a number (" prompt += str(lower) + "-" + str(upper) + "): " number = int(input(prompt)) while number upper: number = int(input(prompt)) return number def main(): print(get_legal_user_num(0, 6)) print(get_legal_user_num(10, 20)) print(get_legal_user_num(1, 2)) main() Recap  From lecture 12  a loop is used for implementing repeated tasks  be able to design and write Python while loops 3CompSci Principles of Programming Enter a number (0-6): -1 Enter a number (0-6): 8 Enter a number (0-6): 6 6 Enter a number (10-20): Enter a number (1-2): 3 Enter a number (1-2): 0 Enter a number (1-2): 2 2

The Python range() function  The Python range() function defines a sequence of integer values within a boundaries.  The range() function has the following syntax: range(start, stop, step) where the three arguments are: start - the lower bound (included) of the sequence defined, stop - the upper bound (excluded) of the sequence defined, step - the increment between each number in the sequence defined.  Some examples:  range(1, 10, 2) defines the sequence 1, 3, 5, 7, 9  range(5, 20, 6) defines the sequence 5, 11, 17  range(14, 4, -3) defines the sequence 14, 11, 8, 5  range(0, 7, 1) defines the sequence 0, 1, 2, 3, 4, 5, 6 4CompSci Principles of Programming

The Python range() function continued range(start, stop, step)  If the step is omitted, the default step is 1.  range(0, 7) defines the sequence 0, 1, 2, 3, 4, 5, 6  range(4, -1) defines the sequence 4, 3, 2, 1, 0  If both the start and the step are omitted, the sequence starts from 0 with a step increment of 1.  range(5) defines the sequence 0, 1, 2, 3, 4,  range(7) defines the sequence 0, 1, 2, 3, 4, 5, 6 5CompSci Principles of Programming Note that printing a range does not print the defined sequence of integers, i.e., print(range(6) does not print the sequence 0, 1, 2, 3, 4, 5

The Python range() function continued range(start, stop, step)  The step cannot be 0:  range(0, 7, 0) gives an error  If the step is negative then the start value must be greater than the stop value.  range(14, 4, -3) defines the sequence 14, 11, 8, 5  range(4, 14, -3) defines an empty sequence  If the step is positive then the start value must be smaller than the stop value.  range(14, 4, 3) defines an empty sequence  range(4, 14, 3) defines the sequence 4, 7, 10, 13 6CompSci Principles of Programming ValueError: range() arg 3 must not be zero

Iteration – for…in loops  The following while loop executes exactly 100 times (for count = 0 to count = 99). The variable count controls the number of times the loop body is executed.  The for…in range(…) loop can provide a compact structure for counter-controlled type of loops. 7CompSci Principles of Programming count = 0 while count < 100: print("Programming is fun!") count = count + 1 count = 0 while count < 100: print("Programming is fun!") count = count + 1 Programming is fun! … for count in range(0, 100): print("Programming is fun!") for count in range(0, 100): print("Programming is fun!") for count in range(…): statement1 statement2 statement3 …

Iteration – for…in loops  Note that in the for…in loop on the previous slide the name given to the loop variable can be any identifier. The following two loops behave in exactly the same way.  Note that in the for…in loops above, the loop body is executed for each value in the sequence defined by the range() function. In the loop, the loop variable takes each value of the sequence defined by the range() function, e.g., 8CompSci Principles of Programming for number in range(0, 100): print("Programming is fun!") for number in range(0, 100): print("Programming is fun!") for value in range(0, 100): print("Programming is fun!") for value in range(0, 100): print("Programming is fun!") for number in range(0, 5): print(number) for number in range(0, 5): print(number) Programming is fun! … for number in range(3, 7): print(number * 5) for number in range(3, 7): print(number * 5)

Complete the code  Complete the for…in range(…) loop so that the output is:  Complete the for…in loop so that the output is: for in : print(number, end = " ") print() for in : print(number, end = " ") print() CompSci Principles of Programming for in : print(value, end = " ") print() for in : print(value, end = " ") print()

Give the output def show_output(): total = 0 for number in range(9, 20): if number % 2 == 0 or number % 3 == 0: total += 1 print(total) def main(): show_output() main() def show_output(): total = 0 for number in range(9, 20): if number % 2 == 0 or number % 3 == 0: total += 1 print(total) def main(): show_output() main() 10CompSci Principles of Programming

Complete the function  An amount doubles each year. Using a for…in loop complete the double_each_year() function which prints the growth of the parameter value, start_amt, for the given number of years ( num_years). The first line printed by the function is the starting amount. Each line of the output is numbered starting from the number 1. The function returns the final amount. def double_each_year(start_amt, num_years): def main(): print(double_each_year(24, 4)) print(double_each_year(235, 3)) print(double_each_year(15, 5)) main() def double_each_year(start_amt, num_years): def main(): print(double_each_year(24, 4)) print(double_each_year(235, 3)) print(double_each_year(15, 5)) main() Starting with: 24 1: 48 2: 96 3: 192 4: 384 After 4 years: 384 Starting with: 235 1: 470 2: 940 3: 1880 After 3 years: 1880 Starting with: 15 1: 30 2: 60 3: 120 4: 240 5: 480 After 5 years: 48 11CompSci Principles of Programming

for…in loops - example  Using a for…in loop complete the print_series() function which prints a series of numbers starting from the parameter value, start_num. The second number printed is the first number plus 1, the third number is the second number plus 2, the fourth number is the third number plus 3, and so on, e.g., a series of 8 numbers starting from the number 2 is: def print_series(start_num, how_many): def main(): print_series(2, 8) print_series(5, 12) print_series(16, 9) main() def print_series(start_num, how_many): def main(): print_series(2, 8) print_series(5, 12) print_series(16, 9) main() CompSci Principles of Programming

while loop vs for…in loops  Counter-controlled while loops can be converted into for…in loops and vice versa.  Not all while loops can be expressed using a for…in loop (only the ones for which we know exactly how many times the loop body is to be executed).  All for…in loops can be expressed as while loops. 13CompSci Principles of Programming count = 0 while count < 100: print("Programming is fun!") count = count + 1 count = 0 while count < 100: print("Programming is fun!") count = count + 1 for count in range(0, 100): print("Programming is fun!") for count in range(0, 100): print("Programming is fun!")

Convert - while loop for…in loop  Convert the following while loop into a for…in loop:  Convert the following for…in loop into a while loop: 14CompSci Principles of Programming counter = 12 while counter < 260: print(counter) counter = counter + 10 counter = 12 while counter < 260: print(counter) counter = counter + 10 for num in range(45, 3, -5): print(num * 2) for num in range(45, 3, -5): print(num * 2)

Same output?  Do the following two loops give the same output? If not, what is the difference in output? 15CompSci Principles of Programming top = 6 bottom = 0 count = 0 sum = 0 while bottom < top: count += 1 sum += top + bottom bottom += 2 print("count:", count, "sum:", sum) top = 6 bottom = 0 count = 0 sum = 0 while bottom < top: count += 1 sum += top + bottom bottom += 2 print("count:", count, "sum:", sum) top = 6 count = 0 sum = 0 for bottom in range(0, top + 1, 2): count += 1 sum += top + bottom print("count:", count, "sum:", sum) top = 6 count = 0 sum = 0 for bottom in range(0, top + 1, 2): count += 1 sum += top + bottom print("count:", count, "sum:", sum)

Which to use, while loop or for…in loop? Which type of loop should you use?  A while loop is more general and can handle any numbers and kinds of repetitions, e.g., known size or user controlled loop (the number of times the loop is executed depends on the user).  A for…in loop is more compact and particularly useful for processing a sequence of values one by one. 16CompSci Principles of Programming

Summary  In a Python program:  the Python range() function is used to define a sequence of values  a for…in loop can be used to implement counter-controlled repetition  a for…in loop (with a range function) can be converted into a while loop and vice versa  a for…in loop which uses the range() function has the following syntax: for a_variable in range(…): statement1 statement2 … 17CompSci Principles of Programming

Examples of Python features used in this lecture def get_divisor_sum(number): divisor = 1 div_sum = 0 middle_num = number // 2 for i in range(middle_num + 1): if number % divisor == 0: div_sum += divisor return div_sum def fun_stuff(): total = 0 for number in range(9, 20): if number % 2 == 0 or number % 3 == 0: total += 1 print(total) 18CompSci Principles of Programming