Loops (While and For) CSE 1310 – Introduction to Computers and Programming 1.

Slides:



Advertisements
Similar presentations
While loops.
Advertisements

CS0007: Introduction to Computer Programming
CS107 Introduction to Computer Science Lecture 3, 4 An Introduction to Algorithms: Loops.
1 Chapter Five Selection and Repetition. 2 Objectives How to make decisions using the if statement How to make decisions using the if-else statement How.
Intro to CS – Honors I Control Flow: Loops GEORGIOS PORTOKALIDIS
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 4 – C Program Control Outline 4.1Introduction.
Introduction to Computers and Programming Lecture 9: For Loops New York University.
CS107 Introduction to Computer Science Loops. Instructions Pseudocode Assign values to variables using basic arithmetic operations x = 3 y = x/10 z =
1 Parts of a Loop (reminder) Every loop will always contain three main elements: –Priming: initialize your variables. –Testing: test against some known.
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 6: Loop Control Structures.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Chapter 2 Writing Simple Programs
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved The switch Multiple-Selection Statement switch.
Fundamentals of Python: From First Programs Through Data Structures
CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7.
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
Fundamentals of Python: First Programs
Chapter 2 Control. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. Repetition, quick overview.
More Looping Structures
Programming for Linguists An Introduction to Python 24/11/2011.
Computer Science 111 Fundamentals of Programming I The while Loop and Indefinite Loops.
CIS 234: LOOPS Adapted from materials by Dr. Donald Bell, 2000 (updated April 2007)
Loops (While and For) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
1 09/20/04CS150 Introduction to Computer Science 1 Let ’ s all Repeat Together.
CS 106 Introduction to Computer Science I 09 / 26 / 2007 Instructor: Michael Eckmann.
Xiaojuan Cai Computational Thinking 1 Lecture 8 Loop Structure Xiaojuan Cai (蔡小娟) Fall, 2015.
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
1 CS 177 Week 6 Recitation Slides Review for Midterm Exam.
Tutorial 9 Iteration. Reminder Assignment 8 is due Wednesday.
COMP Loop Statements Yi Hong May 21, 2015.
9. ITERATIONS AND LOOP STRUCTURES Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Control Flow (Python) Dr. José M. Reyes Álamo. 2 Control Flow Sequential statements Decision statements Repetition statements (loops)
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.
Control Flow (Python) Dr. José M. Reyes Álamo. 2 Control Flow Sequential statements Decision statements Repetition statements (loops)
Python – Part 4 Conditionals and Recursion. Conditional execution If statement if x>0:# CONDITION print (‘x is positive’) Same structure as function definition.
Loops ( while and for ) CSE 1310 – Introduction to Computers and Programming Alexandra Stefan 1.
IST 210: PHP Logic IST 210: Organization of Data IST2101.
More about Iteration Victor Norman CS104. Reading Quiz.
Loops (While and For) CSE 1310 – Introduction to Computers and Programming 1.
Chapter 2 Writing Simple Programs
Control Flow (Python) Dr. José M. Reyes Álamo.
Chapter 4 – C Program Control
Python Loops and Iteration
Python: Control Structures
Lesson 05: Iterations Class Chat: Attendance: Participation
Warm-up Program Use the same method as your first fortune cookie project and write a program that reads in a string from the user and, at random, will.
While Loops in Python.
Do it now activity Green pen activity in books.
Logical Operators and While Loops
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.
Imperative Programming
Loop Structures and Booleans Zelle - Chapter 8
The University of Texas – Pan American
Loops CIS 40 – Introduction to Programming in Python
3 Control Statements:.
More Looping Structures
3. Decision Structures Rocky K. C. Chang 19 September 2018
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
CHAPTER 6: Control Flow Tools (for and while loops)
Logical Operators and While Loops
For loops Taken from notes by Dr. Neil Moore
Another Example Problem
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.
Topic: Loops Loops Idea While Loop Introduction to ranges For Loop
More Looping Structures
Imperative Programming
Presentation transcript:

Loops (While and For) CSE 1310 – Introduction to Computers and Programming 1

Motivation Suppose we want to write a program that does this: – Ask the user to input an integer N. – Prints out all integers between 0 and N. The elements of Python that we have covered so far are not sufficient for writing this program. What is missing: the ability to repeat some instructions as many times as we want.

while loops A while loop is defined as follows: while boolean_expression: line 1 line 2 … line n Line 1, line 2, …, line n are called the body of the while loop. 3

while loop execution while boolean_expression: line 1 line 2 … line n first line after loop This is how a while loop gets executed: – Step 1: evaluate boolean_expression. – Step 2: If the expression is false, go to the first line after the loop. – Step 3: If expression is true, execute the body of the while loop, and go back to step 1. 4

An example of a while loop number_text = input("enter an integer: ") number = int(number_text) i = 0 while (i <= number): print(i) i = i+1 print("done with the while loop") 5

while loops: indentation matters number_text = input("enter an integer: ") number = int(number_text) i = 0 while (i <= number): print(i) i = i+1 print("done with the while loop") 6 What does this program do?

Designing a while loop When you design a while loop, you need to make sure that the loop will terminate exactly when needed, not before, and not after. You will need to define a test (boolean expression), that determines when to stay in the loop and when to exit. You need to update variables within the body of the loop, as needed. 7

for loops (simplest version) A for loop can be defined as follows (note: this definition will be extended when we talk about lists). for variable in range(from, to): line 1 line 2 … line n Line 1, line 2, …, line n are called the body of the for loop. 8

for loop execution (simplest version) for variable in range(from, to): line 1 line 2 … line n first line after loop This is how a for loop gets executed: – Step 1: variable = from – Step 2: If variable >= to, go to first line after the loop. – Step 3: execute the body of the loop (lines 1 to n). – Step 4: update variable to variable + step, and go to step 2 9

An example of a for loop number_text = input("enter an integer: ") number = int(number_text) for i in range(0, number+1): print(i) print("done with the for loop") 10

WARNING about using range If you want to process the integers between X and Y (including X and Y), you need to use range(X, Y+1). If you use range(X, Y), the for loop will go up to Y-1, not up to Y. This is an extremely common source of bugs. 11

for loops, version 2 A for loop can also be defined as follows (note: this definition will be extended when we talk about lists). for variable in range(from, to, step): line 1 line 2 … line n Line 1, line 2, …, line n are called the body of the for loop. 12

for loop execution for variable in range(from, to, step): line 1 line 2 … line n first line after loop This is how a for loop gets executed: – Step 1: variable = from – Step 2: If step is positive and variable >= to, or step is negative and variable <= to, go to first line after the loop. – Step 3: variable = variable + step – Step 4: execute the body of the loop (lines 1 to n). – Step 5: go to step 2 13

A for loop with a step number_text = input("enter an integer: ") number = int(number_text) for i in range(0, number+1, 13): print(i) print() print("printed all numbers between 0 and", number) print("that are divisible by 13") 14

A for loop with a negative step number_text = input("enter an integer: ") number = int(number_text) for i in range(number, -1, -1): print(i) print() print("printed all numbers between", number) print("and 0 in reverse order") 15

A for loop with a negative step number_text = input("enter an integer: ") number = int(number_text) for i in range(number, -1, -1): print(i) print() print("printed all numbers between", number) print("and 0 in reverse order") 16 Note that the second argument of the range is -1, not 0.

The break statement The break statement forces termination of the current while loop or for loop. Example: print the first number >= N that is divisible by 13. N = int(input("enter an integer: ")) i = N while True: if (i % 13 == 0): print("first number >=", N, "divisible by 13 is ", i) break i = i+1 17

The continue statement The continue statement skips the rest of the body of the loop and goes directly to the next iteration (or to termination). Example: print numbers between 1 and N that are divisible by 13. N = int(input("enter an integer: ")) for i in range(0, N+1): if (i % 13 != 0): continue print(i) 18

for loops, general version A for loop, in general, is defined as follows. for variable in sequence_of_values: line 1 line 2 … line n Line 1, line 2, …, line n are called the body of the for loop. sequence_of_values can be, among other things, a string or a list. We will cover lists later in the course. 19

for loop execution for variable in sequence_of_values: line 1 line 2 … line n first line after loop This is how a for loop gets executed: – Step 1: variable = first value from sequence_of_values (if sequence_of_values is empty, go to first line after the loop.) – Step 2: execute the body of the loop (lines 1 to n). – Step 3: if variable has received the last value in sequence_of_values, exit the loop (go to the first line after the loop). – Step 4: set variable equal to next value in sequence_of_values, and go to Step 2. 20

Sequences of Values range(X, Y): – X and Y must be integers. – range(X, Y) generates the sequence X, X+1,..., Y-2, Y-1. – Notice that this sequence EXCLUDES Y. range(X, Y, step) – X, Y, step must all be integers. – range(X, Y, step) generates the sequence: X, X+1*step, X+2*step, …, X+k*step where k is the largest integer such that: X+k*step < Y (if step is positive) X+k*step > Y (if step is negative) 21

Sequences of Values Any string is a sequence. – String 'hello' is the sequence of values: 'h', 'e', 'l', 'l', o. 22

Example 1: for loop with a string text = 'hello' for i in text: print(i) What values will variable i take in the for loop? What will the for loop print? 23

Example 1: for loop with a string text = 'hello' for i in text: print(i) What values will variable i take in the for loop? First 'h', then 'e', then 'l', then 'l', then o. What will the for loop print? h e l l o 24

Example 2: for loop with a string text = input("enter some text: ") counter = 0 for i in text: print(i) if (i == 'a'): print("found an 'a'") counter = counter+1 print("\nThe letter 'a' appears", counter, "times") 25

Example 2: for loop with a string text = input("enter some text: ") counter = 0 for i in text: print(i) if (i == 'a'): print("found an 'a'") counter = counter+1 print("\nThe letter 'a' appears", counter, "times") 26 New elements: string equality, single quote within double quotes, "\n"

Example 3: for loop with a string # count the number of vowels in text entered by the user. text = input("enter some text: ") vowel_counter = 0 for i in text: if (i in 'aeiouyAEIOUY'): vowel_counter = vowel_counter + 1 print("\nThe text contains", vowel_counter, "vowels.") 27

break while boolean_expression: line 1 line 2 … line n first line after loop Suppose that we execute a break within the body of the while loop. What line of code will be executed next? 28

break while boolean_expression: line 1 line 2 … line n first line after loop Suppose that we execute a break within the body of the while loop. What line of code will be executed next? – The first line after the loop. 29

break for variable in sequence_of_values: line 1 line 2 … line n first line after loop Suppose that we execute a break within the body of the for loop. What line of code will be executed next? 30

break for variable in sequence_of_values: line 1 line 2 … line n first line after loop Suppose that we execute a break within the body of the for loop. What line of code will be executed next? – The first line after the loop. 31

continue while boolean_expression: line 1 line 2 … line n first line after loop Suppose that we execute a continue within the body of the while loop. What line of code will be executed next? 32

continue while boolean_expression: line 1 line 2 … line n first line after loop Suppose that we execute a continue within the body of the while loop. What line of code will be executed next? – while boolean_expression. 33

continue for variable in sequence_of_values: line 1 line 2 … line n first line after loop Suppose that we execute a continue within the body of the for loop. What line of code will be executed next? 34

continue for variable in sequence_of_values: line 1 line 2 … line n first line after loop Suppose that we execute a continue within the body of the for loop. What line of code will be executed next? – if we did not reach the last value in sequence_of_values, variable gets updated to next value, and we move to line 1. – else, we go to the first line after the loop. 35

Break and Continue in Nested Loops for variable1 in sequence1: # start of loop 1... for variable2 in sequence2: # start of loop 2... break... first line after loop2... first line after loop1 Suppose some break line belongs to multiple loops. If that break statement is executed, what line of code do we go to? 36

Nested Loops A loop can be part of another group. A loop that is a part of another group is called a nested loop. Example 1: for a in range(1, 11): # start of loop 1 print("multiples of ", a, ":") for b in range(1, 11): # start of loop 2 print(a, "*", b, "=", a*b) print() 37

Nested Loops A loop can be part of another group. A loop that is a part of another group is called a nested loop. Example 2: a = 1 while a <= 10: # start of loop 1 print("multiples of ", a, ":") for b in range(1, 11): # start of loop 2 print(a, "*", b, "=", a*b) print() a = a

Break and Continue in Nested Loops for variable1 in sequence1: # start of loop 1... for variable2 in sequence2: # start of loop 2... break... first line after loop 2... first line after loop 1 Suppose some break line belongs to multiple loops. If that break line is executed, what line of code do we go to? 39

Break and Continue in Nested Loops for variable1 in sequence1: # start of loop 1... for variable2 in sequence2: # start of loop 2... break... first line after loop 2... first line after loop 1 Suppose some break line belongs to multiple loops. If that break line is executed, what line of code do we go to? – The first line after the innermost loop containing the break. 40

Break and Continue in Nested Loops for variable1 in sequence1: # start of loop 1... for variable2 in sequence2: # start of loop 2... break... first line after loop 2... first line after loop 1 What line is executed after the break in this example? 41

Break and Continue in Nested Loops for variable1 in sequence1: # start of loop 1... for variable2 in sequence2: # start of loop 2... break... first line after loop 2... first line after loop 1 What line is executed after the break in this example? – The innermost loop that the break belongs to is loop 2. – The next line will be the first line after loop 2 (shown in green). 42

Break and Continue in Nested Loops for variable1 in sequence1: # start of loop 1... for variable2 in sequence2: # start of loop 2... first line after loop 2... break... first line after loop 1 What line is executed after the break in this example? 43

Break and Continue in Nested Loops for variable1 in sequence1: # start of loop 1... for variable2 in sequence2: # start of loop 2... first line after loop 2... break... first line after loop 1 What line is executed after the break in this example? – The innermost loop that the break belongs to is loop 1. – The next line will be the first line after loop 1 (shown in green). 44

Break and Continue in Nested Loops for variable1 in sequence1: # start of loop 1... for variable2 in sequence2: # start of loop 2... continue... first line after loop 2... first line after loop 1 Suppose some continue line belongs to multiple loops. If that continue line is executed, what line of code do we go to? 45

Break and Continue in Nested Loops for variable1 in sequence1: # start of loop 1... for variable2 in sequence2: # start of loop 2... continue... first line after loop 2... first line after loop 1 Suppose some continue line belongs to multiple loops. If that continue line is executed, what line of code do we go to? – The first line of the innermost loop containing the continue. 46

Break and Continue in Nested Loops for variable1 in sequence1: # start of loop 1... for variable2 in sequence2: # start of loop 2... continue... first line after loop 2... first line after loop 1 What line is executed after continue in this example? 47

Break and Continue in Nested Loops for variable1 in sequence1: # start of loop 1... for variable2 in sequence2: # start of loop 2... continue... first line after loop 2... first line after loop 1 What line is executed after continue in this example? – The innermost loop that the continue belongs to is loop 2. – The next line will be the first line of loop 2 (shown in green). 48

Break and Continue in Nested Loops for variable1 in sequence1: # start of loop 1... for variable2 in sequence2: # start of loop 2... first line after loop 2... continue... first line after loop 1 What line is executed after continue in this example? 49

Break and Continue in Nested Loops for variable1 in sequence1: # start of loop 1... for variable2 in sequence2: # start of loop 2... first line after loop 2... continue... first line after loop 1 What line is executed after continue in this example? – The innermost loop that the continue belongs to is loop 1. – The next line will be the first line of loop 1 (shown in green). 50

Example 1 a = 1 while a <= 10: # start of loop 1 print("multiples of ", a, ":") for b in range(1, 11): # start of loop 2 print(a, "*", b, "=", a*b) if b == 5: break print() a = a

Example 2 a = 1 while a <= 10: # start of loop 1 print("multiples of ", a, ":") for b in range(1, 11): # start of loop 2 print(a, "*", b, "=", a*b) print() if a == 5: break a = a