(CC)A-NC 2.5 by Randall Munroe Python

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

CIS192 Python Programming

Python in 10 (50) minutes

A Brief Introduction to Python for those who know Java. (Last extensive revision: Daniel Moroz, fall 2015)

Basic Python 3 Programming (Theory & Practical)

CS Advanced Unix Tools & Scripting

Webgurukul Programming Language Course

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

Senthil Kumaran S

A Brief Introduction to Python for those who know Java Last extensive revision: Jie Gao, Fall 2018 Previous revisions: Daniel Moroz, Fall 2015

CIS192: Python Programming

6. Data Types and Dynamic Typing (Cont.)

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

Introduction to Python

About Python. Python Duration. Training Objectives. Training Pre - Requisites & Who Should Learn Python

Python Training. Complete Practical & Real-time Trainings. A Unit of SequelGate Innovative Technologies Pvt. Ltd.

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

Python Tutorial. Day 1

Download Python from Any version will do for this class

Babu Madhav Institute of Information Technology, UTU 2015

CSC Software I: Utilities and Internals. Programming in Python

Unit E Step-by-Step: Programming with Python

Introduction to Python

Python Evaluation Rules

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

Python Programming: Lecture 2 Data Types

Table of Contents. Preface... xxi

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

MUTABLE LISTS AND DICTIONARIES 4

Python INTRODUCTION: Understanding the Open source Installation of python in Linux/windows. Understanding Interpreters * ipython.

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

UNIVERSITY OF TORONTO SCARBOROUGH. Fall 2015 EXAMINATIONS. CSC A20H Duration 3 hours. No Aids Allowed

First Programming Language in CS Education The Arguments for Scala

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

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

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

LECTURE 3 Python Basics Part 2

Outline. Simple types in Python Collections Processing collections Strings Tips. 1 On Python language. 2 How to use Python. 3 Syntax of Python

Extending Jython. with SIM, SPARQL and SQL

Key Differences Between Python and Java

Accelerating Information Technology Innovation

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

Princeton University COS 333: Advanced Programming Techniques A Subset of Python 2.7

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

Programming to Python

PYTHON CONTENT NOTE: Almost every task is explained with an example

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017

DSC 201: Data Analysis & Visualization

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

Overview of List Syntax

(IUCAA, Pune) kaustubh[at]iucaa[dot]ernet[dot]in.

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

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

Python a modern scripting PL. Python

CS1 Lecture 3 Jan. 18, 2019

Python 3000 and You. Guido van Rossum PyCon March 14, 2008

Python A Technical Introduction. James Heliotis Rochester Institute of Technology December, 2009

Accelerating Information Technology Innovation


Some material adapted from Upenn cmpe391 slides and other sources

Python Tutorial. CS/CME/BioE/Biophys/BMI 279 Oct. 17, 2017 Rishi Bedi

CS1 Lecture 3 Jan. 22, 2018

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

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

The Practice of Computing Using PYTHON

PYTHON TRAINING COURSE CONTENT

CIS192 Python Programming. Robert Rand. August 27, 2015

Collections. Lists, Tuples, Sets, Dictionaries

Beyond Blocks: Python Session #1

APT Session 2: Python

Introduction to Python

Basic Syntax - First Program 1

Python Interpreted language: work with an evaluator for language expressions (like DrJava, but more flexible) Dynamically typed

Python. Executive Summary

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS

STSCI Python Introduction. Class URL

Part I Basic Concepts 1

Java for Python Programmers. Comparison of Python and Java Constructs Reading: L&C, App B

Python Programming, bridging course 2011

CS 3813/718 Fall Python Programming. Professor Liang Huang.

Basic Python Revision Notes With help from Nitish Mittal

PYTHON. Varun Jain & Senior Software Engineer. Pratap, Mysore Narasimha Raju & TEST AUTOMATION ARCHITECT. CenturyLink Technologies India PVT LTD

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

Course Outline - COMP150. Lectures and Labs

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

Advanced Python. Executive Summary, Session 1

PTN-102 Python programming

Python 3 Quick Reference Card

CSC148 Fall 2017 Ramp Up Session Reference

Course Title: Python + Django for Web Application

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

Question 1. Part (a) Part (b) December 2013 Final Examination Marking Scheme CSC 108 H1F. [13 marks] [4 marks] Consider this program:

Lessons on Python Functions

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

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

Python: Short Overview and Recap

Object-oriented programming in...

Python source materials

[Software Development] Python (Part A) Davide Balzarotti. Eurecom Sophia Antipolis, France

Recap from last Python lecture

Transcription:

http://xkcd.com/353/ (CC)A-NC 2.5 by Randall Munroe Python

Python: Operative Keywords Very high level language Language design is focused on readability Mulit-paradigm Mix of OO, imperative, and functional Strong and dynamic typing (incl. duck typing) Late (dynamic) binding Multiple-inheritance, meta-classes Stuff you ll cover in the OOP course. Python: Operative Keywords Lambda functions and closure Built-in lists, tuples, and maps List comprehension Operator overloading Garbage collected Using the language well == writing pythonic code

Syntax From least to most surprising: Identifiers: [_a-za-z][_a-za-z0-9]*, case-sensitive # comment lines start with # Literal strings 'in single' "or double" quotes Also supports Unicode, Raw, and Multiline strings No char type Semicolons optional No block delimiters ({...}); use indentation instead String Literals Simple: 'in quotes' or "double quotes" Either can contain the other kind, unescaped. Normal escapes:\n \t \r \\etc. Strings can continue\ on next line "שלום" u Unicode: Raw: r"escapes\nare\nignored" Will contain \ and n as part of the string. Can be multiline. """Multi-line strings can be easily created by triple quotes (or triple double-quotes)"""

No Multi-Line Comments # Python only has to-end-of-line comments. # There s no equivalent of /*... */ multi-line comments in C-family languages. """However, any expression with no side-effect can be thought of as a comment. In particular, this includes multi-line strings!""" Quick (and Dirty) No return type def qsort1(lst): No argument type if len(lst) < 2: Built-in list type return lst Block-opening statements (def, if, pivot = lst[0] while...) end with : ; blocks i, left, right, eq = 0, [], [], [] delimited by indent. while i < len(lst): Variables not declared in advance v = lst[i] List access (lst[0]) List literals: [], [v] if v < pivot: Multiple assignment right += [v] if/elif/else elif v > pivot: No i++ left += [v] + used for list concatenation else: eq += [v] i += 1 return qsort1(right) + eq + qsort1(left)

Quick (still Dirty) def qsort2(lst): for statement is very different than the C-style variant. if len(lst) < 2: return lst; pivot = lst[0] left, right, eq = [], [], [] for v in lst: if v < pivot: right += [v] elif v > pivot: left += [v] else: eq += [v] return qsort2(right) + eq + qsort2(left) Slightly Less Quick (but Less Dirty) List comprehension. def qsort3(lst): if len(lst) < 2: return lst; pivot = lst[0] right = [v for v in lst if v < pivot] eq = [v for v in lst if v == pivot] left = [v for v in lst if v > pivot] return qsort3(right) + eq + qsort3(left)

Optional Arguments & Docstring def qsort4(lst, comp = cmp): '''Sorts the input list, using the provided function as a comparator. Default comparison function is cmp.''' if len(lst) < 2: return lst; pivot = lst[0] Docstring is an opening multiline string-comment. Extracted by tools as the documentation for the function. Can you spot the bug in this code? right = [v for v in lst if comp(v, pivot) < 0] eq = [v for v in lst if comp(v, pivot) == 0] left = [v for v in lst if comp(v, pivot) > 0] return qsort4(right) + eq + qsort4(left) Invocation Alternatives qsort4([34,1,32,56,23,1,324,3124,5,4,3,2,46,7]) qsort4([34,1,32,56,23,1,324,3124,5,4,3,2,46,7], lambda x, y: -cmp(x,y)) qsort4(comp = lambda x, y: cmp(y,x), lst = [34,1,32,56,23,1,324,3124,5,4,3,2,46,7])

Help! Help! Try these at the Python prompt: help(5) dir(5) dir([]) cmp. doc print cmp. doc help(cmp) dir(cmp) help(qsort4) Python Files #!/usr/bin/python2.4 # or: #!/usr/bin/python; but things change # between versions. import sys # or: from sys import argv, exit def main: for arg in sys.argv: print arg sys.exit(0) Bang line: specific version recommended import mechanism (not include ) name idiom: even in non-programs, often add main(), with test functionality. if name == " main ": main()

Closures and Lambdas def ratio(a, b): def rat(x): return x / (a+b) print rat(a), rat(b) def makeadder(incr): def add(x): return x + incr return add def makeadderusinglambda(incr): return lambda x: x + incr More About Lists [ can be of, 17, different types, True] range(5) = [0,1,2,3,4] Useful in for loops: for iin range(10) However, not generated lazily... Emulate enums: (apple, orange, kiwi) = range(3) range(2,5) => [2,3,4] Accessing specific elements: lst[i] = the i th element, 0-based lst[-i] = the i th -from-end element, 1-based range(5)[-1] => 4 # last element

Back to Quick (and Dirty) def qsort5(lst): if len(lst) < 2: return lst; pivot = lst[0] def lt(x): return x < pivot def eq(x): return x == pivot def gt(x): return x > pivot right = filter(lt, lst) Local functions, with closure. Filter function: specific variant of list comprehension. Dynamic typing: reuse of eq eq = filter(eq, lst) left = filter(gt, lst) return qsort5(right) + eq + qsort5(left) Slicing list[i:j] = from i(inclusive) to j (exclusive) lst= [ a, b, c, d, e, f, g ] lst[2:5] => [ c, d, e ] list[i:] = from i(inclusive) onwards lst[4:] => [ e, f, g ] list[:j] = from 0 to j (exclusive) lst[:2] = [ a, b ] list[:] = the entire list Slicing also works for strings! therapist [3:] => rapist hello [:-1] => hell

Removing Stuff del list[2] Shifts content after the deleted element del list[5:] del list[-2:] del list[4:9] But also: list[2:2] = [] list[5:] = []... etc. Mutability Lists are mutable; sort(lst) is in-place. But sorted(lst) returns a sorted copy. Assignment of lists is reference assignment. a = range(3); b = a; a[2] =? ; print b[2]? Update by slicing: lst[2:3] = [True, Hello ] lst[4:4] = [ insert, after, 4] lst[4:] = [] Strings are immutable. Cannot assign by slicing. No method modifies a string only returns a modified copy. As in Java.

Tuples Immutable lists of pre-defined size. However, tuple members could be mutable. Some tuple values: (3, hi, True) ( a, b ) ( a,) Dicts Maps in Python are called dicts (short for dictionaries ). Almost any object is a dictionary. Dict literals: {k1:v1, k2:v2,...} Examples: d1 = { name : joe, id : 1234} d2 = {0: a, 1: b, other : z } # non-string keys d3 = {} Keys must be of a hashabletype. Has hash and ( eq and/or cmp ) Hash value never changes Can any of the following serve as a key? (7, 7, 2) [7, 7, 2] (7, 7, { x : 2})

Accessing Dict Content mydict[ key ] = something something = mydict[ key ] if key in mydict: dosomething() oops = mydict[ nosuchkey ] Throws KeyError mydict[ nosuchkey ] = value OK, adds new key del mydict[ somekey ] something = mydict.get( key ) mydict.get( key ) = something Won t compile mydict.get( nosuchkey ) None But note that None could be the value of the key! Iterating Over Dicts for k in d.keys(): print k for k in d: print k for k in d: print d[k] for v in d.values(): print v for e in d.items(): print e Prints (key,value) tuples for k, v in d.items(): print k, :, v

String % Operator String class has a printf-like operator: % str = %d bottles of %s on the wall % (99, beer ) Allows key-based extraction from dicts: str = %(amount) bottles of %(drink) on the wall % { drink : beer, brand : Karlsberg, amount : 99} So, Do You Know Python Now? Spouse of me this night today manufactures the unusual meal in a home. You will join? Guy L.Steele, Jr., in forward to Effective Java, 2e There s a difference between knowing the grammar [syntax], and even the vocabulary [libraries], of a language, to knowing how to use it properly. However, at this stage, you should be able to read, and understand, most non-oo Python code.