For. for loop The for loop in Python is more like a foreach iterative-type loop in a shell scripting language than a traditional for conditional loop.

Slides:



Advertisements
Similar presentations
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Advertisements

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.
Lecture 03 – Sequences of data.  At the end of this lecture, students should be able to:  Define and use functions  Import functions from modules 
An Introduction to Python – Part II Dr. Nancy Warter-Perez.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
CS1061 C Programming Lecture 2: A Few Simple Programs A. O’Riordan, 2004.
 Pearson Education, Inc. All rights reserved Arrays.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
Fundamentals of Python: From First Programs Through Data Structures
4. Python - Basic Operators
Fundamentals of Python: First Programs
Lists in Python.
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.
Handling Lists F. Duveau 16/12/11 Chapter 9.2. Objectives of the session: Tools: Everything will be done with the Python interpreter in the Terminal Learning.
Chap 3 – PHP Quick Start COMP RL Professor Mattos.
1 Python CIS*2450 Advanced Programming Concepts Material for this lecture was developed by Dr. D. Calvert.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Introduction to Programming Workshop 2 PHYS1101 Discovery Skills in Physics Dr. Nigel Dipper Room 125d
CIS 218 Advanced UNIX1 CIS 218 – Advanced UNIX (g)awk.
Input, Output, and Processing
Strings The Basics. Strings can refer to a string variable as one variable or as many different components (characters) string values are delimited by.
Computer Science 101 Introduction to Programming.
>>> # Fibonacci series:... # the sum of two elements defines the next... a, b = 0, 1 >>> while b < 10:... print b... a, b = b, a+b WHILE.
CMSC 202 Arrays. Aug 6, Introduction to Arrays An array is a data structure used to process a collection of data that is all of the same type –An.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
If statements while loop for loop
CMSC 104, Version 9/011 Introduction to C Topics Compilation Using the gcc Compiler The Anatomy of a C Program 104 C Programming Standards and Indentation.
Fundamentals of Python: First Programs
Built-in Data Structures in Python An Introduction.
Chapter 05 (Part III) Control Statements: Part II.
Introducing Python CS 4320, SPRING Resources We will be following the Python tutorialPython tutorial These notes will cover the following sections.
Exam 1 Review Instructor – Gokcen Cilingir Cpt S 111, Sections 6-7 (Sept 19, 2011) Washington State University.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
CS105 Computer Programming PYTHON (based on CS 11 Python track: lecture 1, CALTECH)
Introduction to Strings Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg 1.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
 In computer programming, a loop is a sequence of instruction s that is continually repeated until a certain condition is reached.  PHP Loops :  In.
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
2. WRITING SIMPLE PROGRAMS Rocky K. C. Chang September 10, 2015 (Adapted from John Zelle’s slides)
Python Mini-Course University of Oklahoma Department of Psychology Day 3 – Lesson 11 Using strings and sequences 5/02/09 Python Mini-Course: Day 3 – Lesson.
Printing in Python. Printing Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external.
Chapter 10 Loops: while and for CSC1310 Fall 2009.
I NTRODUCTION TO PYTHON - GETTING STARTED ( CONT )
SEQUENCES:STRINGS,LISTS AND TUPLES. SEQUENCES Are items that are ordered sequentially and accessible via index offsets into its set of elements. Examples:
 Python for-statements can be treated the same as for-each loops in Java Syntax: for variable in listOrstring: body statements Example) x = "string"
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
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.
PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Python: Experiencing IDLE, writing simple programs
Sequences and Indexing
© 2016 Pearson Education, Ltd. All rights reserved.
Python: Control Structures
Miscellaneous Items Loop control, block labels, unless/until, backwards syntax for “if” statements, split, join, substring, length, logical operators,
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during.
Engineering Innovation Center
Introduction to Strings
Introduction to Strings
An Introduction to Python
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
Object Oriented Programming in java
CEV208 Computer Programming
String and Lists Dr. José M. Reyes Álamo.
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Introduction to Strings
Introduction to Strings
For loop Using lists.
Class code for pythonroom.com cchsp2cs
Introduction to Strings
Presentation transcript:

for

for loop The for loop in Python is more like a foreach iterative-type loop in a shell scripting language than a traditional for conditional loop that works like a counter. Python's for takes an iterable (such as a sequence or iterator) and traverses each element once. Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.

General Syntax for iter_var in iterable: suite_to_repeat The for loop traverses through individual elements of an iterable (like a sequence or iterator) and terminates when all the items are exhausted.

Example 1 >>> print 'I like to use the Internet for:' I like to use the Internet for: >>> for item in [' ', 'net-surfing', 'homework', 'chat']:... print item... net-surfing homework chat

continue how we can make Python's for statement act more like a traditional loop, in other words, a numerical counting loop ????? The behavior of a for loop (iterates over a sequence) cannot be change, thus to make it like traditional loop, manipulate the sequence so that it is a list of numbers “iterating over a sequence”

Example-c language #include int main() { int i; for (i = 0; i < 10; i++) { printf ("Hello\n"); printf ("World\n"); } return 0; } Work like counter Python is not working like this!!!!!

Used with Sequence Types Examples - string, list, and tuple types >>> for each Letter in 'Names':... print 'current letter:', each Letter... current letter: N current letter: a current letter: m current letter: e current letter: s

Using for in string For strings, it is easy to iterate over each character: >>> foo = 'abc' >>> for c in foo:... print c... a b c

continue When iterating over a string, the iteration variable will always consist of only single characters (strings of length 1). When seeking characters in a string, more often than not, the programmer will either use in to test for membership, or one of the string module functions or string methods to check for sub strings.

continue iterating through each item is by index offset into the sequence itself: >>> nameList = ['Cathy', "Terry", 'Joe', 'Heather', 'Lucy'] >>> for nameIndex in range(len(nameList)):... print "Liu,", nameList[nameIndex]... Liu, Cathy Liu, Terry Liu, Joe Liu, Heather Liu, Lucy

continue employ the assistance of the len() built-in function, which provides the total number of elements in the tuple as well as the range() built-in function to give us the actual sequence to iterate over. >>> len(nameList) 5 >>> range(len(nameList)) [0, 1, 2, 3, 4]

continue Since the range of numbers may differ, Python provides the range() built-in function to generate such a list. It does exactly what we want, taking a range of numbers and generating a list.

continue To iterate over the indices of a sequence, combine range() and len() as follows: >>> a = [’Mary’, ’had’, ’a’, ’little’, ’lamb’] >>> for i in range(len(a)):... print i, a[i]... 0 Mary 1 had 2 a 3 little 4 lamb

Example : using range and numerical operator >>> for eachnum in range(10):... eachnum=eachnum+2... print eachnum Without this!!!!!!

range () and len() >>> foo = 'abc' >>> for i in range(len(foo)):... print foo[i], '(%d)' % i... a (0) b (1) c (2) index element

Iterating with Item and Index When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function. >>> for i, v in enumerate([’tic’, ’tac’, ’toe’]):... print i, v... 0 tic 1 tac 2 toe

continue >>> nameList = ['Donn', 'Shirley', 'Ben', 'Janice‘, 'David', 'Yen', 'Wendy'] >>> for i, eachLee in enumerate(nameList):... print "%d %s Lee" % (i+1, eachLee)... 1 Donn Lee 2 Shirley Lee 3 Ben Lee 4 Janice Lee 5 David Lee 6 Yen Lee 7 Wendy Lee When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function. >>> for i, v in enumerate([’tic’, ’tac’, ’toe’]):... print i, v... 0 tic 1 tac 2 toe

Example 2 print 'I like to use the Internet for:' for item in [' ', 'net-surfing', 'homework', 'chat']: print item, print put comma to display the items on the same line rather than on separate lines Put one print statement with no arguments to flush our line of output with a terminating NEWLINE by default print statement automatically created newline like example 1

Continue.. Output: I like to use the Internet for: net-surfing homework chat Elements in print statements separated by commas will automatically include a delimiting space between them as they are displayed.

example >>> for eachNum in [0, 1, 2]:... print eachNum ***Within the loop, eachNum contains the integer value that we are displaying and can use it in any numerical calculation that user wish***

example >>> for eachNum in range(3):... print eachNum >>> for eachnum in range(6):... print eachnum

>>> for a in range (3):... a= a*2... print a

List Comprehensions >>> squared = [x ** 2 for x in range(4)] >>> for i in squared:... print i

continue >>> sqdEvens = [x ** 2 for x in range(8) if not x % 2] >>> >>> for i in sqdEvens:... print i

continue To loop over two or more sequences at the same time, the entries can be paired with the zip() function. >>> questions = [’name’, ’quest’, ’favorite color’] >>> answers = [’lancelot’, ’the holy grail’, ’blue’] >>> for q, a in zip(questions, answers):... print ’What is your %s? It is %s.’ % (q, a)... What is your name? It is lancelot. What is your quest? It is the holy grail. What is your favorite color? It is blue.

Use for to read data in file filename = raw_input('Enter file name: ') fobj = open(filename, 'r') for eachLine in fobj: print eachLine, fobj.close()

break and continue Statements, and else Clauses on Loops The break statement, like in C, breaks out of the smallest enclosing for or while loop. The continue statement, also borrowed from C, continues with the next iteration of the loop. Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement. This is exemplified by the following loop, which searches for prime numbers:

example >>> for n in range(2, 10):... for x in range(2, n):... if n % x == 0:... print n, ’equals’, x, ’*’, n/x... break... else:... # loop fell through without finding a factor... print n, ’is a prime number’... 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3