STSCI Python Introduction. Class URL

Similar documents
STSCI Python Introduction

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

THIS CHAPTER DESCRIBES PYTHON S BUILT-IN OPERATORS as well as the precedence

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

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

PYTHON- AN INNOVATION

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

CIS192 Python Programming

CIS192 Python Programming

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

Variable and Data Type I

ECE 364 Software Engineering Tools Laboratory. Lecture 4 Python: Collections I

FILE HANDLING AND EXCEPTIONS

LECTURE 4 Python Basics Part 3

Advanced Algorithms and Computational Models (module A)

Introduction to Bioinformatics

CIS192 Python Programming

Python Tutorial. Day 2

CIS192 Python Programming

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

Python: common syntax

ENGR 101 Engineering Design Workshop

Babu Madhav Institute of Information Technology, UTU 2015

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

And Parallelism. Parallelism in Prolog. OR Parallelism

Introduction to Python

Coral Programming Language Reference Manual

A Little Python Part 3

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

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

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

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

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

file_object=open( file_name.txt, mode ) f=open( sample.txt, w ) How to create a file:

Programming in Python 3

egrapher Language Reference Manual

CS Programming Languages: Python

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

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

Collections. Lists, Tuples, Sets, Dictionaries

CSCE 110 Programming I

Data Handing in Python

UNIVERSITÀ DI PADOVA. < 2014 March >

Topics. Chapter 5. Equality Operators

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

Data Structures. Lists, Tuples, Sets, Dictionaries

STA141C: Big Data & High Performance Statistical Computing

Programming Languages: Part 2. Robert M. Dondero, Ph.D. Princeton University

Script language: Python Data structures

A Little Python Part 3

Advanced Python. Executive Summary, Session 1

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1

Text Input and Conditionals

Programming in Python

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

JAVA Programming Fundamentals

What Version Number to Install

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

C Programming Language (Chapter 2 of K&R) Variables and Constants

Variable and Data Type I

Engineering Computing I

CIS192 Python Programming. Robert Rand. August 27, 2015

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

Chapter 3 : Informatics Practices. Class XI ( As per CBSE Board) Python Fundamentals. Visit : python.mykvs.in for regular updates

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Standard C Library Functions

Compound Data Types 1

Python. Executive Summary

Table of Contents. Preface... xxi

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

The current topic: Python. Announcements. Python. Python

CIS192: Python Programming

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

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

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

LCSL Reference Manual

Guide for The C Programming Language Chapter 1. Q1. Explain the structure of a C program Answer: Structure of the C program is shown below:

More Programming Constructs -- Introduction

MEIN 50010: Python Flow Control

UNIT- 3 Introduction to C++

Python 3 Quick Reference Card

Accelerating Information Technology Innovation

Chapter 4 : Informatics Practices. Data Handling. Class XI ( As per CBSE Board) Visit : python.mykvs.in for regular updates

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

Programming to Python

Index COPYRIGHTED MATERIAL

DaMPL. Language Reference Manual. Henrique Grando

Getting Started with Python

COMP Primitive and Class Types. Yi Hong May 14, 2015

Overview of List Syntax

Computer Organization & Systems Exam I Example Questions

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

Python Working with files. May 4, 2017

Introduction to Python

Java Basic Programming Constructs

MUTABLE LISTS AND DICTIONARIES 4

Introduction to C Language

Introduction to Python! Lecture 2

JAC444 - Lecture 1. Introduction to Java Programming Language Segment 4. Jordan Anastasiade Java Programming Language Course

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

Transcription:

STSCI Python Introduction Class 2 Jim Hare Class URL www.pst.stsci.edu/~hare Each Class Presentation Homework suggestions Example files to download Links to sites by each class and in general I will try to have the PowerPoint slides by Friday AM before each Monday s class. 1

Today s Agenda Object Oriented Concepts Built-in Types Operators Formatting to Strings Control Flow Functions Passing Arguments to Modules Object Oriented Concepts Every piece of data stored in a program is an object. Each object has an identity, a type, and a value. When an object is created, the object created is called an instance of that type. 2

Object Identity Identity pointer or reference to the location in memory. >>> a = 42 # create an instance of an integer a >>> id(a) # gets the memory location for object a 13074924 Object Type The type of an object describes the internal representation of the object, the methods and operations that it supports. Having the data, methods and operations defined within an object is call encapsulation. This is what is different from old programming techniques. You don t have to know how the object is implemented. You just need to know the interface. 3

Example of type() >>> namestring = "Zach Hare >>> type(namestring) <type 'string > >>> namelist = ['Zach','Hare'] >>> type(namelist) <type 'list'> >>> namedict = {'first':'zach','last':'hare'};type(namedict) <type 'dictionary'> >>> age = 12;type(age) <type 'int'> Object Methods and Attributes A method is a function that performs some sort of operation on an object when the method is invoked. An attribute is a property or value associated with an object. Attributes and methods are accessed using the dot (.) operator. 4

Example of Methods and Attributes >>> a = 3 +4j # Create a complex number >>> r = a.real # Get real part (an attribute) >>> print r 3.0 >>> b = [1,2,3] >>> b.append(7) # add element 7 to the list with # method append >>> b [1, 2, 3, 7] None Type Numeric Types Sequence Types Mapping Types Built-in Types 5

The None Type The None type denotes a null object. None has no attributes and evaluates to false in Boolean expressions. Often used as a default value in optional arguments. X = None Numeric Types Integers - whole numbers from -2147483647 to 2147483647 in 32 bits, 4 bytes. Some machines the range is larger 8 bytes. Long integers whole numbers limited only by available memory. Floating-point uses machines double-precision 64-bit, 8 bytes. Complex numbers a pair of floating-point numbers. Z has Z.real and Z.imag. 6

Operators and the Order of Evaluation Operator ( ), [ ], { } s[i], s[i:j], s.attr f( ) +x, -x, ~x x**y x * y, x / y, x % y x + y, x y x << y, x >>y x & y x^ y Name Tuple, list, dictionary creation String conversion Indexing and slicing attributes Function calls Unary operators Power(right associative) Multiplication, division, modulo Addition, subtraction Bit shifting Bitwise and Bitwise exclusive or Operators and the Order of Evaluation Operator x y x < y, x <= y, x > y, x >= y, x == y, x!= y x < > y x is y, x is not y x in s, x not in s not x x and y x or y lambda args: expr Name Bitwise or Comparison, identity, and sequence membership tests Logical negation Logical and Logical or Anonymous function 7

Operator Precedence Examples >>> x = 2;y=3 >>> z = x + y**2 % 6 >>> z 5 >>>z =x +((y**2) % 6) Sequence Types Sequences represent ordered sets of objects indexed by non-negative integers and include strings, Unicode strings, lists, tuples, xrange objects, and buffer objects. Strings and buffers are sequences of characters. xrange objects are sequences of integers. Lists and tuples are sequences of arbitrary objects. 8

List Type Example >>> xlist = [[0,1,2], [3,4,5], [6,7,8]] >>> xlist [0][0] 0>>> xlist [0][2] 2>>> xlist [2][1] 7 X[row][column] String Splicing >>> xstring = 'I am learning NNNNNN today >>> xstring[14:20] = 'Python Traceback (innermost last): File <interactive input>", line 1, in? TypeError: object doesn't support slice assignment >>> xstring = xstring[:14] + 'Python' + \ xstring[20:] >>> xstring 'I am learning Python today' 9

Mapping Types A mapping object represents an arbitrary collection of objects that are indexed by another collection of nearly arbitrary key values. Mapping objects are unordered and keys are immutable. The mappings are mutable. Dictionaries are the only built-in mapping type. X = Python Formatting to Strings Y = I am learning %s today % X X = 3.146789 Y = The real number is %-10.4f % X The real number is 3.1468 10

String Formatting Conversions Char Format Char Format d,i Decimal integer of L u Unsigned integer or L o Octal integer or L x Hexadecimal integer or L X Hexadecimal integer f Floating Point [-]m.dddddd Uppercase letters. e [-]m.dddddde+xx E [-]m.dddddde+xx G,g Use %E or %e for exponents less than 4 or greater than the precison; otherwise use %f s String or any object. The formatting code use str() to generate strings. r Same string as repr() c Single character % Literal % String Formatting Examples a = 42 b = 13.142783 c = hello d = { x :13, y :1.54321, z : world } a is %d % a # a is 42 %10d %f % (a,b) # 42 13.142783 %(x)-10d %(y)0.3g %d # 13 1.54 %*.*f % (5,3,b) # 13.143 11

Control Flow Supports if, for, while, and try Blocks of code executed within a control flow are indented. It is a syntax error when indentation is not correct Boolean expressions or, and, and not are used for Truth Values pass # do nothing Control Flow Conditionals if expression: statements elif expression: statements elif expression: statements else: statements #endif Note: You don t need this but it is wise to keep you organized sometimes. 12

Loops while while expression: else: statements if expression: break statements Loops For for i in range(0,10,2): # ie.(start,stop,step) statements if Istring[I] == foo : break else: statements #endfor not necessary 13

range() and xrange() range(start,end,stride) range constructs a list and populates values according to start, end and stride(step size). Remember end is an up to value xrange() value calculated when accessed; it save memory A = range(5) # A = [0,1,2,3,4] D = range(8,2,-2) # D = [8,6,4] b = xrange(1000000) # b = [0,1,2,, 999999] Try and Except Control Try and Except blocks are a way to override python stopping the execution of a program due to a system error. The except block provides a way to execute statements on a specific error or set of errors Except blocks without a specified type of error execute the statements for any error. 14

try: statements Try and Except Block except: statements to handle error #could just use pass Except: Error Types try: except IOError, e: # e is optional args of except TypeError: # raise See Appendix A, The Python Library for details of exception errors 15

Passing Arguments to Modules Using the python module sys import sys sys.argv a list containg the module name in sys.argv[0] followed by arguments passed sys.path path used to find modules, uses PYTHONPATH environment variable Passing Arguments to Modules os module os.environ is a dictionary of the current environment variables print os.environ[ DSQUERY ] nomad os.environ[ DSQUERY ] = R2D2 Note: This will only change the environment variable for your current program run Example /ess5/psdpython/dbtools.py 16

os.system os.system( pwd ) os.system( echo $DSQUERY ) The shell is the basic c shell not tcsh. Mail Example import os tolist = [{ name : Paul, email : plee@stsci.edu }, { name : Erin, email : roye@stsci.edu}] for todict in tolist: mailstring = Hi %s, The Python class is today at 11:30. Jim % todict[ name ] os.system( printf %s mailx s Class Today r hare@stsci.edu %s %(mailstring,todict[ email ]) 17

Functions Function template Consists of def statement, parameters and return def test1(x,y,j= testcase1 ) j= testcase1 is the default Example /ess5/psdpython/pythonclass/class2/update_ default_db.py Passing Arguments if name == main : if name == ' main ': if len(sys.argv)!= 3: print Error in arguments try again. sys.exit() database = string.lower(sys.argv[1]) account = sys.argv[2] run(database,account) 18

Passing Arguments - continued main is the name of the originating or first module run in the current execution of python def run(database, account='sogsspss'): #database #account os.system('printf "sp_defaultdb %s,%s\\ngo" isql' % (account,database)) os.system('printf "select db_name()\\ngo" isql') return None Functions Returning Values def splitonperiod(instring): # is a string import string stringlist = string.split(instring,. ) test = 1 return test,stringlist astring = md.summer.2002.stsci.edu status,varlist = splitonperiod(astring) 19

Raw Input Command first = raw_input( Type your first name: ) mid = raw_input( Type your middle name: ) last = raw_input( Type your last name: ) print Your full name is %s %s %s \ % (first,mid,last) Example: myname.py Files myfile = open( build_id.data, r ) File modes are: r, w, or a. b following means binary ie. rb Updates r+ or w+, can perform both input and output, as long as output operations flush their data before subsequent input operations ie. f.flush() 20

File Methods - Read F.read - Reads at most n bytes F.readline() - Reads a single line of input F.readlines() - Reads all the lines and returns a list. Ie. mylist = F.readlines() File Methods - Write F.write(S) F.writelines(L) - Writes string S - Writes all strings in List L 21

F.close() F.tell() File Methods - closes the file F - returns the file pointer F.seek(offset [,where]) seek to new file position F.isatty() F.flush() F.truncate([size]) F.fileno() - 1 if F is interactive terminal - Flushes output buffers - truncates to size bytes - integer descriptor File Attributes F.closed - Boolean 0 = open, 1=closed F.mode - I/O mode of file F.name - name of file or source F.softspace - indicator of whether a space character needs to be printed before another value when using the print statement. 22

Standard Input, Output, and Error import sys - to get access to Standard I/O files sys.stdin sys.stdout sys.stderr - Standard Input - Standard Output - Standard Error Examples and Homework Look at: osenv.py a module to create environment variable setup scripts for regression tests. osreg.py a module to run a test in two different environments and compare results. Download these to your working directory. From python import osenv osenv.makeenvfile( test1 ) Get out of python and look at envtest1.py that you just generated 23