Outline. 1 If Statement. 2 While Statement. 3 For Statement. 4 Nesting. 5 Applications. 6 Other Conditional and Loop Constructs 2 / 19

Similar documents
1.3 Conditionals and Loops

1.3 Conditionals and Loops

CS 112 Introduction to Programming

1.3 Conditionals and Loops. 1.3 Conditionals and Loops. Conditionals and Loops

1.3 Conditionals and Loops

1.3 Conditionals and Loops

1.3 Conditionals and Loops

! Sequence of statements that are actually executed in a program. ! Conditionals and loops: enable us to choreograph control flow.

Algorithms and Data Structures

Lecture 3: Loops. While Loops. While Loops: Powers of Two. While Loops: Newton-Raphson Method

Lecture 3: Loops. While Loops. While Loops: Newton-Raphson Method. While Loops: Powers of Two

Dept. of CSE, IIT KGP

2.3 Flow Control. Flow-Of-Control. If-Else: Leap Year. If-Else

1 Truth. 2 Conditional Statements. Expressions That Can Evaluate to Boolean Values. Williams College Lecture 4 Brent Heeringa, Bill Jannen

HUDSONVILLE HIGH SCHOOL COURSE FRAMEWORK

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

Flow Control: Branches and loops

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Programming Training. Main Points: - Python Statements - Problems with selections.

Built-in Types of Data

Chapter 4 Introduction to Control Statements

Flow Control. So Far: Writing simple statements that get executed one after another.

CSI33 Data Structures

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Statements 2. a operator= b a = a operator b

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

Defining Functions 1 / 21

Python Basics. Lecture and Lab 5 Day Course. Python Basics

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Control Flow: Loop Statements

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Introduction to Computer Programming CSCI-UA 2. Review Midterm Exam 1

3. Conditionals & Loops

CS313D: ADVANCED PROGRAMMING LANGUAGE

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

3. Conditionals & Loops

3. Conditionals and loops

CPSC 3740 Programming Languages University of Lethbridge. Control Structures

Text Input and Conditionals

Concepts Review. 2. A program is the implementation of an algorithm in a particular computer language, like C and C++.

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

UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA C ASSIGNMENTS

LECTURE 5 Control Structures Part 2

Basics of Programming with Python

Repetition, Looping. While Loop

An introduction to Scheme

Object-Oriented Programming

Computer Programming C++ (wg) CCOs

CIS192 Python Programming. Robert Rand. August 27, 2015

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

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Practical Questions CSCA48 Winter 2018 Week 11

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

Announcements. Project 1 will be posted today on webpage and cvs. Due Tuesday

Modules and Clients 1 / 21

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Condition Controlled Loops. Introduction to Programming - Python

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Python for Finance. Control Flow, data structures and first application (part 2) Andras Niedermayer

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Python as a First Programming Language Justin Stevens Giselle Serate Davidson Academy of Nevada. March 6th, 2016

Algorithms and Data Structures

CS 320: Concepts of Programming Languages

ECE 122. Engineering Problem Solving with Java

Chapter 8. Statement-Level Control Structures

Chapter 1. Fundamentals of Higher Order Programming

C++ Programming Lecture 7 Control Structure I (Repetition) Part I

Chapter 4: Control structures. Repetition

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING

Iteration. # a and b are now equal # a and b are no longer equal Multiple assignment

A Look Back at Arithmetic Operators: the Increment and Decrement

CONDITION CONTROLLED LOOPS. Introduction to Programming - Python

Introduction to: Computers & Programming: Review prior to 1 st Midterm

n Group of statements that are executed repeatedly while some condition remains true

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

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

Programming for Engineers Iteration

Scheme G. Sample Test Paper-I. Course Name : Computer Engineering Group Course Code : CO/CD/CM/CW/IF Semester : Second Subject Tile : Programming in C

Chapter 4: Control structures

More on control structures

Introduction to Python

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT

Introduction to Programming Using Java (98-388)

THE IF STATEMENT. The if statement is used to check a condition: if the condition is true, we run a block

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

Hacettepe University Computer Engineering Department. Programming in. BBM103 Introduction to Programming Lab 1 Week 4. Fall 2018

Principles of Computer Science

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17

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

Accelerating Information Technology Innovation

Variable and Data Type I

Chapter 1 INTRODUCTION. SYS-ED/ Computer Education Techniques, Inc.

Decaf Language Reference Manual

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Transcription:

Control Flow 1 / 19

Outline 1 If Statement 2 While Statement 3 For Statement 4 Nesting 5 Applications 6 Other Conditional and Loop Constructs 2 / 19

If Statement Most computations require different actions for different inputs and one way to express these differences in Python is using the if statement if < boolean expression >:... elif < boolean expression >:... elif < boolean expression >:...... else :... 3 / 19

If Statement flip.py: Simulate a coin flip by writing Heads or Tails to standard output. random if random. randrange (0, 2) == 0:. writeln ( Heads ) else :. writeln ( Tails ) $ python3 flip. py Tails $ python3 flip. py Heads $ python3 flip. py Heads 4 / 19

While Statement Many computations are inherently repetitive and the basic Python construct for handling such computations is the while statement while < boolean expression >:... 5 / 19

While Statement tenhellos.py: Write 10 Hellos to standard output.. writeln ( 1st Hello ). writeln ( 2nd Hello ). writeln ( 3rd Hello ) i = 4 while i <= 10:. writeln ( str (i) + th Hello ) i = i + 1 $ python3 tenhellos. py 1st Hello 2nd Hello 3rd Hello 4th Hello 5th Hello 6th Hello 7th Hello 8th Hello 9th Hello 10 th Hello Variable trace i output ---------------- 4 4th hello 5 5th hello 6 6th hello 7 7th hello 8 8th hello 9 9th hello 10 10 th hello 11 6 / 19

While Statement powersoftwo.py: Accept positive integer n as a command-line argument. Write to standard output a table showing the first n powers of two. sys n = int ( sys. argv [1]) power = 1 i = 0 while i <= n:. writeln ( str (i) + + str ( power )) power = 2 * power i = i + 1 Variable trace (n = 8) $ python3 powersoftwo. py 8 0 1 1 2 2 4 3 8 4 16 5 32 6 64 7 128 8 256 power i output -------------------- 1 0 0 1 2 1 1 2 4 2 2 4 8 3 3 8 16 4 4 16 32 5 5 32 64 6 6 64 128 7 7 128 256 8 8 256 512 9 7 / 19

While Statement Modifying a variable is something that we do so often that Python provides shorthand notations for the purpose The most common practice is to abbreviate an assignment statement of the form i = i + 1 with the shorthand notation i += 1 The same notation works for other binary operators, including -, *, and / The scope of a variable is part of the program where it is defined, ie, statements that follow the definition in the same block (marked by indentation level) 8 / 19

For Statement The for statement provides a more compact notation for carrying out repeated computations for < variable > in < iterable object >:... The most commonly used iterable objects are the lists containing arithmetic progressions of integers, returned by the built-in function range() The call range(start, stop[, step]) returns a list starting at start, ending just before stop, and in increments (or decrements) given by the optional step argument, which defaults to 1 The call range(stop) is shorthand for range(0, stop) For example range (8, 0, -2) = [8, 6, 4, 2] range (3, 9) = [3, 4, 5, 6, 7, 8] range (5) = [0, 1, 2, 3, 4] 9 / 19

For Statement The tenhellos.py program can be written using a for statement as follows. writeln ( 1st Hello ). writeln ( 2nd Hello ). writeln ( 3rd Hello ) for i in range (4, 11):. writeln ( str (i) + th Hello ) Strings are iterable objects, so its characters can be enumerated using a for loop For example, the following code for c in AGCT :. writeln (c) produces the output A G C T 10 / 19

Nesting The if, while, and for statements, collectively called control-flow statements, have the same status as assignment statements or any other statements in Python As a result, we can use a control-flow statement whenever a statement is called for In particular, we can nest one or more of the control-flow statements in the body of another 11 / 19

Nesting divisorpattern.py: Accept integer command-line argument n. Write to standard output an n-by-n table with an asterisk in row i and column j if either i divides j or j divides i. sys n = int ( sys. argv [1]) for i in range (1, n + 1): for j in range (1, n + 1): if ( i % j == 0) or ( j % i == 0):. write ( * ) else :. write ( ). writeln (i) Variable trace (n = 3) $ python3 divisorpattern. py 3 * * * 1 * * 2 * * 3 i j output ---------------- 1 1 * 1 2 * 1 3 * 1\n 2 1 * 2 2 * 2 3 2\n 3 1 * 3 2 3 3 * 3\n 12 / 19

Nesting $ python3 divisorpattern. py 10 * * * * * * * * * * 1 * * * * * * 2 * * * * 3 * * * * 4 * * * 5 * * * * 6 * * 7 * * * * 8 * * * 9 * * * * 10 13 / 19

Applications harmonic.py: Accept integer n as a command-line argument. Write to standard output the nth harmonic number Hn, computed as Hn = 1 + 1/2 + 1/3 + + 1/n. Note that Hn ln(n) + 0.57721 for large n. sys n = int ( sys. argv [1]) total = 0.0 for i in range (1, n + 1): total += 1 / i. writeln ( total ) $ python3 harmonic. py 2 1.5 $ python3 harmonic. py 10 2.92896825397 $ python3 harmonic. py 10000 9.78760603604 14 / 19

Applications sqrt.py: Accept a float c as a command-line argument. Write to standard output the square root of c to 15 decimal places of accuracy, calculated using Newton s method. sys EPSILON = 1e -15 c = float ( sys. argv [1]) t = c while abs (1 - c / t ** 2) > EPSILON : t = (c / t + t) / 2. writeln (t) $ python3 sqrt. py 2.0 1.41421356237 $ python3 sqrt. py 2544545 1595.16300108 15 / 19

Applications binary.py: Accept integer n as a command-line argument. Write the binary representation of n to standard output. sys 16 8 4 2 1 n = int ( sys. argv [1]) v = 1 while v <= n // 2: v *= 2 while v > 0: if n < v:. write (0) else :. write (1) n -= v v //= 2. writeln () 2 1 16 19 1 0 0 1 1 $ python3 binary. py 19 10011 $ python3 binary. py 255 11111111 $ python3 binary. py 512 1000000000 16 / 19

Applications gambler.py: Accept integer command-line arguments stake, goal, and trials. Run trials experiments that start with stake dollars and terminate on 0 dollars or goal. Write to standard output the percentage of wins and the average number of bets per experiment, which can be calculated as 100 stake/goal and stake (goal stake), respectively. random sys stake = int ( sys. argv [1]) goal = int ( sys. argv [2]) trials = int ( sys. argv [3]) bets = 0 wins = 0 for t in range ( trials ): cash = stake while cash > 0 and cash < goal : bets += 1 if random. randrange (0, 2) == 0: cash += 1 else : cash -= 1 if cash == goal : wins += 1. writeln ( str (100 * wins // trials ) + % wins ). writeln ( Avg # bets : + str ( bets // trials )) goal stake 0 goal stake 0 win loss $ python3 gambler. py 50 250 100 24% wins Avg # bets : 12548 17 / 19

Applications factors.py: Accept integer n as a command-line argument. Write to standard output the prime factors of n. sys n = int ( sys. argv [1]) factor = 2 while factor * factor <= n: while n % factor == 0: n //= factor. write ( str ( factor ) + ) factor += 1 if n > 1:. write (n). writeln () $ python3 factors. py 3757208 2 2 2 7 13 13 397 $ python3 factors.py 287994837222311 17 1739347 9739789 18 / 19

Other Conditional and Loop Constructs The conditional expression supports an alternate form of an if-else statement < expression > if < boolean expression > else < expression > For example, the following code assigns Heads or Tails to the variable flip, each with probability 1/2 flip = Heads if random. random () < 0.5 else Tails The break statement immediately exits a loop without letting it to run to completion For example, the following code tests and prints if a number N is prime or not i = 2 while i <= N // i: if N % i == 0: break i += 1. writeln ( str ( N) + ( is if i > N // i else is not ) + prime ) The continue statement skips to next iteration of a loop For example, the following code iterates over the characters in the English alphabet and prints only the consonants for c in abcdefghijklmnopqrstuvwxyz : if c == a or c == e or c == i or c == o or c == u : continue. writeln (c) 19 / 19