Loops CIS 40 – Introduction to Programming in Python

Slides:



Advertisements
Similar presentations
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Advertisements

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.
1 9/29/06CS150 Introduction to Computer Science 1 Loops Section Page 255.
1 9/28/07CS150 Introduction to Computer Science 1 Loops section 5.2, 5.4, 5.7.
Loops – While, Do, For Repetition Statements Introduction to Arrays
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
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.
Fundamentals of Python: From First Programs Through Data Structures
Fundamentals of Python: First Programs
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
Lecture Set 5 Control Structures Part D - Repetition with Loops.
PYTHON: PART 2 Catherine and Annie. VARIABLES  That last program was a little simple. You probably want something a little more challenging.  Let’s.
By the end of this session you should be able to...
Introduction to Loops For Loops. Motivation for Using Loops So far, everything we’ve done in MATLAB, you could probably do by hand: Mathematical operations.
More Python!. Lists, Variables with more than one value Variables can point to more than one value at a time. The simplest way to do this is with a List.
Chapter 7 Problem Solving with Loops
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Development Environment
REPETITION CONTROL STRUCTURE
CS161 Introduction to Computer Science
Topics Introduction to Repetition Structures
ECS10 10/10
Loop Structures.
Variables, Expressions, and IO
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Introduction To Flowcharting
Functions CIS 40 – Introduction to Programming in Python
Topic 5 for Loops -Arthur Schopenhauer
Topics Introduction to Repetition Structures
Lecture 07 More Repetition Richard Gesick.
Iterations Programming Condition Controlled Loops (WHILE Loop)
Lecture 4B More Repetition Richard Gesick
Logical Operators and While Loops
Print slides for students reference
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.
Lecture 4A Repetition Richard Gesick.
LESSON 11 – WHILE LOOPS UNIT 5 – 1/10/17.
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
Selection CIS 40 – Introduction to Programming in Python
Outline Altering flow of control Boolean expressions
File IO and Strings CIS 40 – Introduction to Programming in Python
For -G7 programing language Teacher / Shamsa Hassan Alhassouni.
Introduction to Object-Oriented Programming with Java--Wu
Repetition Structures
Understanding the Three Basic Structures
Algorithm Discovery and Design
Iteration: Beyond the Basic PERFORM
Coding Concepts (Basics)
Repetition Control Structure
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Chapter 6: Repetition Statements
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Computing Fundamentals
CSC115 Introduction to Computer Programming
Language Constructs Construct means to build or put together. Language constructs refers to those parts which make up a high level programming language.
CHAPTER 6: Control Flow Tools (for and while loops)
Logical Operators and While Loops
Java Programming Loops
Chapter 4: Repetition Structures: Looping
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Using C++ Arithmetic Operators and Control Structures
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.
Software Development Techniques
JavaScript 101 Lesson 8: Loops.
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

Loops CIS 40 – Introduction to Programming in Python De Anza College Clare Nguyen

Intro (1 of 2) In this module we learn about loops, which are instructions that cause the CPU to run a block of code over and over. The idea of running a block of code repeatedly may at first seem like a bug rather than something we want. For example, if we go to an ATM and withdraw $40, we want the machine to take out only $40 from our account. We don’t want it to repeatedly withdraw $40 from our account ten more times. However, we recall that at the end of a withdrawal transaction, the ATM asks if we want to do another transaction. And if we select yes, we could do another withdrawal or a deposit. The code running the ATM will loop, or run the transaction code again, as many times as we choose. A loop that is put in the correct location in the code can be a useful tool.

Intro (2 of 2) In this module we start the discussion with a few features of Python that support loops. Then we explore the 2 loops in Python: for and while loops.

Update a Variable A variable in a program often needs to be updated to have the newest data value. The simplest way to update a variable is to assign the new data back to the variable: num = 5 # initialize num with 5 num = num * 2 # multiply 5 * 2 and store 10 back in num # The value in num is updated to 10 Two very common ways to update a variable is by incrementing or decrementing it. Increment: num = num + 1 the value of num increases Decrement: num = num – 1 the value of num decreases

The range Function The range function creates a range of integers as the output. Examples: range (6) Output: 0, 1, 2, 3, 4, 5 range(2, 5) Output: 2, 3, 4 range(10, 18, 2) Output: 10, 12, 14, 16 range(10, 4, -1) Output: 10, 9, 8, 7, 6, 5 Format: range( start, stop, step ) start: an optional number which is the starting number for the output. If not used, the start is 0. stop: a required number which is the stopping point of the range. The range does not include the stopping number. step: an optional number to specify the step or difference between values in the range. If not used, the step is +1.

Repetition Recall our first line of code: The print statement will output one line of text. What if we want the same line of text to be printed 50 times? Instead of having to copy and paste the print statement 50 times, we write the print statement one time and then ask the computer to repeatedly run it 50 times for us. To ask the computer to run a block of code repeatedly for a specific number of time, we use a for loop.

The for Loop (1 of 2) Format: for iterator in list: statement block Flow chart: a list of data values an iteration variable loop body (indented) for iterator in list: statement block The size of the list determines how many times the loop body will be run. If the list has 5 data values, the loop body will run 5 times. Each time that the loop body runs is called an iteration. During each iteration, the iterator contains the value of one data in the list. done run loop body one time iterator = next data in list iterator = first data in list iterator has data? no yes

The for Loop (1 of 2) Example: There are 6 values in the list, from the range function output: 0, 1, 2, 3, 4, 5 1st loop iteration: i is 0 “Hello world!” is printed 2nd iteration: i is 1 “Hello world!” is printed 3rd iteration: i is 2 “Hello world!” is printed 4th iteration: i is 3 “Hello world!” is printed 5th iteration: i is 4 “Hello world!” is printed 6th iteration: i is 5 “Hello world!” is printed No more data in list, loop stops There are 6 data values in the list, and the text is printed 6 times.

More for Loop Examples Note how the iterator i contains each value in the list, one value for each iteration of the loop: What does this print? What is the last number that is printed? code output

Demo Click for a video demo of how to use the for loop to calculate a running sum

The while Loop Python provides us with a second way to tell the computer to run a block of code repeatedly: the while loop. The while loop is used when we want the block of code to keep running repeatedly while some condition (a Boolean expression) is True. Format: while Boolean_expression: statement block (or loop body) Flow chart: The Boolean_expression is called the test condition because it is the condition that determines whether the loop continues. Looping continues as long as the test condition is True. done run loop body one time evaluate Boolean_expression False True

while Loop Example (1 of 2) The following script prints the square of positive integers, starting from 1, up to a max limit. The max limit is from a user input, so we don’t know how large it is. If it’s large, there will be many iterations of the loop before we can reach the limit. If it’s small, then there may be only a couple of iterations. Since we can’t tell how many times the loop might run, we use the while loop, which runs the loop body as long as the test condition (square < max limit) is True. Code: Output: code

while Loop Example (2 of 2) Taking a closer look at how the example code runs: We start by initializing num to 1, the first number that will be squared. Start with test: 12 < 30 is True => print 1 num is updated to 2 Loop back to test: 22 < 30 is True => print 4 num is updated to 3 Loop back to test with num = 3, 4, 5 and run loop body Loop back to test: 62 < 30 is False => the loop stops Print final line of text

Number of Iterations What is the minimum number of iterations for a while loop? The test condition is False right away on the very first test, so the loop never runs. The minimum number of iterations is 0. What is the maximum number of iterations for a while loop? The test condition is True on the first test, so num is incremented. This means the test condition is also True on the next tests as num keeps incrementing. The test condition never becomes False so the loop keeps running. This is known as an infinite loop. The maximum number of iterations is infinity (in theory). In practice most of us will stop the run away loop with control-c.

Test Condition Must-Haves Since the test condition controls how many iterations the loop will run, it is important that we set this condition properly. There are 2 steps that we must ensure for the test condition: Initialize: before the test statement Update: in the loop body In the example code: If we didn’t initialize num to 1, then there is no data to use for the test condition. If we didn’t update num in the loop body, then num will stay at the value 1, and the test condition will always be True. initialize update

Demo Click for a video demo of how to use the while loop to check the user input

Which Loop To Use We have 2 types of loops to use whenever we want the computer to re-run a block of code: for and while. If we want the block of code to be repeatedly run for a certain number of times, then it is simplest to use the for loop. The while loop can also be used for repeating code a number of times, but it takes more effort to remember to initialize and update the test condition. If we want the block of code to be repeatedly run as long as a condition is True, then it is simplest to use the while loop because it has a built-in test condition in its format. When using the while loop, we should make sure that there is an initialization and an update of the test condition so that the loop will run the correct number of iterations.

What’s Next (1 of 2) We have learned a very useful construct that allows computers to keep running: a loop. Whether we are at an ATM machine and do one transaction after another, or we’re at the Python shell and keep getting the >>> prompt to enter another instruction, it’s a loop that drives the repetitive behavior of a device. We have now learned how to use all the basic components of modern programming language: A way to store data (variables) A way to perform computation (operators and expressions) A way to communicate with the outside world (standard IO) A way to modularize code (functions) A way to make decisions (if statements) A way to repeat instructions (loops)

What’s Next (2 of 2) For the rest of the modules in this class we will get an overview of the more advanced features of many current programming languages: A way to read from and store data to files A way to organize data into collections (or groups) to process them more efficiently A way to use the class data type to create our own data type so that we’re not limited to just the Python data types We will begin with file IO in the next module.