Fundamentals of Python: From First Programs Through Data Structures

Slides:



Advertisements
Similar presentations
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.
Advertisements

 2002 Prentice Hall. All rights reserved Control Structures 3 control structures –Sequential structure Built into Python –Selection structure The.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
16/27/ :53 PM6/27/ :53 PM6/27/ :53 PMLogic Control Structures Arithmetic Expressions Used to do arithmetic. Operations consist of +,
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Chapter 6 Control Statements Continued
C++ for Engineers and Scientists Third Edition
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6: Repetition  Some additional operators increment and decrement.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements II.
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.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
The University of Texas – Pan American
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
EGR 2261 Unit 4 Control Structures I: Selection  Read Malik, Chapter 4.  Homework #4 and Lab #4 due next week.  Quiz next week.
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Control Structures Week Introduction -Representation of the theory and principles of structured programming. Demonstration of for, while,do…whil.
Programming Logic and Design Fifth Edition, Comprehensive
Computer Science 111 Fundamentals of Programming I The while Loop and Indefinite Loops.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Controlling Execution Programming Right from the Start with Visual Basic.NET 1/e 8.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
Chapter 5 Control Structure (Repetition). Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
Saeed Ghanbartehrani Summer 2015 Lecture Notes #5: Programming Structures IE 212: Computational Methods for Industrial Engineering.
A First Book of ANSI C Fourth Edition Chapter 4 Selection.
CSCI 3328 Object Oriented Programming in C# Chapter 5: C# Control Statement – Part II – Exercises 1 Xiang Lian The University of Texas Rio Grande Valley.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Flow of Control Chapter 3. Outline Branching Statements Java Loop Statements Programming with Loops The Type boolean.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Loops and Simple Functions CS303E: Elements of Computers and Programming.
Chapter 6 Control Statements Continued
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.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition)
Chapter 4 Introduction to Control Statements
September 7, 2004ICP: Chapter 3: Control Structures1 Introduction to Computer Programming Chapter 3: Control Structures Michael Scherger Department of.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition)
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Control Structures (Selection & Repetition)
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Chapter 4 – C Program Control
Topics Introduction to Repetition Structures
JavaScript: Control Statements I
Topics Introduction to Repetition Structures
Outline Altering flow of control Boolean expressions
A First Book of ANSI C Fourth Edition
The University of Texas – Pan American
Iteration: Beyond the Basic PERFORM
Coding Concepts (Basics)
Chapter 3 – Control Structures
Chapter 6: Repetition Statements
Chapter 5: Control Structures II (Repetition)
Topics Introduction to Repetition Structures
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.
Fundamentals of Python: First Programs Second Edition
Presentation transcript:

Fundamentals of Python: From First Programs Through Data Structures Chapter 3 Control Statements

Objectives After completing this chapter, you will be able to: Write a loop to repeat a sequence of actions a fixed number of times Write a loop to traverse the sequence of characters in a string Write a loop that counts down and a loop that counts up Write an entry-controlled loop that halts when a condition becomes false Fundamentals of Python: From First Programs Through Data Structures

Objectives (continued) Use selection statements to make choices in a program Construct appropriate conditions for condition-controlled loops and selection statements Use logical operators to construct compound Boolean expressions Use a selection statement and a break statement to exit a loop that is not entry-controlled Fundamentals of Python: From First Programs Through Data Structures

Definite Iteration: The for Loop Repetition statements (or loops) repeat an action Each repetition of action is known as pass or iteration Two types of loops Those that repeat action a predefined number of times (definite iteration) Those that perform action until program determines it needs to stop (indefinite iteration) Fundamentals of Python: From First Programs Through Data Structures

Executing a Statement a Given Number of Times Python’s for loop is control statement that most easily supports definite iteration The form of this type of loop is: loop header loop body statements in body must be indented and aligned in the same column Fundamentals of Python: From First Programs Through Data Structures

Executing a Statement a Given Number of Times (continued) Example: Loop to compute an exponentiation for a non-negative exponent If the exponent were 0, the loop body would not execute and value of product would remain as 1 Fundamentals of Python: From First Programs Through Data Structures

Count-Controlled Loops Loops that count through a range of numbers To specify a explicit lower bound: Fundamentals of Python: From First Programs Through Data Structures

Count-Controlled Loops (continued) Here is the form of this version of the for loop: Example: bound-delimited summation Fundamentals of Python: From First Programs Through Data Structures

Augmented Assignment Augmented assignment operations: Format: Equivalent to: Fundamentals of Python: From First Programs Through Data Structures

Loop Errors: Off-by-One Error Example: Loop actually counts from 1 through 3 This is not a syntax error, but rather a logic error Fundamentals of Python: From First Programs Through Data Structures

Traversing the Contents of a Data Sequence range returns a list Strings are also sequences of characters Values in a sequence can be visited with a for loop: Example: Fundamentals of Python: From First Programs Through Data Structures

Specifying the Steps in the Range xrange and range expect a third argument that allows you specify a step value Example in a loop: Fundamentals of Python: From First Programs Through Data Structures

Loops That Count Down Example: Fundamentals of Python: From First Programs Through Data Structures

Formatting Text for Output Many data-processing applications require output that has tabular format Field width: Total number of data characters and additional spaces for a datum in a formatted string Fundamentals of Python: From First Programs Through Data Structures

Formatting Text for Output (continued) This version contains format string, format operator %, and single data value to be formatted To format integers, letter d is used instead of s To format sequence of data values: Fundamentals of Python: From First Programs Through Data Structures

Formatting Text for Output (continued) To format data value of type float: where .<precision> is optional Examples: Fundamentals of Python: From First Programs Through Data Structures

Case Study: An Investment Report Request: Write a program that computes an investment report Fundamentals of Python: From First Programs Through Data Structures

Case Study: An Investment Report (continued) Analysis: Fundamentals of Python: From First Programs Through Data Structures

Case Study: An Investment Report (continued) Design: Receive the user’s inputs and initialize data Display the table’s header Compute results for each year and display them Display the totals Fundamentals of Python: From First Programs Through Data Structures

Case Study: An Investment Report (continued) Coding: Fundamentals of Python: From First Programs Through Data Structures

Selection: if and if-else Statements Selection statements allow a computer to make choices Based on a condition Fundamentals of Python: From First Programs Through Data Structures

The Boolean Type, Comparisons, and Boolean Expressions Boolean data type consists of two values: true and false (typically through standard True/False) Example: 4 != 4 evaluates to False Fundamentals of Python: From First Programs Through Data Structures

if-else Statements Also called a two-way selection statement Often used to check inputs for errors: Syntax: Fundamentals of Python: From First Programs Through Data Structures

if-else Statements (continued) must be a Boolean expression Better alternative: Fundamentals of Python: From First Programs Through Data Structures

One-Way Selection Statements Simplest form of selection is the if statement Fundamentals of Python: From First Programs Through Data Structures

Multi-way if Statements A program may be faced with testing conditions that entail more than two alternative courses of action Can be described in code by a multi-way selection statement Fundamentals of Python: From First Programs Through Data Structures

Multi-way if Statements (continued) Syntax: Fundamentals of Python: From First Programs Through Data Structures

Logical Operators and Compound Boolean Expressions Often a course of action must be taken if either of two conditions is true: Below are two approaches Could we use the and logical operator instead? Fundamentals of Python: From First Programs Through Data Structures

Logical Operators and Compound Boolean Expressions (continued) Fundamentals of Python: From First Programs Through Data Structures

Logical Operators and Compound Boolean Expressions (continued) Next example verifies some of the claims made in the previous truth tables: The logical operators are evaluated after comparisons but before the assignment operator not has higher precedence than and and or Fundamentals of Python: From First Programs Through Data Structures

Logical Operators and Compound Boolean Expressions (continued) Fundamentals of Python: From First Programs Through Data Structures

Short-Circuit Evaluation In (A and B), if A is false, then so is the expression, and there is no need to evaluate B In (A or B), if A is true, then so is the expression, and there is no need to evaluate B Short-circuit evaluation: Evaluation stops as soon as possible Short-circuit evaluation can be used to avoid division by zero Fundamentals of Python: From First Programs Through Data Structures

Testing Selection Statements Tips: Make sure that all of the possible branches or alternatives in a selection statement are exercised After testing all of the actions, examine all of the conditions Test conditions that contain compound Boolean expressions using data that produce all of the possible combinations of values of the operands Fundamentals of Python: From First Programs Through Data Structures

Conditional Iteration: The while Loop The while loop can be used to describe conditional iteration Example: A program’s input loop that accepts values until user enters a sentinel that terminates the input Fundamentals of Python: From First Programs Through Data Structures

The Structure and Behavior of a while Loop Conditional iteration requires that condition be tested within loop to determine if it should continue Called continuation condition Improper use may lead to infinite loop while loop is also called entry-control loop Condition is tested at top of loop Statements within loop can execute zero or more times Fundamentals of Python: From First Programs Through Data Structures

The Structure and Behavior of a while Loop (continued) Fundamentals of Python: From First Programs Through Data Structures

The Structure and Behavior of a while Loop (continued) data is the loop control variable Fundamentals of Python: From First Programs Through Data Structures

Count Control with a while Loop Fundamentals of Python: From First Programs Through Data Structures

The while True Loop and the break Statement while loop can be complicated to write correctly Possible to simplify its structure and improve its readability loop’s termination condition causes an exit from the loop a while True loop with a delayed exit Fundamentals of Python: From First Programs Through Data Structures

The while True Loop and the break Statement (continued) Alternative: Use a Boolean variable to control loop Fundamentals of Python: From First Programs Through Data Structures

Random Numbers Programming languages include resources for generating random numbers random module supports several ways to do this randint returns random number from among numbers between two arguments, included Example: A simple guessing game Fundamentals of Python: From First Programs Through Data Structures

Random Numbers (continued) Fundamentals of Python: From First Programs Through Data Structures

Loop Logic, Errors, and Testing Errors to rule out during testing while loop: Incorrectly initialized loop control variable Failure to update this variable correctly within loop Failure to test it correctly in continuation condition To halt loop that appears to hang during testing, type Control+c in terminal window or IDLE shell If loop must run at least once, use a while True loop with delayed examination of termination condition Ensure a break statement to be reached eventually Fundamentals of Python: From First Programs Through Data Structures

Case Study: Approximating Square Roots Request: Write a program that computes square roots Analysis: Design: Use Newton’s square root approximation algorithm: Square root y of a positive number x is the number y such that y2 = x If initial estimate of y is z, a better estimate of y can be obtained by taking the average of z together with x/z Fundamentals of Python: From First Programs Through Data Structures

Case Study: Approximating Square Roots (continued) A quick session with the Python interpreter shows this method of successive approximations in action: Fundamentals of Python: From First Programs Through Data Structures

Case Study: Approximating Square Roots (continued) Design (continued): Algorithm set x to the user’s input value set tolerance to 0.000001 set estimate to 1.0 while True set estimate to (estimate + x / estimate) / 2 set difference to abs(x - estimate ** 2) if difference <= tolerance: break output the estimate Fundamentals of Python: From First Programs Through Data Structures

Case Study: Approximating Square Roots (continued) Implementation (Coding): Fundamentals of Python: From First Programs Through Data Structures

Summary Control statements determine order in which other statements are executed in program Definite iteration is process of executing set of statements fixed, predictable number of times Example: use for loop for loop consists of header and set of statements called body Can be used to implement a count-controlled loop Use xrange to generate sequence of numbers Can traverse and visit the values in any sequence Fundamentals of Python: From First Programs Through Data Structures

Summary (continued) A format string and its operator % allow programmer to format data using field width and precision An off-by-one error occurs when loop does not perform intended number of iterations, there being one too many or one too few Boolean expressions evaluate to True or False Constructed using logical operators: and, or, not Python uses short-circuit evaluation in compound Boolean expressions Selection statements enable program to make choices Fundamentals of Python: From First Programs Through Data Structures

Summary (continued) if-else is a two-way selection statement Conditional iteration is the process of executing a set of statements while a condition is true Use while loop (which is an entry-control loop) A break can be used to exit a loop from its body Any for loop can be converted to an equivalent while loop Infinite loop: Continuation condition never becomes false and no other exit points are provided random.randint returns a random number Fundamentals of Python: From First Programs Through Data Structures