Condition Controlled Loops. Introduction to Programming - Python

Similar documents
Condition Controlled Loops. Introduction to Programming - Python

CONDITION CONTROLLED LOOPS. Introduction to Programming - Python

Topics. Introduction to Repetition Structures Often have to write code that performs the same task multiple times. Controlled Loop

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

LOOPS. Repetition using the while statement

(Python) Chapter 3: Repetition

Repetition, Looping. While Loop

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Loops (while and for)

Loops In Python. In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.

While Loops A while loop executes a statement as long as a condition is true while condition: statement(s) Statement may be simple or compound Typical

Introduction to Computer Science Unit 3. Programs

Controls Structure for Repetition

Repetition, Looping CS101

In this lab, you will learn more about selection statements. You will get familiar to

Loops In Python. In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.

Outline. Announcements. Homework 2. Boolean expressions 10/12/2007. Announcements Homework 2 questions. Boolean expression

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

Chapter 4 Loops. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

(Refer Slide Time: 00:26)

Number System. Introduction. Natural Numbers (N) Whole Numbers (W) Integers (Z) Prime Numbers (P) Face Value. Place Value

While Loops CHAPTER 5: LOOP STRUCTURES. While Loops. While Loops 2/7/2013

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently.

ECE 122. Engineering Problem Solving with Java

Chapter 6. Repetition Statements. Animated Version The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Control structure: Repetition - Part 2

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

Chapter 4 Loops. int x = 0; while ( x <= 3 ) { x++; } System.out.println( x );

Java Coding 3. Over & over again!

Java Outline (Upto Exam 2)

Course Learning Outcomes for Unit I. Reading Assignment. Unit Lesson. UNIT I STUDY GUIDE Number Theory and the Real Number System

How To Think Like A Computer Scientist, chapter 3; chapter 6, sections

Python Activity 7: Looping Structures WHILE Loops

CONTROL FLOW CREATING ALTERNATE PATHS OF EXECUTION USING: BRANCHING WHILE LOOPS FOR LOOPS

Control Structures II. Repetition (Loops)

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Chapter Goals. Contents LOOPS

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Looping. Arizona State University 1

Looping Subtasks. We will examine some basic algorithms that use the while and if constructs. These subtasks include

Lab 2: Booleans, Strings, Random Numbers, Recursion, Variables, Input function

Lecture 7 Tao Wang 1

Lecture 11: while loops CS1068+ Introductory Programming in Python. for loop revisited. while loop. Summary. Dr Kieran T. Herley

Textbook. Topic 5: Repetition. Types of Loops. Repetition

Beyond programming. CS 199 Computer Science for Beginners Spring 2009 Lois Delcambre Week 5/12/2009 1

LAB 5: REPETITION STRUCTURE(LOOP)

Crude Video Game Simulator Algorithm

Motivations. Chapter 5: Loops and Iteration. Opening Problem 9/13/18. Introducing while Loops

CS 1803 Pair Homework 3 Calculator Pair Fun Due: Wednesday, September 15th, before 6 PM Out of 100 points

Computer Programming I - Unit 5 Lecture page 1 of 14

Programming Language. Control Structures: Repetition (while) Eng. Anis Nazer Second Semester

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

What is Iteration? CMPT-101. Recursion. Understanding Recursion. The Function Header and Documentation. Recursively Adding Numbers

Algorithms and Data Structures

Lecture Transcript While and Do While Statements in C++

METHODS EXERCISES GuessNumber and Sample run SumAll Sample Run

Here is a sample IDLE window illustrating the use of these two functions:

Chapter 4 Loops. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

LAB 5: SELECTION STATEMENTS

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control

REPETITION CONTROL STRUCTURE LOGO

Advanced Computer Programming

Loops / Repetition Statements

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

CS112 Lecture: Repetition Statements

Math Day 2 Programming: How to make computers do math for you

11.3 Function Prototypes

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

Control Statements Loops

MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON

Theory of control structures

CIS 3260 Intro to Programming in C#

Why Is Repetition Needed?

Loop structures and booleans

Programming for Experimental Research. Flow Control

An Introduction to Programming with C++ Sixth Edition. Chapter 7 The Repetition Structure

cs1114 REVIEW of details test closed laptop period

Information Science 1

6.S189 Homework 2. What to turn in. Exercise 3.1 Defining A Function. Exercise 3.2 Math Module.

Information Science 1

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output

This is the basis for the programming concept called a loop statement

Test #2 October 8, 2015

LESSON 3 CONTROL STRUCTURES

6.149 Checkoff 2. What to complete. Recall: Creating a file and running a program in IDLE.

Lecture. Loops && Booleans. Richard E Sarkis CSC 161: The Art of Programming

Chapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved

Repetition and Loop Statements Chapter 5

Overview. Iteration 4 kinds of loops. Infinite Loops. for while do while foreach

3 The L oop Control Structure

Islamic University of Gaza Computer Engineering Dept. C++ Programming. For Industrial And Electrical Engineering By Instructor: Ruba A.

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

C++ Programming: From Problem Analysis to Program Design, Third Edition

LAB 5: REPETITION STRUCTURE(LOOP)

Getting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners

T H E I N T E R A C T I V E S H E L L

Transcription:

Condition Controlled Loops Introduction to Programming - Python

Decision Structures Review

Programming Challenge: Review Ask the user for a number from 1 to 7. Tell the user which day of the week was selected! Assume the week starts on a Sunday. If the user enters a number that is not valid be sure to tell the user that negative numbers, zero, and numbers over 7 do not represent a day of the week!

Trace the Output

Trace the Output

Trace the Output

Generating Random Numbers

Random Integer Example

Programming Challenge Ask the user to guess a number between 1 and 10. Assume they will enter an Integer. Have the program randomly pick a number between 1 and 10 that is your secret number (for example, 5) If the user types in your secret number, tell them that they win! If the user types in a number less than or greater than your secret number, tell them that they re either above or below the number and to try once again. Every time you play, the secret number should change.

Programming Challenge: Rock, Paper, Scissors Write a program to ask the user to select one of three options - Rock (r), Paper (p) or Scissors (s) Use the random.randint() function to select an option for the computer Determine the winner and print the result. Rock beats Scissor Scissor beats Paper Paper beats Rock

Random Numbers in the Wild Digital Monkeys with Typewriters recreate Shakespeare

Random Painting

Random Numbers in the Wild http://alteredqualia.com/visualization/evolve/

Repetition Structures

Repetition Structures Programmers commonly find that they need to write code that performs the same task over and over again

Repetition Structures In the previous example our code ended up being one long sequence structure which contained a lot of duplicate code There are several disadvantages to this approach Your programs will tend to get very large Writing this kind of program can be extremely time consuming If part of the duplicated code needs to be corrected then the correction must be implemented many times

Repetition Structures One solution to this kind of problem is to use a repetition structure, which involves the following: Write the code for the operation one time Place the code into a special structure that causes Python to repeat it as many times as necessary We call this a repetition structure or, more commonly, a loop There are a variety of different repetition structures that can be used in Python

Condition Controlled Loops

Condition Controlled Loops A condition controlled loop is programming structure that causes a statement or set of statements to repeat as long as a condition evaluates to True

Condition Controlled Loops

The While Loop In Python we can implement a condition controlled loop by writing a while loop while loops work as follows: Evaluate a Boolean expression. If it is False, skip the block of statements associated with the while loop and condition the program as normal If it is True Execute a series of statements. At the end of the statement block re-evaluate the condition If it is True, repeat the block of statements If it is False, skip the block of statements associated with the while loop and continue the program as normal

The While Loop

Some notes of while loops We refer to the process of going through a loop as an iteration If a loop cycles through 5 times then we say we have iterated through it 5 times The while loop is considered a pre-test loop, meaning that it only iterates upon the successful evaluation of a condition This means that you always need to set up your loop prior to Python being able to work with it (i.e. setting up a control variable)

Warning! When working with a while loop there is nothing to prevent you from writing a Boolean condition that will never evaluate to False If this happens your loop will continue executing forever, or until you send an interrupt to IDLE using the CTRL-C key combination We call this an infinite loop since it never stops executing With the exception of a few special cases you want to try and avoid writing infinite loops

Trace the Output

Programming Challenge: Guess the Number Rewrite the guess the number game we wrote back in the selection statement unit to use a while loop Allow the user to continually guess a number until they eventually guess the correct number

Accumulator Variables and Augmented Assignment Operators

Accumulator Variables Many programming tasks require you to calculate the total of a series of numbers or the number of times you iterate through a loop (kind of like your homework!) We can utilize an accumulator variable to do this.

Using Accumulator Variables Set up your accumulator variables outside of your loops. I generally initialize my accumulator variables right before I enter a repetition structure. Decide on a value you want to start your accumulator values at. 0 or 0.0 is generally a good starting point depending on whether you are counting whole numbers or numbers with fractional values. Use a self-referential assignment statement when incrementing an accumulator variable. Example: counter = counter + 1

Self-referential assignment statements

Augmented Assignment Operators The self-referential assignment statement that we just used is extremely useful, and can be extended to use any of the other math operations we have covered in class so far. a = a + 1 b = b * 2 c = c / 3 d = d - 4

Augmented Assignment Operators However, Python (and most other programming languages) contains a series of shortcuts that can be used to cut down the amount of typing when working with self-referential assignment statements. We call these shortcuts the augmented assignment operators

Augmented Assignment Operators Operator Usage Equal to += c += 5 c = c + 5 -= c -= 2 c = c 2 *= c *= 3 c = c * 2 /= c /= 3 c = c / 3 %= c %= 3 c = c % 3

Programming Challenge: AI Guess a Number game Write a program that asks the user to supply a secret number between 1 and 1,000,000 Then have the computer continually guess until they find the secret number Keep track of the number of attempts Extension: How can this be optimized?

Programming Challenge: ELIZA-Line of Inquiry Take your Eliza code from last week save it with a new version number add a keyword look out re.search() for the word game reply with I love games Rock, Paper, Scissors and shoot wait for user input say which one ELIZA pulled End the game when either the player or the computer earns 3 points see youshoot.py

Sentinels

Sentinels Imagine that you want to ask your users to enter in a large number of items that need to be calculated in a certain way. You don t know how many values the user will be entering. Given our current toolset we really only have ways to handle this kind of scenario: Ask the user at the end of each iteration if they want to continue. This can be annoying and make your program cumbersome if you will be entering in hundreds or thousands of values. Ask the user ahead of time how many items they will be entering. This can be difficult since the user may not know at the beginning of the loop how many items they will be working with.

Sentinels A sentinel value is a pre-defined value that the user can type in to indicate that they are finished entering data Example: >> Enter a test score (type -1 to end): 100 >> Enter a test score (type -1 to end): 80 >> Enter a test score (type -1 to end): -1 >> Your test average is: 90 % In the example above the value -1 is considered a sentinel -- it indicates to the program that the user is finished entering data. Sentinels must be distinctive enough that they will not be mistaken for regular data (in the previous example the value -1 was used there is no way that a real test value could be -1)

Programming Challenge: Adding Machine Write a program that asks the user for an integer Add the supplied integer to a total variable Draw that amount of squares Ask the user for another integer Draw that amount of squares When the user enters a 0 value end the program and display the sum (and all the squares) for the user

Repetition Flow Control

The break command The break command is a special Python command that can be used to immediately end a loop. It will not, however, end your program it simply ends the current repetition structure and allows the program to pick up from the line directly after the end of your loop Note that when the break command runs it will immediately terminate the current loop, which prevents any commands in the loop after the break command from running

Trace the Output

Prime Number Tester Write a program that asks the user for an integer Test to see if the number is prime. A prime number is any number that is evenly divisible by 1 and itself. If it is draw a square on that location and up until 500,500

Simple Data Validation

Simple Data Validation Often we need to ask the user to supply a value in our programs But as you know you can't always trust the user to supply you with usable data! One strategy you can use to ensure that you get "good" data is to "validate" the user's input. This involves asking the user for a value if it meets our criteria we can continue. If not we will need to ask the user to re-supply the value.

Programming Challenge With our ELIZA Program, which game they would like to play (pretend ELIZA can play three games of your choice) If the user supplies an invalid game you should re-prompt them See HAL for reference: https://www.youtube.com/watch?v=arj8cagm6je&spfreload=10 Once you have a game you can play start the game sequence.

Infinite Loops

Infinite Loops What happens when the condition is never false? The loop will run forever! (Or at least as long as the computer is powered up ) In general, we want to be avoid infinite loops.

Infinite Loops: An Artistic View M.C. Escher (1898-1972) was a Dutch graphic artist who used mathematical concepts in some of his drawings. (http://en.wikipedia.org/wiki/ M._C._Escher) Here is one vision of an infinite loop: