Python. Executive Summary

Similar documents
Advanced Python. Executive Summary, Session 1

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

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

Python I. 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:

Python Intro GIS Week 1. Jake K. Carr

Babu Madhav Institute of Information Technology, UTU 2015

LECTURE 3 Python Basics Part 2

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

Beyond Blocks: Python Session #1

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

18.1. CS 102 Unit 18. Python. Mark Redekopp

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

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

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University

Introduction to Python for Plone developers

Python. Karin Lagesen.

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

Exercise: The basics - variables and types

Introduction to Python

Exceptions and File I/O

Python Evaluation Rules

The Practice of Computing Using PYTHON

Control Structures 1 / 17

Sequences and iteration in Python

DaMPL. Language Reference Manual. Henrique Grando

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

Variable and Data Type I

TEXT MINING INTRO TO PYTHON

EE 355 Unit 17. Python. Mark Redekopp

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

Try and Error. Python debugging and beautification

Jarek Szlichta

Coral Programming Language Reference Manual

Exercise: The basics - variables and types

Introduction to Python Code Quality

PYTHON FOR KIDS A Pl ayfu l I ntrodu ctio n to Prog r am m i ng J a s o n R. B r i g g s

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

Python debugging and beautification

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

egrapher Language Reference Manual

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

Lists, loops and decisions

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

STSCI Python Introduction. Class URL

Strings. Upsorn Praphamontripong. Note: for reference when we practice loop. We ll discuss Strings in detail after Spring break

6. Data Types and Dynamic Typing (Cont.)

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

Python Tutorial. Day 1

University of Texas at Arlington, TX, USA

Programming in Python 3

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

Introduction to Python! Lecture 2

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

Part IV. More on Python. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26,

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

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

At full speed with Python

Overview of List Syntax

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

SCoLang - Language Reference Manual

Flow Control: Branches and loops

Duration: Six Weeks Faculty : Mr Sai Kumar, Having 10+ Yrs Experience in IT

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

Python in 10 (50) minutes

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT

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

Variable and Data Type I

Types, lists & functions

x = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

Course Introduction and Python Basics

ENGR 101 Engineering Design Workshop

IE 555 Programming for Analytics

VLC : Language Reference Manual

Python and Bioinformatics. Pierre Parutto

Introduction to Python Part I

Basic Python Revision Notes With help from Nitish Mittal

COMP 204: Sets, Commenting & Exceptions

Python source materials

CIS192: Python Programming

Programming to Python

MEIN 50010: Python Flow Control

String Processing CS 1111 Introduction to Programming Fall 2018

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Constants. Variables, Expressions, and Statements. Variables. x = 12.2 y = 14 x = 100. Chapter

Lecture #15: Generic Functions and Expressivity. Last modified: Wed Mar 1 15:51: CS61A: Lecture #16 1

Chapter 8: More About Strings. COSC 1436, Summer 2018 Dr. Zhang 7/10/2018

Abstract Data Types. David E. Culler CS8 Computational Structures in Data Science Lecture 7 March 7, 2016

UNIVERSITÀ DI PADOVA. < 2014 March >

Collections. Lists, Tuples, Sets, Dictionaries

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

An Introduction to Python

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS

Python 1: Intro! Max Dougherty Andrew Schmitt

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

Exception Handling. Genome 559

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

CS Programming Languages: Python

1 Classes. 2 Exceptions. 3 Using Other Code. 4 Problems. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, / 19

Transcription:

Python Executive Summary DEFINITIONS OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or response to operators). Everything in Python is an object. "atomic" data: integer, float, string, boolean, None "container" data: list, tuple, set, dict "code" objects: functions, methods, classes "custom" objects: defined by Python module authors (including you) VARIABLE: an object bound (assigned to) a name. var = 10 myxx = "hello!" def myfunc(): print('ok!') # int object # str object # function object Initialization of a variable means that the object is being stored in memory for later use during the run of the program. Re-initialization means that the name has been bound to a new object, and is now unbound from the prior object. All initializations create a new binding between a name and an object. STATEMENTS simple statements: assignment (with =): var = 10 augmented assignment (+=, -=, etc.): var += 5 del (unbind a variable or remove a dict key/value): del var break (drop out of a loop): break continue (jump to next iteration of a loop): continue import (import a Python module): import random ternary: an if/else in a simple statement var = 0 if xx < 0 else xx conditional assignment: if/else assignment var = xx or 100 compound statements: if, elif, else: if var > 5: and, or (for compound tests): if var > 5 and var < 10: not (testing negative condition): if not var > 5: while loop: while var < 100:

for: iterate through an iterable (container or file): for item in mylist: try: test code for a raised exception: try: except: lines to execute if exception occurs except IndexError: def: declare a function: def myfunc(arg1, arg2): class: declare a class class MyClass(object): OPERATORS An operator usually has two operands upon which it operates; it returns the result. math operators (+, -, *, /, **, %): var = 5 * 10 concatenation operator (+): var = 'hello' + ', world!' string repetition operator (*) var = 'hello' * 3 binary assignment operators (+=, -=, *=, /=, **=): var += 1 comparison operators (<, >, ==, <=, >=,!=): if var < 20: print var membership operators (in, not in): if 'David' not in names_list: identity operators (is, is not): if var is None: boolean compound operators (and, or): if var > 10 and var < 20: ternary expression (x if C else y): var = 0 if var < 0 else var FUNCTIONS all(): given a container, True if all are True if all([5, 10, 0.9, True]): any(): given a container, True if any are True if any([5, 0, 0, 0.0, None]): bool(): return True or False based on passed object enumerate(): return a list of (count, item) for count, item in enumerate(mylst): exit(): exit the program exit() int(), float(), str(), bool(): object constructors myf = float(5) len(): length of a string or container mylen = len('hello') min(), max(): min or max val from an iterable this = min([5, 9, 3, 0.9, 2]) print(): echo text to the screen print('hello');print('hello', end='\n') range(): return a list of integers in a range myrange = range(5, 10) input(): take keyboard input x = raw_input('enter num: ') repr(): display an object in more 'literal' form print repr(mystr) round(): round a float myr = round(5.539, 2) sorted(): return a list of sorted objects x = sorted([5, 9, 3, 0.9, 2]) type(): get type of any object print type(myr)

INTEGER and FLOAT var = 5 my_xx = 5.0 # initialize an int object # initialize a float object STRING mystr = 'hello' yourzzy = "hello" this_one = """this is a multi-line string.""" # initialize a single-quoted string object # initialize a double-quoted string (same as above) # initialize a multi-line string object count(): return int occurrences of substr within a string mynum = mystr.count('e') find(): return int index position of substr within a string indexx = mystr.index('e') format(): return a new string with {} tokens replaced fmstr = mystr.format(55, 23.0) isdigit(): return True if string is all digit characters if mystr.isdigit(): join(): return a string of element values joined on a str ','.join(['val1', 'val2', 'val3']) replace(): return a new string with substr replaced rstr = mystr.replace('e', 'a') rstrip(): return a str with whitespace / other chars removed mystr = mystr.rstrip() split(): return a list of strs from string split on delimeters slist = mystr.split() splitlines(): return a list of strs comprising lines from file slines = text.splitlines() startswith(): return True if string begins with substr if mystr.startswith('hel'): string slicing: return a portion of string slicstr = mystr[3:5] upper(), lower(): return an upper- or lowercased str newstr = mystr.upper() LIST and TUPLE mylist = ['a', 'b', 'c', 'hello', 5.3, 9] mytup = ('a', 'b', 'c', 'hello', 5.3, 9) # initialize a list # initialize a tuple slicing: return a list or tuple withs elected items newlist = mylist[3:5] subscripting: return one item from a list myitem = mylist[3] list append(): add an item to the end of a list mylist.append(100)

SET myset = { 'a', 'b', 'c', 'd' } =or= myset = set(['a', 'b', 'c', 'd']) add(): add an item to a set myset.add('newitem') difference(): return items in this set not in an iterable newset = myset.difference(this_list) intersection(): return items in this set also in an iterable newset = myset.intersection(a_tuple) union(): return items in both this set and an iterable newset = myset.union(some_set) DICTIONARY mydict = { 'a': 1, 'b': 2, 'c': 3 } add a key/value pair mydict['d'] = 4 read a value based on a key var = mydict['d'] loop through a dict's keys for key in mydict: loop through a dict's items for key, val in mydict.items() check for key membership for key in mydict: return length of a dict thislen = len(mydict).get(): return a value (or default) given a key value = mydict.get('a', None).items(): return a list of 2-element tuples items = mydict.items().keys(): return a list of the dict's keys keys = mydict.keys().values(): return a list of the dict's values values = mydict.values() FILE fh = open('thisfile.txt') # initialize a file object function: open() a file for writing fh = open('thisfile.txt', 'w') function: open() a file for appending fh = open('thisfile.txt', 'a') method: write(): write string data to the file fh.write('a line of text\n') 'for' looping: assign each line in file to a 'control variable' for line in fh: read(): return a string containing the text of the file text = fh.read() readlines(): return a list of strings, each line from file lines = fh.readlines()

MULTIDIMENSIONAL CONTAINERS list of lists x = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] o access a single element item = x[1][2] # 6 list of dicts o loop through for innerlist in x: for item in innerlist: print item x = [ { 'this': 5, 'that': 10 }, { 'this': 20, 'that': 7 } ] o access a single element value = x[1]['that'] # 7 dict of lists o loop through for innerdict in x: for key in innerdict: print innerdict[key] x = { 'a': [ 1, 2, 3, 4 ], 'b': [1, 3, 2, 4] } o access a single element item = x['b'][1] # 3 o loop through for key in x: for item in x[key]: print item dict of dicts x = { 'a': { 'this': 5, 'that': 10 }, 'b': { 'this': 20, 'that': 25 } } o access a single element o loop through value = x['a']['that'] # 10 for key in x: print key + ':' for ikey in x[key]: print ' ' + ikey + ', ' + str(x[key][ikey])

CONTAINER OPERATIONS (applies to list, tuple, set, string, others) len(): get int length of (# of items in) container length = len(mylist) in: test for membership in a container if 'hello' in mylist: for: loop through each item in a container for item in myset: sum(): sum values in a container (numbers) total = sum(prices) max(): get max value in a container highest = max(prices) min(): get min value in a container minim = min(prices) sorted(): return list of items, sorted slist = sorted(mylist) subscript: return item at index pos (list, tuple) first = mylist[0] slice: return new container with selected items newlist = mylist[3:5] LIST COMPREHENSIONS wanted_lines = [line.split()[1] for line in lines if line.startswith('1972')] LAMBDAS slist = sorted(mylist, key=lambda x: x.split()[0]) CUSTOM SORT FUNCTIONS def by_first_item(line): items = line.split() first_item = items[0] return first_item slist = sorted(mylist, key=by_first_item) TRAPPING EXCEPTIONS try: x = int(input('enter a number, please: ') except ValueError: print('oops, that did not convert to an int!')

USER-DEFINED FUNCTIONS def addthese(arg1, arg2): mysum = arg1 + arg2 return mysum argument and return value def myfunc(this_arg): new_val = this_arg + 1 return new_val positional arguments def myfunc(arg1, arg2): keyword arguments def myfunc(this=none, that=0): arbitrary arguments: *args def myfunc(*args): arbitrary keyword arguments: **kwargs def myfunc(**kwargs): MODULES time: import time time.sleep(10) date and datetime: from datetime import datetime dt = datetime.now() timedelta: from datetime import timedelta td = timedelta(hours=3) USING MODULES import modname: import a module's variables through its name import mymod print mymod.var import modname as convenientname: rename module in our code import mymod as tt print tt.var from modname import varname: import a variable from module from mymod import var from modname import *: don't ever do this! ;) NO sys.path: module search path sys.path.append(newdir) PYTHONPATH: environment variable informing the sys.path if name == ' main ': module / script "identity gate" if name == ' main ': main() pip module install program

CLASSES class declaration class MyClass(object): pass set object's attributes ( dict ) x = MyClass() x.var = 5 get attribute value print x.var self implicit argument to method def dothis(self): init constructor def init (self): EXCEPTIONS (also see Exceptions Reference) SyntaxError: when the code has a syntax mistake (missing paren or quote, etc.) NameError: when a variable name is used that doesn't exist (often a misspelling) TypeError: when the type of object used in a function or method is incorrect AttributeError: when attempting to acces an attribute (e.g. method) that is incorrect for the object IndexError: when attempting to access an item in a list where the index doesn't exist UnboundLocalError: reading a local variable before def dothis(): assigning x = x + 1 # is x a global? IndentationError: when an indent occurs before for item in mylist: a block, or doesn't occur inside a block print item raise: cause an exception to occur raise ValueError