Condition Controlled Loops. Introduction to Programming - Python

Similar documents
CONDITION CONTROLLED LOOPS. Introduction to Programming - Python

Condition Controlled Loops. Introduction to Programming - Python

Repetition Structures

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

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

METHODS EXERCISES GuessNumber and Sample run SumAll Sample Run

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

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

Lecture 7 Tao Wang 1

More about Loops and Decisions

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

Math Glossary Numbers and Arithmetic

LOOPS. Repetition using the while statement

LAB 5: REPETITION STRUCTURE(LOOP)

Math 6 Unit 2: Understanding Number Review Notes

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

Loops / Repetition Statements

Repetition, Looping. While Loop

Loops (while and for)

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

Topic 3: Fractions. Topic 1 Integers. Topic 2 Decimals. Topic 3 Fractions. Topic 4 Ratios. Topic 5 Percentages. Topic 6 Algebra

Decisions, Decisions. Testing, testing C H A P T E R 7

CpSc 1011 Lab 4 Formatting and Flow Control Windchill Temps

LAB 5: REPETITION STRUCTURE(LOOP)

(Refer Slide Time: 00:26)

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

Algorithms and Data Structures

Lecture Transcript While and Do While Statements in C++

6. Control Statements II

Controls Structure for Repetition

Chapter 5 : Repetition (pp )

ECE 122. Engineering Problem Solving with Java

EXCEL INTERMEDIATE 2016

Control structure: Repetition - Part 2

cs1114 REVIEW of details test closed laptop period

3rd Grade Mathematics

Eng. Mohammed S. Abdualal

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

Accuplacer Arithmetic Study Guide

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

(Python) Chapter 3: Repetition

ADD Identifier-1 TO Identifier-2 Literal-1. ADD Identifier-1. GIVING Identifier-2 Literal-1

Python Programming: An Introduction to Computer Science

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

CS112 Lecture: Repetition Statements

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

Lab ACN : C++ Programming Exercises

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

Java Coding 3. Over & over again!

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

Fundamentals of Programming (Python) Getting Started with Programming

Add Subtract Multiply Divide

Chapter 3 Problem Solving and the Computer

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

Looping. Arizona State University 1

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

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

Chapter 4 Introduction to Control Statements

Dept. of CSE, IIT KGP

Chapter 3. Iteration

Quiz Determine the output of the following program:

Excerpt from "Art of Problem Solving Volume 1: the Basics" 2014 AoPS Inc.

Florida Math 0018 Correlation of the ALEKS course Florida Math 0018 to the Florida Mathematics Competencies - Lower

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

Python lab session 1

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

More About WHILE Loops

6th Grade Arithmetic (with QuickTables)

Programming. Why is programming fun?

Chapter 4 Repetition Structures. Dr. Zhang COSC 1436 Spring 2017 June 15, 2017

SUMMER REVIEW PACKET 2 FOR STUDENTS ENTERING ALGEBRA 1

Thousands. Hundreds. Tenths. Ones. Tens. Hundredths. Decimal Point. Thousandths. Place Value. 1000s 100s 10s 1s.

An-Najah National University Faculty of Engineering Electrical Engineering Department Programmable Logic Controller. Chapter 11 Math instruction

HOW TO DIVIDE: MCC6.NS.2 Fluently divide multi-digit numbers using the standard algorithm. WORD DEFINITION IN YOUR WORDS EXAMPLE

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

The Practice of Computing Using PYTHON. Chapter 2. Control. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Digital Fundamentals. CHAPTER 2 Number Systems, Operations, and Codes

C Programming for Engineers Structured Program

Mathematics LV 5 (with QuickTables)

Decision Structures CSC1310. Python Programming, 2/e 1

NUMBER SENSE AND OPERATIONS. Competency 0001 Understand the structure of numeration systems and multiple representations of numbers.

Montana City School GRADE 5

Stratford upon Avon School Mathematics Homework Booklet

CS110D: PROGRAMMING LANGUAGE I

Laboratory 5: Implementing Loops and Loop Control Strategies

Rational Number is a number that can be written as a quotient of two integers. DECIMALS are special fractions whose denominators are powers of 10.

Example. CS 201 Selection Structures (2) and Repetition. Nested if Statements with More Than One Variable

Alabama State Standards correlated to Merit Software Math Programs

بسم اهلل الرمحن الرحيم

Introduction to Scientific Computing

Properties of Operations

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

Objectives/Outcomes. Introduction: If we have a set "collection" of fruits : Banana, Apple and Grapes.

in normal arithmetic = == = == 5 7 x 2 = 24 7 * 2 == = 3 remainder 1 7 / 2 7 % 2

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

using cells to create dynamic formulas

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input

Control Structures II. Repetition (Loops)

Transcription:

+ Condition Controlled Loops Introduction to Programming - Python

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

+ Example: Commission calculator for a sales team n Write a program that allows the user to calculate sales commission earned by each member of a sales team. n Currently there are 3 people on the sales team, but there may be more in the future. n Input n Gross sales (float) n Commission Rate (float) n Process n Commission = gross sales * commission rate n Output n Commission earned

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

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

+ Condition Controlled Loops

+ Condition Controlled Loops n 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 n In Python we can implement a condition controlled loop by writing a while loop n while loops work as follows: n Evaluate a Boolean expression. n If it is False, skip the block of statements associated with the while loop and condition the program as normal n If it is True n Execute a series of statements. n At the end of the statement block re-evaluate the condition n If it is True, repeat the block of statements n If it is False, skip the block of statements associated with the while loop and continue the program as normal

+ The While Loop

+ Programming Challenge: Commission Calculator n Write a program that allows the user to calculate sales commission earned by each member of a sales team. n Input n Gross sales (float) n Commission Rate (float) n Process n Commission = gross sales * commission rate n Output n Commission earned

+ Some notes of while loops n We refer to the process of going through a loop as an iteration n If a loop cycles through 5 times then we say we have iterated through it 5 times n The while loop is considered a pre-test loop, meaning that it only iterates upon the successful evaluation of a condition n 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! n When working with a while loop there is nothing to prevent you from writing a Boolean condition that will never evaluate to False n If this happens your loop will continue executing forever, or until you send an interrupt to IDLE using the CTRL-C key combination n We call this an infinite loop since it never stops executing n With the exception of a few special cases you want to try and avoid writing infinite loops

+ Trace the Output

+ Programming Challenge: Temperature Conversion n Write a program that allows the user to convert a temperature in Fahrenheit into Celsius using the following formula n Celsius = (Fahrenheit 32) * 5/9 n After calculating the temperature ask the user if they wish to continue. If so, repeat the conversion with a new number. Otherwise end the program.

+ Divisibility Tester n Write a program that lets the user test to see if a series of numbers are evenly divisible by another number (3). If they are, print out a status message telling the user. n Extension: Start off by asking the user to enter in the number that should be used during the test (i.e. enter 5 if you want to test to see if a range of numbers is evenly divisible by 5)

+ Programming Challenge: Combo Lock n Write a program that asks the user for three numbers n Test those numbers against three secret numbers that represent the combination to a virtual padlock n If the user gets the numbers right you should let them know that they have gained access to your program n If not, allow them to continue to enter combinations until they guess correctly

+ Programming Challenge: Arithmetic Quiz n Write a program that asks the user to answer a simple math problem (5 + 6) n Continually prompt the user for the correct answer. If they answer correctly, congratulate them and end the program. If they answer incorrectly you should re-prompt them for the answer a second time.

+ Accumulator Variables and Augmented Assignment Operators

+ Accumulator Variables n 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!) n We can utilize an accumulator variable to do this.

+ Using Accumulator Variables n Set up your accumulator variables outside of your loops. I generally initialize my accumulator variables right before I enter a repetition structure. n 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. n Use a self-referential assignment statement when incrementing an accumulator variable. Example: n counter = counter + 1

+ Self-referential assignment statements

+ Programming Challenge: Average Commission n Write a program that asks the user to continually enter in the following information for a group of employees: n Sales n Commission Rate n Calculate the commission earned by multiplying sales * commission rate n Keep track of the following information and print out a summary document at the end of your loop n Number of employees n Total sales n Average sales n Total commission due

+ Augmented Assignment Operators n 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. n a = a + 1 n b = b * 2 n c = c / 3 n d = d - 4

+ Augmented Assignment Operators n 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. n 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: Grocery Checkout Calculator n Write a program that asks the user to enter in a series of price values n Calculate a running total of these values n Calculate sales tax (7%) on the total bill and display the result to the user at the end of the program

+ Programming Challenge: My Grades n Write a program that asks the user to enter in a test score along with the total points possible for the test n Allow the user to enter in as many scores as he or she wishes n When finished, calculate the user s average score in the class

+ Programming Challenge: Coin Flips n Write a program that simulates a coin flipping 1 million times n Count the # of heads and tails that result, and display the result to the user after you have finished running the simulation

+ Programming Challenge: Math Quiz Part II n Write a program that asks the user 5 simple math problems n Each problem should utilize random numbers, but you can standardize on a single operation (i.e. subtraction) n Ask the user a question. If they answer correctly, they earn a point. If not, they do not earn a point. n At the end of the program present the user with their score.

+ Sentinels

+ Sentinels n 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. n You don t know how many values the user will be entering. n Given our current toolset we really only have ways to handle this kind of scenario: n 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. n 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 n A sentinel value is a pre-defined value that the user can type in to indicate that they are finished entering data n Example: n >> Enter a test score (type -1 to end): 100 n >> Enter a test score (type -1 to end): 80 n >> Enter a test score (type -1 to end): -1 n >> Your test average is: 90 % n In the example above the value -1 is considered a sentinel -- it indicates to the program that the user is finished entering data. n 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 n Write a program that continually asks the user for an integer n Add the supplied integer to a total variable n When the user enters a 0 value end the program and display the sum for the user

+ Programming Challenge: Weight Loss Log n Write a program that asks the user to enter in a series of weight measurements taken over a period of days n The user can enter as many or as few weight values as they would like. Entering the value 0 should indicate that the user has finished entering data. n Calculate the user s average weight during this period n Also calculate their weight change from the beginning of their weight loss program to the end of the program

+ Repetition Flow Control

+ The break command n The break command is a special Python command that can be used to immediately end a loop. n 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 n Note that when the break command runs it will immediately terminate the current loop, which prevents any commands after the break command from running

+ Trace the Output

+ Prime Number Tester n Write a program that asks the user for an integer n Test to see if the number is prime. A prime number is any number that is evenly divisible by 1 and itself.

+ Simple Data Validation

+ Simple Data Validation n Often we need to ask the user to supply a value in our programs n But as you know you can't always trust the user to supply you with usable data! n 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 n Write a program that asks the user for a positive integer n Do not accept a negative value (or zero) if the user supplies an invalid value you should re-prompt them n Once you have a positive integer you can print that number of stars to the screen. For example: Enter a positive integer: -5 Invalid, try again! Enter a positive integer: 0 Invalid, try again! Enter a positive integer: 5 *****

+ Infinite Loops

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

+ Infinite Loops: An Artistic View n 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) n Here is one vision of an infinite loop: