Lecture 7: Python s Built-in. in Types and Basic Statements

Similar documents
Data Structures. Lists, Tuples, Sets, Dictionaries

381 INTRODUCTION TO PYTHON SUSHIL J. LOUIS

CS2304: Python for Java Programmers. CS2304: Sequences and Collections

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

Argh! Why another language? Scripting Part 2 (part 1 was shell): Introduction Python. Pythonic style. Python

Lists, Tuples and Dictionaries. HORT Lecture 10 Instructor: Kranthi Varala

OOP and Scripting in Python Advanced Features

MEIN 50010: Python Data Structures

Introduction to Python! Lecture 2

COMP1730/COMP6730 Programming for Scientists. Sequence types, part 2

Programming in Python

Python: Short Overview and Recap

Advanced Python. Executive Summary, Session 1

MUTABLE LISTS AND DICTIONARIES 4

Some material adapted from Upenn cmpe391 slides and other sources

Computer Sciences 368 Scripting for CHTC Day 3: Collections Suggested reading: Learning Python

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

A Little Python Part 2

Python: common syntax

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

History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability

Senthil Kumaran S

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

Python Tutorial. Release Guido van Rossum and the Python development team. December 10, Python Software Foundation

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output

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

Introduction to Python. Data Structures

Python Intro GIS Week 1. Jake K. Carr

Module 04: Lists. Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10. CS116 Fall : Lists

Python a modern scripting PL. Python

Sequences and iteration in Python

CSC326 Python Sequences i. CSC326 Python Sequences

Introduction to Python

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Collections. Lists, Tuples, Sets, Dictionaries

Data Science Python. Anaconda. Python 3.x. Includes ALL major Python data science packages. Sci-kit learn. Pandas.

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Python for Non-programmers

Introduction to Programming in Python (2)

Introduction to Programming in Python (1)

All programs can be represented in terms of sequence, selection and iteration.

Compound Data Types 1

COMP1730/COMP6730 Programming for Scientists. Strings

John Perry. Fall 2009

A Brief Python Tutorial

Why Python? Introduction into Python. Introduction: Remarks. Where to get Python and Learn More?

Computational Integer Programming. Lecture 4: Python. Dr. Ted Ralphs

Python Tutorial. Release Guido van Rossum and the Python development team. October 24, Python Software Foundation

Python Tutorial. Release Guido van Rossum and the Python development team. January 23, Python Software Foundation

Lesson 4: Type Conversion, Mutability, Sequence Indexing. Fundamentals of Text Processing for Linguists Na-Rae Han

CSCE 110 Programming I

Python CIS 218. Oakton Community College CIS 218

A Tutorial Introduction. CS 3270 Chapter 1

Lists How lists are like strings

What is Python? Developed by Guido van Rossum in the early1990s Named after Monty Python Available on eniac Available for download from

CS S-02 Python 1. Most python references use examples involving spam, parrots (deceased), silly walks, and the like

Dictionaries. Looking up English words in the dictionary. Python sequences and collections. Properties of sequences and collections

Adapted from a Tuturial by Guido van Rossum Director of PythonLabs at Zope Corporation. Presented at LinuxWorld - New York City - January 2002

6. Data Types and Dynamic Typing (Cont.)

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

Beyond Blocks: Python Session #1

Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8

Python. Executive Summary

(CC)A-NC 2.5 by Randall Munroe Python

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

ENGR 101 Engineering Design Workshop

Python BASICS. Introduction to Python programming, basic concepts: formatting, naming conventions, variables, etc.

Python Lists. What is not a Collection. A List is a kind of Collection. friends = [ 'Joseph', 'Glenn', 'Sally' ]

Python - Variable Types. John R. Woodward

Python. Jae-Gil Lee Based on the slides by K. Naik, M. Raju, and S. Bhatkar. December 28, Outline

Python Programming: Lecture 2 Data Types

List of squares. Program to generate a list containing squares of n integers starting from 0. list. Example. n = 12

a name refers to an object side effect of assigning composite objects

Teaching London Computing

AI Programming CS S-02 Python

2. A Python Tutorial

Download Python from Any version will do for this class

Practical Workbook Computer Programming

CSCE 110 Programming I

TUPLES AND RECURSIVE LISTS 5

COMP519 Web Programming Lecture 20: Python (Part 4) Handouts

Introduction to Python, Cplex and Gurobi

Here n is a variable name. The value of that variable is 176.

Introduction. Python. Python features. Python philosophy. Python. Python features. Most recent popular (scripting/extension) language

Chapter 8 : Computer Science. Datastructures: Class XII ( As per CBSE Board) lists, stacks, queues. Visit : python.mykvs.in for regular updates

LECTURE 3 Python Basics Part 2

The current topic: Python. Announcements. Python. Python

Accelerating Information Technology Innovation

Chapter 6: List. 6.1 Definition. What we will learn: What you need to know before: Data types Assignments

1. Whetting Your Appetite

Python and Bioinformatics. Pierre Parutto

Introduction to Python

Outline: Data collections (Ch11)

Announcements. Project 2 due next Monday. Next Tuesday is review session; Midterm 1 on Wed., EE 129, 8:00 9:30pm

An Introduction to Programming in Python. Stephen White

CSc 120 Introduction to Computer Programing II Adapted from slides by Dr. Saumya Debray

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

The UOB Python Lectures: Part 1 - Introduction to Python

CIS192: Python Programming Data Types & Comprehensions Harry Smith University of Pennsylvania September 6, 2017 Harry Smith (University of Pennsylvani

Transcription:

The University of North Carolina at Chapel Hill Spring 2002 Lecture 7: Python s Built-in in Types and Basic Statements Jan 25 1 Built-in in Data Structures: Lists A list is an ordered collection of objects Lists can contain any type of object Lists are mutable Examples [] Empty list [1, 2, 3.0] Three-element element list [1, [ 2, 4], 3.0] Nested list 2 1

Lists: Accessing Items Syntax: list[index] Indexing from the left starts at 0 >>> l = [1, ["2", 4], 3.0] >>> l[0] 1 >>> l[2] 3.0 >>> l[1] ['2', 4] >>> l[3] = 4 Traceback (most recent call last): File "<pyshell pyshell#17>", line 1, in? l[3] = 4 IndexError: : list assignment index out of range 3 Lists: Accessing Items Syntax: list[-index] index] Indexing from the right starts at -1 >>> l = [1, ["2", 4], 3.0] >>> l[-1] 3.0 >>> l[-3] 1 >>> l[-4] Traceback (most recent call last): File "<pyshell pyshell#29>", line 1, in? l[-4] IndexError: : list index out of range 4 2

Lists: Deleting Items Syntax: del list[index] >>> l = [1, ["2", 4], 3.0] >>> del l[2] >>> l [1, ['2', 4]] >>> del l[2] Traceback (most recent call last): File "<pyshell pyshell#16>", line 1, in? del l[2] IndexError: : list assignment index out of range 5 Lists: Length Syntax: len(list) >>> l = [1, ["2", 4], 3.0] >>> len(l) 3 >>> l = [] >>> len(l) 0 6 3

Lists: Constructing Lists Concatenation Syntax: list1 + list2 >>> l1 = [1, 2] >>> l1 + [3, 4, 5] [1, 2, 3, 4, 5] Repetition Syntax: list * integer >>> [1, 2] * 5 [1, 2, 1, 2, 1, 2, 1, 2, 1, 2] 7 Lists: Constructing Lists Slicing Syntax: list[i:j] >>> l = [1, ["2", 4], 3.0] >>> l[1:2] [['2', 4]] >>> l[0:-2] [1] >>> l[1:-2] [] >>> l[1:-3] [] >>> l[1:3] = [2, 3] >>> l [1, 2, 3] 8 4

Lists: Constructing Lists Ranges range(start, end, step) Default values for start (0) and step (1) >>> range(1,100,10) [1, 11, 21, 31, 41, 51, 61, 71, 81, 91] >>> range(1,13) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] >>> range(3) [0, 1, 2] 9 Lists: Methods Inserting an item at a given position list.insert[index, item] >>> l = [1, ["2", 4], 3.0] >>> l.insert(0, 8.3) >>> l [8.3, 1, ['2', 4], 3.0] Adding an item at the end of the list list.append[item] >>> l.append( end ) >>> l [8.3, 1, ['2', 4], 3.0, end ] 10 5

Lists: Methods Sorting Syntax: list.sort() >>> l = [1, 3, 2.0, 4] >>> l.sort() >>> l [1, 2.0, 3, 4] >>> l=["c", "d", "a", "b"] >>> l.sort() >>> l ['a', 'b', 'c', 'd'] 11 Lists: Methods Reversing Syntax: list.reverse() >>> l = [1, 3, 2.0, 4] >>> l.reverse() >>> l [4, 2.0, 3, 1] 12 6

Built-in in Data Structures: Dictionaries A dictionary is an unordered collection of objects indexed by keys Any object can be a key Any object can be a item indexed by a key Dictionaries are mutable Examples {} Empty dictionary {'item':'tire','price':20.99} Two-element dictionary 13 Dictionaries: Accessing items Syntax: list[key] >>> d = {'item':'tire','price':20.99} >>> d[ price'] 20.99 >>> d[item] Traceback (most recent call last): File "<pyshell pyshell#88>", line 1, in? d[item] NameError: : name 'item' is not defined >>> str = 'item' >>> d[str str] 'tire' 14 7

Dictionaries: Deleting items Syntax: del list[key] >>> d = {'item':'tire','price':20.99} >>> del d['item'] >>> d {'price': 20.989999999999998} >>> del d['brand'] Traceback (most recent call last): File "<pyshell pyshell#95>", line 1, in? del d['brand'] KeyError: : brand 15 Dictionaries: Length Syntax: len(list) >>> d = {'item':'tire','price':20.99} >>> len(d) 2 16 8

Dictionaries: Methods Membership Syntax: list.has_key(key) >>> l = {'item':'tire','price':20.99} >>> l.has_key('item') 1 >>> l.has_key('brand') 0 17 Dictionaries: Methods List of keys Syntax: list.keys() >>> l = {'item':'tire','price':20.99} >>> l.keys() ['item', 'price'] List of values Syntax: list.values() >>> l.values() ['tire', 20.989999999999998] 18 9

Built-in in Data Structures: Tuples A tuple is an ordered collection of objects Tuples can contain any type of object Tuples are immutable Examples () Empty tuple 1, One-element element tuple (!) (1, 2, 3.0) Three-element element tuple 1, ( 2, 3.0) Nested tuple 19 Built-in in Data Structures: Tuples Commas are used to define tuples Parentheses around tuples are optional >>> 1,('2',2.0) (1, ('2', 2.0)) >>> (1,('2',2.0)) (1, ('2', 2.0)) The one-element element list requires a trailing comma >>> 1, (1,) >>> (1) This is not a tuple but a number 1 20 10

Tuples: Accessing Items Syntax: tuple[index] >>> t = (1, 2, (3, 4, 5)) >>> t[1] 2 >>> t[-1] (3, 4, 5) >>> t[-1][1] 4 >>> t[3] Traceback (most recent call last): File "<pyshell pyshell#110>", line 1, in? t[3] IndexError: : tuple index out of range 21 Tuples: No Deletion and Length No deletion! Tuples are immutable Length: len len(tuple) >>> t = (1,2,(3,4,5)) >>> len(t) 3 >>> len(t[1]) Traceback (most recent call last): File "<pyshell pyshell#117>", line 1, in? len(t[1]) TypeError: len() of unsized object >>> len(t[2]) 3 22 11

Tuples: Constructing Tuples Concatenation Syntax: tuple1 + tuple2 >>> t = (1,2) + (3,) >>> t (1, 2, 3) Repetition Syntax: tuple * integer >>> t * 5 (1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3) 23 Hierarchy of Numbers Source: Lutz & Ascher, Learning Python,, Figure 2-32 24 12

Hierarchy of Built-in in Collections Source: Lutz & Ascher, Learning Python,, Figure 2-32 25 Statements: Assignment Syntax: reference = object or reference >>> a = 3 >>> a 3 >>> s1, n, m = "hello", 4.0, a >>> s1 'hello' >>> n 4.0 >>> m 3 26 13

Statements: Print Syntax: print object or reference >>> print "hello", 'again' hello again >>> print 3.0e5 300000.0 >>> name = "python" >>> ver = 2.2 >>> print "This is %(name)s %(ver ver).3f" % vars() This is python 2.200 27 Selection Syntax: if test: statements elif test: statements else: statements Conditional expressions: >, <, >=, <=, ==, and, or, not 28 14

E.g. Selection >>> x = -3 >>> if x < 0: print "negative" elif x == 0: print "zero" else: print "positive" negative 29 Sequence Iteration Syntax: for var in sequence: statements >>> sum = 0 >>> for i in range(1,10,2): sum = sum + i >>> sum 25 Membership operator: in 30 15

Iteration Syntax: >>> sum = 0 >>> i = 1 >>> while i < 10: sum = sum + i i = i + 2 >>> sum 25 while test: statements Break and continue are also possible 31 Functions Syntax: def name(parameters): statements return object >>> def incr(x): return x + 1 >>> incr(3) 4 32 16

Functions Default values def ask_ok(prompt, retries=4, complaint='yes or no!'): while 1: ok = raw_input(prompt) if ok in ('y', 'ye', 'yes'): return 1 if ok in ('n', 'no', 'nop',, 'nope'): return 0 retries = retries - 1 if retries < 0: raise IOError, 'refusenik user' print complaint 33 Functions Parameter passing by position and by name def parrot(voltage, state='a stiff', action='voom' 'voom', type='norwegian Blue'): print "--" This parrot wouldn't", action, print "if you put", voltage, "Volts through it." print "--" Lovely plumage, the", type print "--" It's", state, "!" >>> parrot(1000) >>> parrot(action = 'VOOOOOM', voltage = 1000000) >>> parrot('a thousand', state = 'pushing up the daisies') >>> parrot('a million', 'bereft of life', 'jump') 34 17

Functions Functions can also have an arbitrary number of parameters Passed as a dictionary or as list of remaining parameters See documentation We will talk about lambda forms and other functional programming techniques After the Haskell lectures 35 Reading Assignment Guido van Rossum and Fred L. Drake, Jr. (ed.), Python tutorial, PythonLabs,, 2001. Read chapters 3 to 5 http://www.python.org/doc/current/tut/tut.html Write some simple programs Eric S. Raymond, Why Python? http://www.linuxjournal.com/article.php?sid=3882 36 18