Introduction to: Computers & Programming:

Similar documents
Flow Control: Branches and loops

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

Introduction to: Computers & Programming: Strings and Other Sequences

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

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

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

ECE 122. Engineering Problem Solving with Java

Introduction to: Computers & Programming Defining Identifiers: Objects with Names

Introduction. C provides two styles of flow control:

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

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

You submitted this homework on Mon 23 Sep :59 PM PDT (UTC -0700). You got a score of out of You can attempt again, if you'd like.

Chapter 5 Conditional and Iterative Statements (Part-II) To carry out repetitive task, python provides following iterative/looping statements:

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts

Control structure: Repetition - Part 3

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

LOOPS. Repetition using the while statement

Introduction to: Computers & Programming: Strings and Other Sequences

Midterm 1 Review. Important control structures. Important things to review. Functions Loops Conditionals

CS1 Lecture 11 Feb. 9, 2018

Fundamentals of Programming (Python) Control Structures. Sina Sajadmanesh Sharif University of Technology Fall 2017

You submitted this homework on Thu 19 Sep :28 AM EET (UTC +0200). You got a score of out of

Comp 150 Exam 2 Overview.

Introduction to: Computers & Programming: Review prior to 2 nd Midterm

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python

Python I. Some material adapted from Upenn cmpe391 slides and other sources

Emil Sekerinski, McMaster University, Winter Term 16/17 COMP SCI 1MD3 Introduction to Programming

Chapter 4 The If Then Statement

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

REPETITION CONTROL STRUCTURE LOGO

Test #2 October 8, 2015

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Control structure: Repetition - Part 2

CSI33 Data Structures

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

Chapter 5 Conditional and Iterative Statements. Statement are the instructions given to the computer to perform any kind of action.

Lab 5 - Repetition. September 26, 2018

Condition Controlled Loops. Introduction to Programming - Python

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

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

SOFT 161. Class Meeting 1.6

PRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops

Chapter 2: Functions and Control Structures

Repetition Algorithms

Conditional Expressions and Decision Statements

Selection statements. CSE 1310 Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington

ECS 10 Concepts of Computation Example Final Problems

Individual research task. You should all have completed the research task set last week. Please make sure you hand it in today.

Control Flow: Loop Statements

Loops. Upsorn Praphamontripong. CS 1110/CS 1111 Introduction to Programming Spring 2018

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

Algorithms and Data Structures

3/12/2018. Structures. Programming in C++ Sequential Branching Repeating. Loops (Repetition)

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Programming for Experimental Research. Flow Control

Introduction to C Programming

Conditionals and Recursion. Python Part 4

Control Structures 1 / 17

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

Accelerating Information Technology Innovation

The second statement selects character number 1 from and assigns it to.

Chapter 1: Problem Solving Skills Introduction to Programming GENG 200

Part 1 (80 points) Multiple Choice Questions (20 questions * 4 points per question = 80 points)

ENGR 101 Engineering Design Workshop

Why Is Repetition Needed?

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

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

DM536 Introduction to Programming. Peter Schneider-Kamp.

Repetition Structures

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

PYTHON DATA SCIENCE TOOLBOX II. List comprehensions

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

Control and Environments Fall 2017 Discussion 1: August 30, Control. If statements. Boolean Operators

CS 61A Control and Environments Spring 2018 Discussion 1: January 24, Control. If statements. Boolean Operators

Programming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029

CONTROL AND ENVIRONMENTS 1

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

Score score < score < score < 65 Score < 50

Loop structures and booleans

Looping. Arizona State University 1

Conditionals & Control Flow

CSCI 1101B. While Loops

CPSC 3740 Programming Languages University of Lethbridge. Control Structures

CS 115 Lecture 13. Strings. Neil Moore. Department of Computer Science University of Kentucky Lexington, Kentucky

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

YOLOP Language Reference Manual

Introduction to: Computers & Programming: Exception Handling

Chapter 8. Statement-Level Control Structures

Basics of Programming with Python

An Introduction to Python

Control Structures. CIS 118 Intro to LINUX

Introduction to: Computers & Programming Defining Identifiers: Objects with Names

Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.5. for loop and do-while loop

CMSC201 Computer Science I for Majors

Chapter 8 Statement-Level Control Structures

Lecture #15: Generic Functions and Expressivity. Last modified: Wed Mar 1 15:51: CS61A: Lecture #16 1

CPSC 217 Midterm (Python 3 version)

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

Flow Control. CSC215 Lecture

Common Loop Algorithms 9/21/16 42

Transcription:

Introduction to: Computers & Programming: Adam Meyers New York University

Outline What is a Loop? While Loops For Loops Examples Nested Loops

Loops are control structures A block of code repeats What is a Loop? The extent of the repetition is usually limited in some way Two kinds of while loops The evaluation of a boolean expression determines when the repetition stops Changes in values of variables lead to different evaluations of the boolean expression on each repetition When the expression is evaluated as False, the loop halts If the expression can never evaluate as False, the loop is endless for loops The length of a sequence determines how many times the body executes A sequence is an object that is made up of other objects (arranged in an order), e.g., a string is a sequence of characters: duck = d, u, c, k. The loop uses one member of the sequence at a time, ending with the last one

An Endless Loop: keeping time Example def endless_timer (): import time now = 0 while True: time.sleep(1) now = now + 1 print(now) This loop will keep counting seconds until stopped with a Control-C

What is a while Loop? A while loop consists of: The word while A boolean expression (True on the last slide) A colon : The body: an indented block of instructions The body of the loop repeats until the boolean expression is False The loop on the previous slide is endless because True does not change in value And True does not equal False. Any program can be stopped using Control-C

A normal while Loop Normal loops iterate until some condition is True (endless loops are unusual) def timer (total_seconds): import time now = 0 while (now < total_seconds): time.sleep(1) now = now + 1 print(now) If we call timer with 5 as an argument The variable now is initialized to 0 The loop iterates 5 times Each time: a second passes, 1 is added to now and now is printed In this way, 1 to 5 is printed over 5 seconds How many times would a loop beginning while False: repeat?

Loops for Guiding User Input def get_yes_or_no_answer(): ## User must respond yes or no output = 'initial_input' # initialize the variable output output = output.lower() # convert to lowercase while(not ((output == 'yes') or (output == 'no'))): if output!= 'initial_input': print('invalid Input!') output=(input( Please respond: 'yes' or 'no')) output = output.lower() # convert to lowercase if output=='yes': return(true) elif output=='no': return(false) def get_integer_from_user(): ## User must respond with a single digit output = 'initial_input' # initialize variable output while (not (output in '0123456789')): if output!= 'initial_input': print('invalid Input!') output = input('choose an integer. ') return(output)

A sample for loop This function simulates a 60 second timer def one_minute_timer (): print(0) for second in range(60): time.sleep(1) print(second + 1) The function prints 0, then enters a for loop The loop iterates through a list of numbers from 0 to 59 The variable second is assigned that number as a value The system waits one second The system prints second + 1

The range function range takes three arguments: START: An optional 1st argument (starts at START) MAXIMUM: A required 2nd argument (ends before MAXIMUM) INCREMENT: An optional 3rd argument When left out, START defaults to 0 When left out, INCREMENT defaults to 1 creates a sequence of numbers from START to MAXIMUM-1 such that consecutive items in the sequence differ by INCREMENT Examples: range(5) [0,1,2,3,4] range(2,5) [2,3,4] range(0,10,2) --> [0,2,4,6,8] range(10,2,-2) [10,8,6,4] if negative increment, numbers count down range still ends at 1 less than max

Looping Through a Range def factorial(number): total = 1 ## example of accumulator variable for num in range(1,number+1): total=total*num return(total)

Looping through String def accum_spaces_and_add_stars(word): output = '* ' ## also an accummulator variable for letter in string: output = output+letter+' ' output = output+'*' return(output)

The for loop The first line for variable in sequence: for and in are keywords variable can be any legal variable name sequence is an ordered set of items Python sequences includes data types like: range, list, string, The body of the loop repeats once for each item in the sequence On each iteration, the variable is bound to the next item in the sequence Examples: for character in 'multi-character': print(character) for number in range(5): print(number)

Looping Through a String Using a for loop def for_string_loop (string): for letter in string: print(letter) for_string_loop('downward') Using a while loop def while_string_loop (string): position = 0 ## counter while(position < len(string)): print(string[position]) position = 1 + position

Lengths and elements of Sequences The function len returns a sequence's length The number of characters len('downward') The number of integers in a range len(range(60)) Elements in a sequence can be identified by their position, beginning with 0 and ending in one less than the length. 'Downward'[0], range(5,10)[0] 'Downward'[7], range(5,10)[4] 'Downward'[8], range(5,10)[5] --- these are errors The number in square brackets refers positions around items in sequences Example: 'cat' consists of 3 letters starts at position 0 and ends at position 3 0 c 1 a 2 t 3 cat[2] 't' --- because 't' starts at position 2

for loops vs. while loops With some code modification, it is always possible to replace a for loop with a while loop, but not the other way around for loops are used for situations where you know the number of iterations ahead of time e.g., looping through sequences There is no significant efficiency difference The difference relates to ease in which humans can read/write code

Simple Examples of Nested Loops What do you expect to be returned from the following loop within a loop? def print_1_to_4_by_a_to_d(): for number in [1,2,3,4]: for letter in 'abcd': print(number,letter) Function based on above example def print_two_item_combinations(seq1,seq2): for item1 in seq1: for item2 in seq2: print(item1,item2) Notice that embedded loops are indented under higher loops

Example:Printing a Multiplication table def multiplication_table (high_num): for num1 in range(1, 1+high_num): for num2 in range(1, 1+high_num): print(num1,'x',num2, '=', num1*num2) How does this work?

break: causes a loop to exit keep counting while num is less than 10 def count_to_ten_with_while(): num = 0 while num < 10: num = num + 1 print(num) Equivalently, break out of loop when num equals 10 def count_to_ten_with_break(): num = 0 while True: if num >= 10: break num = num+1 print(num)

pass does nothing pass and continue def print_every_other_number(max): for num in range(1,max+1): if num%2==0: else: pass print(num) continue skips to next iteration of loop def skip_every_fifth_number(max): for num in range(1,max+1): if num%5==0: continue print(num)

A Few More Details About print print takes 2 optional arguments: sep='*' prints asterisk between arguments Default: prints spaces between arguments end='$' prints dollar sign at the end of line Default prints newline character at end of line def test1(): print('new','york','university',sep='*',end='$') print('blah','blah','blah',sep='*',end='$') def test2(): print('new','york','university') print('blah','blah','blah')

Example: Drawing an asterisk triangle def draw_n_asterisks(n): for current_length in range(n): print('*',end='') Printing nothing (the empty string) at the end of each line, instead of the newline character def asterisk_triangle(base_size): for current_length in range(1,base_size+1): draw_n_asterisks(current_length) print()

Drawing an asterisk triangle 2 Nested Loops a single function def asterisk_triangle2(base_size): for current_length in range(1,base_size+1): for n in range(current_length): print('*',end='') print() Python indicates depth of nesting via indentation Suppose the last line was indented once

Sample Problem for Class Write a function that: Takes three arguments: base_size repetitions hour_glass_or_diamond This function makes a pattern of asterisks that repeats the number of times indicates by repetitions Each cycle consists of two triangles, one the upside down version of each other, both of which have a base of size base_size If hour_glass_or_diamond is in the 'hour glass' setting, the function draws an upside down triangle and then a right side up triangle If hour_glass_or_diamond is in the 'diamond' setting, the function draws the right side up triangle first and the upside down one second

Summary Loops provide a way to repeat blocks of instructions While loops are the most general They require a condition for exiting the loop If the condition is never false, the loop is endless For loops provide a simple way of repeating a block once for each element in a sequence or a fixed number of times A For loop can always be replaced by an equivalent While loop It is often useful to have nested loops (loops within loops)

Homework Go to HW part of website: http://cs.nyu.edu/courses/fall17/-007/#homework%20schedule http://cs.nyu.edu/courses/fall17/-011/#homework%20schedule See Homework due October 4 Modules/readings before class Written assignment at midnight