Chapter 10 Loops: while and for CSC1310 Fall 2009.

Slides:



Advertisements
Similar presentations
Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.
Advertisements

Python Mini-Course University of Oklahoma Department of Psychology Day 4 – Lesson 15 Tuples 5/02/09 Python Mini-Course: Day 4 – Lesson 15 1.
Introduction to Computing Science and Programming I
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
CS0004: Introduction to Programming Repetition – Do Loops.
I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
Chapter 4 Loops and Character Manipulation Dr. Ali Can Takinacı İstanbul Technical University Faculty of Naval Architecture and Ocean Engineering İstanbul.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Copyright © Texas Education Agency, Computer Programming For Loops.
Guide to Programming with Python
Python Control of Flow.
Fundamentals of Python: From First Programs Through Data Structures
4. Python - Basic Operators
COMPE 111 Introduction to Computer Engineering Programming in Python Atılım University
Chapter 2 Control. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. Repetition, quick overview.
Python – Part 4 Conditionals and Recursion. Modulus Operator Yields the remainder when first operand is divided by the second. >>>remainder=7%3 >>>print.
October 4, 2005ICP: Chapter 4: For Loops, Strings, and Tuples 1 Introduction to Computer Programming Chapter 4: For Loops, Strings, and Tuples Michael.
Lists in Python.
Introduction to Python Basics of the Language. Install Python Find the most recent distribution for your computer at:
Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group.
C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved For Loops October 16, 2013 Slides by Evan Gallagher.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
If statements while loop for loop
Chapter Function Basics CSC1310 Fall Function function (subroutine, procedure)a set of statements different inputs (parameters) outputs In.
Built-in Data Structures in Python An Introduction.
Functions. Built-in functions You’ve used several functions already >>> len("ATGGTCA")‏ 7 >>> abs(-6)‏ 6 >>> float("3.1415")‏ >>>
Introducing Python CS 4320, SPRING Resources We will be following the Python tutorialPython tutorial These notes will cover the following sections.
Ch. 10 For Statement Dr. Bernard Chen Ph.D. University of Central Arkansas Spring 2012.
Chapter 14 Advanced Function Topics CSC1310 Fall 2009.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
Introduction to Loops For Loops. Motivation for Using Loops So far, everything we’ve done in MATLAB, you could probably do by hand: Mathematical operations.
Python 101 Dr. Bernard Chen University of Central Arkansas PyArkansas.
By Austin Laudenslager AN INTRODUCTION TO PYTHON.
More Python!. Lists, Variables with more than one value Variables can point to more than one value at a time. The simplest way to do this is with a List.
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Data Collections CS 127. Lists Lists are ordered sequences of items All programming languages provide a sequence structure similar to a Python list; in.
1 CS 177 Week 6 Recitation Slides Review for Midterm Exam.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Tutorial 9 Iteration. Reminder Assignment 8 is due Wednesday.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
Python Programing: An Introduction to Computer Science
Fourth Quarter.  Involves loops or cycles ◦ Loops: means that a process may be repeated as long as certain condition remains true or remains false. ◦
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Python Files and Lists. Files  Chapter 9 actually introduces you to opening up files for reading  Chapter 14 has more on file I/O  Python can read.
 Python for-statements can be treated the same as for-each loops in Java Syntax: for variable in listOrstring: body statements Example) x = "string"
Python – Part 4 Conditionals and Recursion. Conditional execution If statement if x>0:# CONDITION print (‘x is positive’) Same structure as function definition.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
Lists/Dictionaries. What we are covering Data structure basics Lists Dictionaries Json.
Guide to Programming with Python Chapter Four Strings, and Tuples; for Loops: The Word Jumble Game.
String and Lists Dr. José M. Reyes Álamo.
Chapter 6: Loops.
REPETITION CONTROL STRUCTURE
Python Loops and Iteration
Tuples and Lists.
Warm-up Program Use the same method as your first fortune cookie project and write a program that reads in a string from the user and, at random, will.
CS 115 Lecture 8 Structured Programming; for loops
Section 6: Sequences Chapter 4 and 5.
Topics Introduction to Repetition Structures
Arrays, For loop While loop Do while loop
Arithmetic operations, decisions and looping
String and Lists Dr. José M. Reyes Álamo.
Topics Sequences Introduction to Lists List Slicing
For loops Taken from notes by Dr. Neil Moore
CHAPTER 4: Lists, Tuples and Dictionaries
Topics Sequences Introduction to Lists List Slicing
Selamat Datang di “Programming Essentials in Python”
Presentation transcript:

Chapter 10 Loops: while and for CSC1310 Fall 2009

Loop looping repeat Python has two main looping constructs --- statements that repeat an action over and over while The while loop provides a way to code general loop. for The for statement steps through the items in a sequence object and runs a block of code for each of them.

While Loop General format: while : #start of body #start of body #end of body #end of bodyelse: true It repeatedly executes the body, as long as test expression at the top has true value. false When the test becomes false, control continues after all statements (body) in the while block. If the test is initially false, the body never runs.

while in Action Be careful with. >>>while 1: print “I will run forever!\n” (infinite loop) Python will execute it for ever since is always true (infinite loop). Ctrl-C Ctrl-C stops execution.

“while” in Action Prints all odd numbers between 0 and 10 >>>count=0 >>>while count<=10: if count%2!=0: print count count+=1 # count=count+1 else: print “Done” Iterates through string >>>x=‘while’ >>>while x: print x #print x, - what has changed? x=x[1:]

How to Get Such Output?

break and continue breakjumps out break jumps out of the closest enclosing loop (past the entire loop statement) continue jumps to the top continue jumps to the top of the closest enclosing loop (to the loop’s header line) while : #start of body #start of body if :break if :break if : continue if : continue #end of body #end of body else: #runs only if loop is exited normally

continue in Action >>>count=0 >>>while count<=10: if count%2!=0: print count if count%3==0: print “is divisible by 3” else: print “is not divisible by 3” count+=1 else: print “Done” >>>count=-1 >>>while count<10: count+=1 if count%2==0: continue print count if count%3==0: print “is divisible by 3” else: print “is not divisible by 3” else: print “Done”

break in Action >>>while 1: x=raw_input(“Enter integer\n”) if x.isdigit():break print “It is not a valid input!” else: print “It would not be printed ever!” >>>y=int(x)

break in Action >>>x=y/2 >>>while x>1: if y%x==0: print y,’ has factor ’,x break x-=1 else: print y, “ is prime” y=7 y=8 y=2

for Loop iterator. The for loop is a generic sequence iterator. ANY ordered It can step through the items in ANY ordered sequence object General format: for in : else: When Python runs a for loop, it assigns item in the sequence object to the target “one by one” and executes the loop body for each. For loop body, assignment target refers to the current item in sequence.

for Loop The name for the target is usually a (new) variable. automatically It is automatically set to the next item in sequence when control returns to the top of the loop again. break After the loop, this variable normally still refers to the last item visited unless loop exits with break. for in : #start of body #start of body if :break if :break if : continue if : continue #end of body #end of body else: #runs only if loop is exited normally

for in Action >>>aa=[“spam”, “eggs”, “ham”] >>>for i in aa: print i >>>x=[12,121,34,56,105,33,45,101,110] >>>count=0 >>>for i in x: if i>100:count+=1 if count==3: print “The third number greater than 100 is ”, i break else: print “There is only ”,count,“ numbers>100”

for in Action >>>x=[1,2,3,4] >>>sum=0 >>>for i in x: sum = sum + i >>>product=1 >>>for i in x: product = product * i >>>print sum,” ”,product

Loop Variations There are also situations where you will need to iterate in a more specialized way in the loop operation. For example, what if you need to visit every second or third item in a list? while You could use while with manual indexing. range for (xrange). Or built-in range function to produce list of successively higher integers that could be used as indices in for (xrange).

Counter Loops: range range()for range() is independent from for loop. >>>range(5), range(-2,3), range(2,11,3),range(2,-3,-1) >>>i=1 >>>while i<10: print i i+=2 >>>for i in range(1,10,2): print i >>>x=‘python’; i=0 >>>for item in x:print item, >>>while i<len(x): print x[i],; i+=1 >>>for i in range(len(x)): print x[i]

Nonexhaustive Traversals: range >>>x= [1,2,3,4,5,6,7,8,9] If we only want to compute the sum of the first 5 scores: >>>sum=0 >>>for i in range(5): >>> sum=sum + x[i] If we only need to sum even scores: >>>sum=0 >>>for i in range(0,len(x),2): >>> sum+=x[i] >>>sum=0 >>>for i in x[::2]: sum+=i

Changing List: range >>>x= [1,2,3,4,5,6,7,8,9] >>>for i in range(len(x)): x[i]+=i >>>i=0 >>>while i<len(x): x[i]+=i i+=1

New Type: Tuples Tuples Tuples are collections of any objects that can not be changed. Ordered collection of arbitrary objects Ordered collection of arbitrary objects Accessed by offset Accessed by offset (indexing, slicing) Immutable sequence Immutable sequence Fixed length, heterogeneous, arbitrary nestable Fixed length, heterogeneous, arbitrary nestable Arrays of object references Arrays of object references >>>t1=() >>>t1=() # an empty list >>>t2=(0,) >>>t2=(0,) # not an expression >>>t3=(0, ’Ni’, 1.3, 4); t4=0, ’Ni’, 1.3, 4 >>>t5=(‘0’, (‘abc’, ‘345’))

Basic operations: len(), +, *,in len(t1)t1. len(t1) returns number of items in the tuple t1. >>>len((1, 2, (4,5))) t1+t2 (concatenation)t1 t2 t1+t2 (concatenation) creates a new tuple by joining t1 and t2. >>>(1, 2, 3) + (‘a’, ’b’, ’c’) t1*i (repeat)t1i t1*i (repeat) adds t1 to itself i times. >>> (1, 2)*3 obj1 in t1 (membership)obj1 t1 obj1 in t1 (membership) returns true if obj1 is item of the tuple t1; otherwise, returns false. >>>’a’ in (1,2,’a’) >>>for x in (1, ‘abcd’, (3,4), [4,5, ‘y’]): print x,

Indexing and Slicing Indexing and slicing work the same way as for strings or lists. >>>tuple=(‘aa’,’bb’,1.2, [3,4], (5, 6, 7)) >>>tuple[1], tuple[-1][1], tuple[-2][0] >>>tuple[::-1], tuple[2:] A list inside a tuple could be changed! >>>tuple=(1, [3,4], (5, 6, 7)) >>>tuple[1][1]=‘abc’ >>>tuple[1]=‘abc’

Tuples and Lists list() To sort tuple, convert it to list with list() >>>t=(‘cc’, ’bb’, ’aa’, ’dd’, ‘ee’) >>>tmp=list(t) >>>tmp.sort() >>>print tmp l1tuple(l1) List l1 to tuple: tuple(l1) >>>t=tuple(tmp) >>>print t Lists are for ordered collections that might need to be changed; tuples cover the other cases. Tuples can be used as dictionary keys (lists can not.)

Parallel Traversals: zip and map zip()for zip() allows to use for to visit multiple sequences in parallel. sequences of any type list of tuples It takes one or more sequences of any type, and returns a list of tuples that pair up parallel items taken from its argument. >>>L1=[65,34,56,43] >>>L2=[‘a’, ’b’, ’c’, ’d’] >>>for (x,y) in zip(L1,L2): print y,’ is ’, x truncates shortest sequence zip() truncates result tuples at the length of the shortest sequence >>>zip(‘abcdef’, (1,), [2,3,4,5]) map() None map() does the same as zip(), but pads shorter sequence with None if argument lengths differ. >>>map(None,‘abcdef’, (1,), [2,3,4,5])

Dictionary Construction: zip >>>keys=[65,34,56,43] >>>vals=[‘a’, ’b’, ’c’, ’d’] >>>D2={} >>>for (k,v) in zip(keys,vals): D2[k]=v >>>print D2 dict() Object-construction request with dict() >>>D3=dict(zip(keys,vals))