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

Slides:



Advertisements
Similar presentations
Container Types in Python
Advertisements

Introduction to Python Week 15. Try It Out! Download Python from Any version will do for this class – By and large they are all mutually.
Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.
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.
A Crash Course Python. Python? Isn’t that a snake? Yes, but it is also a...
Tuples. Tuples 1 A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The only difference is that tuples can't be.
Sequences The range function returns a sequence
What is a scripting language? What is Python?
1 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lecture 6: Introduction to Scripting Languages with Python COMP 144 Programming Language.
Introduction to Python. Outline Python IS ……. History Installation Data Structures Flow of Control Functions Modules References.
Intro to Python Paul Martin. History Designed by Guido van Rossum Goal: “Combine remarkable power with very clear syntax” Very popular in science labs.
2/28/2008. >>> Overview Arrays in Python – a.k.a. Lists Ranges are Lists Strings vs. Lists Tuples vs. Lists Map-Reduce Lambda Review: Printing to a file.
1 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lecture 7: Python’s Built-in Types and Basic Statements COMP 144 Programming Language Concepts.
Introduction to Python. What is Python? Interpreted object oriented high level programming language – No compiling or linking neccesary Extensible: add.
Introduction to Python Guido van Rossum Director of PythonLabs at Zope Corporation
January 24, 2006And Now For Something Completely Different 1 “And Now For Something Completely Different” A Quick Tutorial of the Python Programming Language.
Python Crash Course Containers 3 rd year Bachelors V1.0 dd Hour 3.
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.
Python Lists and Such CS 4320, SPRING List Functions len(s) is the length of list s s + t is the concatenation of lists s and t s.append(x) adds.
Numbers, lists and tuples Genome 559: Introduction to Statistical and Computational Genomics Prof. William Stafford Noble.
Built-in Data Structures in Python An Introduction.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 8 Working.
Getting Started with Python: Constructs and Pitfalls Sean Deitz Advanced Programming Seminar September 13, 2013.
10. Python - Lists The list is a most versatile datatype available in Python, which can be written as a list of comma-separated values (items) between.
Lists. The list is a most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
Python I Some material adapted from Upenn cmpe391 slides and other sources.
Lists CS303E: Elements of Computers and Programming.
By Austin Laudenslager AN INTRODUCTION TO PYTHON.
Data Collections CS 127. Lists Lists are ordered sequences of items All programming languages provide a sequence structure similar to a Python list; in.
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 Data Structures By Greg Felber. Lists An ordered group of items Does not need to be the same type – Could put numbers, strings or donkeys in the.
Introduction to Python Sajal Desai. What is Python? Versitile, simple, high level language No linking and compilation “By the way, the language is named.
שיעור 8:tuple, פונקציות 2, sets, dict מבוא ל Python שיעור 5: set, פונקציות, dict.
CSc 120 Introduction to Computer Programing II Adapted from slides by
CSc 120 Introduction to Computer Programing II Adapted from slides by
CSc 120 Introduction to Computer Programing II
Ruth Anderson University of Washington CSE 160 Spring 2015
Section 6: Sequences Chapter 4 and 5.
Lecture 10 Data Collections
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during.
Lists Part 1 Taken from notes by Dr. Neil Moore & Dr. Debby Keen
CISC101 Reminders Quiz 2 this week.
Introduction To Python
Bryan Burlingame 03 October 2018
Bryan Burlingame Halloween 2018
Ruth Anderson University of Washington CSE 160 Spring 2018
Introduction to Python
CS190/295 Programming in Python for Life Sciences: Lecture 6
Data types Numeric types Sequence types float int bool list str
8 – Lists and tuples John R. Woodward.
4. sequence data type Rocky K. C. Chang 16 September 2018
Python I Some material adapted from Upenn cmpe391 slides and other sources.
CSC1018F: Intermediate Python
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Topics Sequences Introduction to Lists List Slicing
Dictionaries Dictionary: object that stores a collection of data
Python I Some material adapted from Upenn cmpe391 slides and other sources.
CS1110 Today: collections.
Topics Sequences Lists Copying Lists Processing Lists
CISC101 Reminders Assignment 2 due today.
CHAPTER 4: Lists, Tuples and Dictionaries
Bryan Burlingame Halloween 2018
Topics Sequences Introduction to Lists List Slicing
And now for something completely different . . .
Python Basics. Topics Features How does Python work Basic Features I/O in Python Operators Control Statements Function/Scope of variables OOP Concepts.
COMPUTER SCIENCE PRESENTATION.
Dictionary.
Introduction to Computer Science
Presentation transcript:

Lecture 7: Python’s Built-in Types and Basic Statements The University of North Carolina at Chapel Hill COMP 144 Programming Language Concepts Spring 2002 Lecture 7: Python’s Built-in Types and Basic Statements Felix Hernandez-Campos Jan 25 COMP 144 Programming Language Concepts Felix Hernandez-Campos

Built-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 list [1, [”2”, 4], 3.0] Nested list COMP 144 Programming Language Concepts Felix Hernandez-Campos

Lists: Accessing Items Syntax: list[index] Indexing from the left starts at 0 E.g. >>> 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#17>", line 1, in ? l[3] = 4 IndexError: list assignment index out of range COMP 144 Programming Language Concepts Felix Hernandez-Campos

Lists: Accessing Items Syntax: list[-index] Indexing from the right starts at -1 E.g. >>> l = [1, ["2", 4], 3.0] >>> l[-1] 3.0 >>> l[-3] 1 >>> l[-4] Traceback (most recent call last): File "<pyshell#29>", line 1, in ? l[-4] IndexError: list index out of range COMP 144 Programming Language Concepts Felix Hernandez-Campos

Lists: Deleting Items Syntax: del list[index] E.g. [1, ['2', 4]] Traceback (most recent call last): File "<pyshell#16>", line 1, in ? del l[2] IndexError: list assignment index out of range COMP 144 Programming Language Concepts Felix Hernandez-Campos

Lists: Length Syntax: len(list) E.g. 3 >>> l = [] COMP 144 Programming Language Concepts Felix Hernandez-Campos

Lists: Constructing Lists Concatenation Syntax: list1 + list2 E.g. >>> 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] COMP 144 Programming Language Concepts Felix Hernandez-Campos

Lists: Constructing Lists Slicing Syntax: list[i:j] E.g. >>> 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] COMP 144 Programming Language Concepts Felix Hernandez-Campos

Lists: Constructing Lists Ranges Syntax: range(start, end, step) Default values for start (0) and step (1) E.g. >>> 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] COMP 144 Programming Language Concepts Felix Hernandez-Campos

Lists: Methods Inserting an item at a given position Syntax: list.insert[index, item] E.g. >>> 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 Syntax: list.append[item] >>> l.append(“end”) [8.3, 1, ['2', 4], 3.0, “end”] COMP 144 Programming Language Concepts Felix Hernandez-Campos

Lists: Methods Sorting Syntax: list.sort() E.g. >>> l.sort() >>> l [1, 2.0, 3, 4] >>> l=["c", "d", "a", "b"] ['a', 'b', 'c', 'd'] COMP 144 Programming Language Concepts Felix Hernandez-Campos

Lists: Methods Reversing Syntax: list.reverse() E.g. >>> l.reverse() >>> l [4, 2.0, 3, 1] COMP 144 Programming Language Concepts Felix Hernandez-Campos

Built-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 COMP 144 Programming Language Concepts Felix Hernandez-Campos

Dictionaries: Accessing items Syntax: list[key] E.g. >>> d = {'item':'tire','price':20.99} >>> d[‘price'] 20.99 >>> d[item] Traceback (most recent call last): File "<pyshell#88>", line 1, in ? d[item] NameError: name 'item' is not defined >>> str = 'item' >>> d[str] 'tire' COMP 144 Programming Language Concepts Felix Hernandez-Campos

Dictionaries: Deleting items Syntax: del list[key] E.g. >>> d = {'item':'tire','price':20.99} >>> del d['item'] >>> d {'price': 20.989999999999998} >>> del d['brand'] Traceback (most recent call last): File "<pyshell#95>", line 1, in ? del d['brand'] KeyError: brand COMP 144 Programming Language Concepts Felix Hernandez-Campos

Dictionaries: Length Syntax: len(list) E.g. >>> d = {'item':'tire','price':20.99} >>> len(d) 2 COMP 144 Programming Language Concepts Felix Hernandez-Campos

Dictionaries: Methods Membership Syntax: list.has_key(key) E.g. >>> l = {'item':'tire','price':20.99} >>> l.has_key('item') 1 >>> l.has_key('brand') COMP 144 Programming Language Concepts Felix Hernandez-Campos

Dictionaries: Methods List of keys Syntax: list.keys() E.g. >>> l = {'item':'tire','price':20.99} >>> l.keys() ['item', 'price'] List of values Syntax: list.values() >>> l.values() ['tire', 20.989999999999998] COMP 144 Programming Language Concepts Felix Hernandez-Campos

Built-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 tuple (!) (1, ”2”, 3.0) Three-element tuple 1, (”2”, 3.0) Nested tuple COMP 144 Programming Language Concepts Felix Hernandez-Campos

Built-in Data Structures: Tuples Commas are used to define tuples Parentheses around tuples are optional E.g. >>> 1,('2',2.0) (1, ('2', 2.0)) >>> (1,('2',2.0)) The one-element list requires a trailing comma >>> 1, (1,) >>> (1)  This is not a tuple but a number 1 COMP 144 Programming Language Concepts Felix Hernandez-Campos

Tuples: Accessing Items Syntax: tuple[index] E.g. >>> 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#110>", line 1, in ? t[3] IndexError: tuple index out of range COMP 144 Programming Language Concepts Felix Hernandez-Campos

Tuples: No Deletion and Length Tuples are immutable Length: Syntax: len(tuple) E.g. >>> t = (1,2,(3,4,5)) >>> len(t) 3 >>> len(t[1]) Traceback (most recent call last): File "<pyshell#117>", line 1, in ? len(t[1]) TypeError: len() of unsized object >>> len(t[2]) COMP 144 Programming Language Concepts Felix Hernandez-Campos

Tuples: Constructing Tuples Concatenation Syntax: tuple1 + tuple2 E.g. >>> 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) COMP 144 Programming Language Concepts Felix Hernandez-Campos

Hierarchy of Numbers Source: Lutz & Ascher, Learning Python, Figure 2-3 COMP 144 Programming Language Concepts Felix Hernandez-Campos

Hierarchy of Built-in Collections Source: Lutz & Ascher, Learning Python, Figure 2-3 COMP 144 Programming Language Concepts Felix Hernandez-Campos

Statements: Assignment Syntax: reference = object or reference E.g. >>> a = 3 >>> a 3 >>> s1, n, m = "hello", 4.0, a >>> s1 'hello' >>> n 4.0 >>> m COMP 144 Programming Language Concepts Felix Hernandez-Campos

Statements: Print Syntax: print object or reference E.g. >>> print "hello", 'again' hello again >>> print 3.0e5 300000.0 >>> name = "python" >>> ver = 2.2 >>> print "This is %(name)s %(ver).3f" % vars() This is python 2.200 COMP 144 Programming Language Concepts Felix Hernandez-Campos

Selection Syntax: Conditional expressions: if test: statements elif test: else: Conditional expressions: >, <, >=, <=, ==, and, or, not COMP 144 Programming Language Concepts Felix Hernandez-Campos

Selection E.g. >>> x = -3 >>> if x < 0: print "negative" elif x == 0: print "zero" else: print "positive" negative COMP 144 Programming Language Concepts Felix Hernandez-Campos

Sequence Iteration Syntax: for var in sequence: statements E.g. >>> sum = 0 >>> for i in range(1,10,2): sum = sum + i >>> sum 25 Membership operator: in COMP 144 Programming Language Concepts Felix Hernandez-Campos

Iteration Syntax: while test: statements E.g. >>> sum = 0 >>> i = 1 >>> while i < 10: sum = sum + i i = i + 2 >>> sum 25 Break and continue are also possible COMP 144 Programming Language Concepts Felix Hernandez-Campos

Functions Syntax: def name(parameters): statements return object E.g. >>> def incr(x): return x + 1 >>> incr(3) 4 COMP 144 Programming Language Concepts Felix Hernandez-Campos

Functions Default values E.g. 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 COMP 144 Programming Language Concepts Felix Hernandez-Campos

Functions Parameter passing by position and by name E.g. def parrot(voltage, state='a stiff', action='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') COMP 144 Programming Language Concepts Felix Hernandez-Campos

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 COMP 144 Programming Language Concepts Felix Hernandez-Campos

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 COMP 144 Programming Language Concepts Felix Hernandez-Campos