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

Similar documents
AI Programming CS S-02 Python

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

Programming in Python

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

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

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

Python in 10 (50) minutes

Some material adapted from Upenn cmpe391 slides and other sources

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

Accelerating Information Technology Innovation

Accelerating Information Technology Innovation

Large-Scale Networks

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays.

Beyond Blocks: Python Session #1

Senthil Kumaran S

Shell / Python Tutorial. CS279 Autumn 2017 Rishi Bedi

Intro. Scheme Basics. scm> 5 5. scm>

python. a presentation to the Rice University CS Club November 30, 2006 Daniel Sandler

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

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

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

Introduction to Python! Lecture 2

Python for C programmers

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

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

18.1. CS 102 Unit 18. Python. Mark Redekopp

Babu Madhav Institute of Information Technology, UTU 2015

Python: common syntax

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

Key Differences Between Python and Java

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

Part III Appendices 165

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

Pace University. Fundamental Concepts of CS121 1

Java Bytecode (binary file)

STSCI Python Introduction. Class URL

Overview of List Syntax

Course May 18, Advanced Computational Physics. Course Hartmut Ruhl, LMU, Munich. People involved. SP in Python: 3 basic points

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

Download Python from Any version will do for this class

Lists, loops and decisions

Algorithmic Thinking: Computing with Lists

CS 11 python track: lecture 3. n Today: Useful coding idioms

The Pyth Language. Administrivia

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

CS 349 / SE 382 Scripting. Professor Michael Terry March 18, 2009

Play with Python: An intro to Data Science

Introduction to Python. Fang (Cherry) Liu Ph.D. Scien5fic Compu5ng Consultant PACE GATECH

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords

CS Advanced Unix Tools & Scripting

Introduction to Python Part 1. Brian Gregor Research Computing Services Information Services & Technology

CMSC 201 Computer Science I for Majors

CS Summer 2013

Introduction to Bioinformatics

Programming to Python

CSC Web Programming. Introduction to JavaScript

CSC Software I: Utilities and Internals. Programming in Python

Basic Scripting, Syntax, and Data Types in Python. Mteor 227 Fall 2017

ENGR 102 Engineering Lab I - Computation

CIS192 Python Programming

And Parallelism. Parallelism in Prolog. OR Parallelism

COMP519 Web Programming Lecture 17: Python (Part 1) Handouts

Full file at

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

Python. Executive Summary

MUTABLE LISTS AND DICTIONARIES 4

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

CS Programming Languages: Python

CS 61A Discussion 8: Scheme. March 23, 2017

An Introduction to Python

Introduction to Python (All the Basic Stuff)

The Practice of Computing Using PYTHON

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

University of Texas at Arlington, TX, USA

Python Tutorial. CSE 3461: Computer Networking

CIS192: Python Programming

Today: Revisit some objects. Programming Languages. Key data structure: Dictionaries. Using Dictionaries. CSE 130 : Winter 2009

CME 193: Introduction to Scientific Python Lecture 1: Introduction

Introduction to Python for IBM i

Numerical Methods. Centre for Mathematical Sciences Lund University. Spring 2015

Fall 2017 CISC124 9/16/2017

Python a modern scripting PL. Python

1. BASICS OF PYTHON. JHU Physics & Astronomy Python Workshop Lecturer: Mubdi Rahman

Python 1: Intro! Max Dougherty Andrew Schmitt

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

Al al-bayt University Prince Hussein Bin Abdullah College for Information Technology Computer Science Department

STEAM Clown & Productions Copyright 2017 STEAM Clown. Page 1

PYTHON FOR MEDICAL PHYSICISTS. Radiation Oncology Medical Physics Cancer Care Services, Royal Brisbane & Women s Hospital

What is PHP? [1] Figure 1 [1]

Notes from a Short Introductory Lecture on Scala (Based on Programming in Scala, 2nd Ed.)

Introduction to Python

EE 355 Unit 17. Python. Mark Redekopp

Programming. Syntax and Semantics

Basic Python Revision Notes With help from Nitish Mittal

MEIN 50010: Python Data Structures

Advanced Python. Executive Summary, Session 1

Introduction to Python for Plone developers

ENGR 102 Engineering Lab I - Computation

Introduction to Python

Transcription:

CS662-2013S-02 Python 1 02-0: Python Name python comes from Monte Python s Flying Circus Most python references use examples involving spam, parrots (deceased), silly walks, and the like Interpreted language Type in an expression, returns the value Use Python like a calculator Variables don t need to be declared, type is inferred by assigning a value 02-1: Why Python is Cool Easy to use & read Strongly typed, with inferred types First order programming Everything is an object Functions as data Lots of powerful built-in libraries File processing (including URLs) regular expressions GUIs 02-2: Python as Calculator All the standard operators +, -, *,/, %, ** or pow for x y Assigning a value to a variable declares it Type is inferred from value assigned Coercion, just like 3+4.0/2 3/2=? 02-3: Datatypes: Numbers Integers (longs in C) 1, -32, 5612 Long integers (unlimited size) 333422395954556L floats (doubles in C) 1.23 3.1e+15 Octal and Hexadecimal 0143, 0x3aff3 Complex numbers (3.0+5j)

CS662-2013S-02 Python 2 02-4: Datatypes: Strings Denoted with or (equivalent) >>> "spam" spam >>> spam spam Can mix and match, helpful when want or in a string: >>> "The parrot was dead " "The parrot was dead " >>> The parrot was "dead" The parrot was "dead" 02-5: Datatypes: Strings Multi-line strings using >>> """Thisis a multiline string""" This is a\nmultiline string Handy for function comments (more on this in a bit) 02-6: Datatypes: Strings Access individual elements using subscripts: = "HelloThere" [3] l (Note that l is not a character, it is a string of length 1 (no chars in python)) Also use slices: = "HelloThere" [3:5] llo 02-7: Datatypes: Strings Negative indicies in slices count from the end of the string: = "HelloThere" [0:-3] Hello The Think of the indices as pointing between charaters:

CS662-2013S-02 Python 3 +---+---+---+---+---+ S p a m! +---+---+---+---+---+ 0 1 2 3 4 5-5 -4-3 -2-1 02-8: Datatypes: Strings +---+---+---+---+---+ S p a m! +---+---+---+---+---+ 0 1 2 3 4 5-5 -4-3 -2-1 What should this return? = "HelloThere" [-1:-5] 02-9: Datatypes: Strings Can concatinate strings using + (just like java) = "cat" >>> y = "dog" + y catdog Repitition using * >>> "cat"*3 catcatcat 02-10: Datatypes: Strings Strings are immutable = "cat" [1] = "o" ERROR How could we change the elemet at index 1 to an o? 02-11: Datatypes: Strings Strings are immutable = "cat" [1] = "o" ERROR How could we change the elemet at index 1 to an o?

CS662-2013S-02 Python 4 = "cat" = x[0:1]+ o + x[2:3] cot Note that this is a bit wasteful, creates lots of strings (more on how to do string manipulation efficiently in a bit...) 02-12: Datatypes: Lists Items between [ and ], separated by commas are lists Lists are heterogeneous >>> [1, 2, 3, 4] [1, 2, 3, 4] >>> [3, "a", 4.5, 3+4j] [3, a, 4.5, (3+4j)] 02-13: Datatypes: Lists Access elements with [], but lists are mutable (unlike strings) = [1, 2, 3, 4] [2] 3 [2] = 99 [1, 2, 99, 4] 02-14: Datatypes: Lists Python makes list processing very easy = [1, 2, 3].append("car") [1, 2, 3, car ] [2] = [1,2,3,4] [1, 2, [1, 2, 3, 4], car ] 02-15: Datatypes: Lists append(), pop() stacks and queues +, *, append, extend, sort, reverse Use slices (just like strings) = [1,2,3,4] [1:2] = [5,6,7,8] [1, 5, 6, 7, 8, 3, 4]

CS662-2013S-02 Python 5 02-16: Datatypes: Lists List variables store reference: = [1,2,3,4] >>> y = x >>> y[1] = 99 [1, 99, 3, 4] Get a copy by using a slice = [1,2,3,4] >>> y = x[:] >>> y[1] = 99 [1, 99, 3, 4] 02-17:== vs. is Python does a good job of doing what you want == is value-equality, not reference equality is is reference equality = [1,2,3,4] >>> y = [1,2,3,4] >>> z = x == y True is y False is z True 02-18: Tuples Immuable lists use ( ) instead of [ ] () empty tuple (3,2) tuple with two elements What about singletons? (3) is just 3 with parens (3,) is a singleton tuple Otherwise, just like lists 02-19: Tuples

CS662-2013S-02 Python 6 Can use tuples for multiple assignment Handy for swapping (also for returning > 1 value) >>> spam, chips=3,4 >>> spam, chips=chips,spam >>> spam 4 >>> chips 3 02-20: Datatypes: Dictionaries Like hash tables Denoted with{} Accessed like arrays = { } ["cat"]=3 ["dog"]="mouse" [4] = pipsqueak 02-21: Datatypes: Dictionaries Can create a dictionary on a single line: = { "green":"eggs",3:"blindmice"} ["green"] eggs ["newentry"] = "new value" 02-22: Datatypes: Dictionaries Can have nested dictionaries = { "red":3, "complex":{"blue":4}} ["red"] 3 ["complex"] { "blue":4} ["complex]["blue"] 4 02-23: Datatypes: Dictionaries keys method returns a list of keys in a dictionary Add elements to a dictionay by assignment Delete keys using del

CS662-2013S-02 Python 7 = { "red":3, "blue":4} ["green"]=5 { red : 3, blue :4, green :5} >>> del x[ blue ] { red : 3, green :5} 02-24: Multiple Lines No separators (semicolons, etc) No begin/end,{,}to define blocks One statement per line, blocks defined by indentation 02-25: Control Structures: if if <test>: elif: elif: else: 02-26: Control Structures: while while <test>: break, continue just like java/c/c++ 02-27: Booleans in Python False: False (built in, careful of case!) 0, 0.0 (be careful of rounding errors!) () (empty tuple) [] (empty list) {} (empty dictionary) (empty string

CS662-2013S-02 Python 8 True: Anything else 02-28: Booleans in Python a and b a or b if a is true, return b, else return a if a is true, return a, else return b 02-29: and-or trick Can get C-style (test? x : y) test and x or y Examples... When does this break? 02-30: and-or trick Fixing the and-or trick: (test and [x] or [y])[0] What does this do? Do we have the same problem? 02-31: Iterators for loop: >>> lst = [1, 2, 3, 4] >>> for x in lst: print x, 1 2 3 02-32: Iterators Trailing, supresses end-of-line For loop only iterates over a data structure Use range([low],high,[skip]) to iterate over a range Dictionaries: >>> d = { a :1, b :2, c : 3 } >>> for key in d: print key, a b c >>> for key, value in d.iteritems(): print key, value a 1 b 2 c 3

CS662-2013S-02 Python 9 02-33: Membership test with in <data structure> = [1, 2, 3, 4] >>> 2 in x True >>> 5 in x False >>> y = {"car":1, "dog" : 2} >>> "car" in y True >>> 1 in y False 02-34: Functions def <name>(params): <body> Params are all pass-by-value (like C/Java) Return statements work just like C/Java Can use tuples to return> 1 value from a function 02-35: Functions def fib(n): if n <= 2: return 1 else: return fib(n-1) + fib(n-2) def fib2(n): if n <= 2: return(1,1) else: (prev, prevprev) = fib2(n-1) return prev+prevprev, prev 02-36: Function comments def <name>(params): """Comment that describes the function""" <body> Comment is part of the function itself Can be accessed with help(functionname) 02-37: Function parameters Functions can have optional praramters

CS662-2013S-02 Python 10 Can call functions using name of the parameter Can have variable numbers of parameters 02-38: Modules *args, **args Each.py file is a module Can load module.py with import module Module needs to be in a location described by PYTHONPATH enviornment variable PYHONPATH has same syntax as standard PATH Path stored in sys.path, can modify at runtime Need to use module when calling functions from <module> import <symbol> from<module> import * 02-39: Python scripts When you import a module, execute the entire file def s generate functions have any code at all executed when module is run.py files can be scripts (to be run from the commmand line), or modules (imported by other python programs). We can have the same.py file serve 2 purposes The symbol name will have the value main if and only if file is being used as a script 02-40: File Handling if name == " main ": <run main program of script> outfile=file( fname, w ), infile=file( fname, r ) r is default, can be left out S=infile.read() reads entire file into string S S=infile.read(n) reads first n lines into S S=infile.readline() reads one line into S L=infile.readlines() reads while file into a list of strings 02-41: URLs Unless the file is really large, better to read all at once with read() or readlines(), and then process the strings

CS662-2013S-02 Python 11 >>> Import urllib >>> sock = urllib.urlopen("http://cs.usfca.edu/") >>> htmlsource = sock.read() >>> sock.close() >>> print htmlsource <!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>department of Computer Science</title> <link rel="stylesheet" type="text/css" href="/cs.css"> <link rel="shortcut icon" type="image/ico" href="/favicon.ico"> </head>... etc 02-42: Regular Expressions Dive into Python has a good explaination Dive in, and come to me with questions Spend lecture time on regular expressions if there is classwide confusion