Advanced Python. Executive Summary, Session 1

Similar documents
Python. Executive Summary

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.

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

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

Exceptions and File I/O

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

Python Intro GIS Week 1. Jake K. Carr

18.1. CS 102 Unit 18. Python. Mark Redekopp

Beyond Blocks: Python Session #1

Babu Madhav Institute of Information Technology, UTU 2015

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

Sequences and iteration in Python

University of Texas at Arlington, TX, USA

The Practice of Computing Using PYTHON

Introduction to Python

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

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

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

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

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

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

Control Structures 1 / 17

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

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

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

Variable and Data Type I

Python: common syntax

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

Introduction to Python for Plone developers

DaMPL. Language Reference Manual. Henrique Grando

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

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

Exercise: The basics - variables and types

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

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

Working with Sequences: Section 8.1 and 8.2. Bonita Sharif

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

Python Evaluation Rules

Computing with Strings. Learning Outcomes. Python s String Type 9/23/2012

Programming in Python 3

cs1114 REVIEW of details test closed laptop period

Variables, Expressions, and Statements

String Processing CS 1111 Introduction to Programming Fall 2018

ENGR 101 Engineering Design Workshop

The Practice of Computing Using PYTHON. Chapter 4. Working with Strings. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Comp Exam 1 Overview.

CS 303E Fall 2011 Exam 2 Solutions and Criteria November 2, Good Luck!

SCoLang - Language Reference Manual

Python Review IPRE

12. Logical Maneuvers. Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except

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

CSCE 110 Programming I

CIS192: Python Programming

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

6. Data Types and Dynamic Typing (Cont.)

Exercise: The basics - variables and types

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

Programming in Python

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

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

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

EE 355 Unit 17. Python. Mark Redekopp

Python source materials

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

Variable and Data Type I

The Warhol Language Reference Manual

MEIN 50010: Python Flow Control

Types, lists & functions

At full speed with Python

Python Tutorial. Day 1

CS 115 Lecture 13. Strings. Neil Moore. Department of Computer Science University of Kentucky Lexington, Kentucky

CIS192 Python Programming

CIS192 Python Programming

A Problem. Loop-Body Returns. While-Loop Solution with a Loop-Body Return. 12. Logical Maneuvers. Typical While-Loop Solution 3/8/2016

Overview of List Syntax

ARG! Language Reference Manual

Part III Appendices 165

Working with Strings. Husni. "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc.

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

Lists, loops and decisions

UNIT-III. All expressions involving relational and logical operators will evaluate to either true or false

egrapher Language Reference Manual

CMPT 120 Basics of Python. Summer 2012 Instructor: Hassan Khosravi

Sequence of Characters. Non-printing Characters. And Then There Is """ """ Subset of UTF-8. String Representation 6/5/2018.

UNIVERSITÀ DI PADOVA. < 2014 March >

Student Number: Comments are not required except where indicated, although they may help us mark your answers.

An Introduction to Python

ECE 364 Software Engineering Tools Lab. Lecture 3 Python: Introduction

MULTIPLE CHOICE. Chapter Seven

STSCI Python Introduction. Class URL

Python Review IPRE

Python and Bioinformatics. Pierre Parutto

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp

CIS192 Python Programming

Try and Error. Python debugging and beautification

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

Python - Variable Types. John R. Woodward

def order(food): food = food.upper() print( Could I have a big + food + please? ) return fresh + food

Transcription:

Advanced Python Executive Summary, Session 1 OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or use with 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!' Initialization of a variable means that the variable name has been bound to an object, and the object is now 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. STATEMENT simple statements: assignment (with =): var = 10 augmented assignment (+=, -=, etc.): var += 5 del (unbind a variable or remove a dict key/value): del var? print (echo string text to STDOUT): print 'hello!' break (drop out of a loop): break continue (jump to next iteration of a loop): continue import (import a Python module): import random

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): OPERATORS An operator usually has two operands upon which it operates; it returns the result. math operators (+, -, *, /) var = 5 * 10 # 50 exponientation operator (**): var = 5 ** 2 # 25 binary assignment operators (+=, -=, *=, /=, **=): var += 1 string concatenation operator (+) string repetition operator (*) 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 len(): length of a string or container mylen = len('hello') round(): round a float myr = round(5.539, 2) type(): get type of any object print type(myr) raw_input(): take keyboard input x = raw_input('enter num: ') exit(): exit the program exit() int(), float(), str(), bool(): object constructors myf = float(5) repr(): display an object in more 'literal' form print repr(mystr) any(): given a container, True if any are True if any([5, 0, 0, 0.0, None]): all(): given a container, True if all are True if all([5, 10, 0.9, True]): min(), max(): min or max val from an iterable this = min([5, 9, 3, 0.9, 2])

sorted(): return a list of sorted objects x = sorted([5, 9, 3, 0.9, 2]) range(): return a list of integers in a range myrange = range(5, 10) enumerate(): return a list of (count, item) for count, item in enumerate(mylst): CORE OBJECT TYPES 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 string slicing: return a portion of string slicstr = mystr[3:5] upper(), lower(): return an upper- or lowercased str newstr = mystr.upper() 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') replace(): return a new string with substr replaced rstr = mystr.replace('e', 'a') 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(): startswith(): return True if string begins with substr if mystr.startswith('hel'): 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() rstrip(): return a str with whitespace / other chars removed mystr = mystr.rstrip() LIST and TUPLE subscripting: return one item from a list myitem = mylist[3] slicing: return a list or tuple withs elected items newlist = mylist[3:5] list append(): add an item to the end of a list mylist.append(100) SET add(): add an item to a set myset.add('newitem')

FILE fh = open('thisfile.txt') # initialize a file object '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() 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] 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): TRAPPING EXCEPTIONS try: x = int(input('enter a number, please: ') except ValueError: print('oops, that did not convert to an int!')

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