Python Tutorial. Day 2

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

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

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

LECTURE 4 Python Basics Part 3

FILE HANDLING AND EXCEPTIONS

CIS192 Python Programming

CIS192 Python Programming

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

CIS192 Python Programming

CIS192 Python Programming

STSCI Python Introduction. Class URL

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

Python Tutorial. Day 1

CS 11 python track: lecture 2

Exceptions and File I/O

Java Bytecode (binary file)

Exceptions CS GMU

MEIN 50010: Python Flow Control

CSc 120. Introduction to Computer Programming II. 07: Excep*ons. Adapted from slides by Dr. Saumya Debray

Control Structures 1 / 17

Some material adapted from Upenn cmpe391 slides and other sources

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

An Introduction to Python

Modules and scoping rules

stdin, stdout, stderr

Try and Error. Python debugging and beautification

Reading and writing files

EE 355 Unit 17. Python. Mark Redekopp

Python for Informatics

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

CS Programming Languages: Python

Introduction to Python! Lecture 2

Key Differences Between Python and Java

What is an Exception? Exception Handling. What is an Exception? What is an Exception? test = [1,2,3] test[3]

Flow Control: Branches and loops

Introduction to Python

Basic Syntax - First Program 1

CSE : Python Programming. Homework 5 and Projects. Announcements. Course project: Overview. Course Project: Grading criteria

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

Introduction to Python (All the Basic Stuff)

CS Lecture 26: Grab Bag. Announcements

Accelerating Information Technology Innovation

What we already know. more of what we know. results, searching for "This" 6/21/2017. chapter 14

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

Python for Non-programmers

CS Summer 2013

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

Python File Modes. Mode Description. Open a file for reading. (default)

(Refer Slide Time: 01:12)

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

Exception Handling and Debugging

Lecture 18. Classes and Types

A Little Python Part 3

S206E Lecture 19, 5/24/2016, Python an overview

1 Strings (Review) CS151: Problem Solving and Programming

Python. How You Can Do More Interesting Things With Python (Part II)

Idioms and Anti-Idioms in Python

Beyond Blocks: Python Session #1

Review 3. Exceptions and Try-Except Blocks

Accelerating Information Technology Innovation

Python Working with files. May 4, 2017

Babu Madhav Institute of Information Technology, UTU 2015

Most of the class will focus on if/else statements and the logical statements ("conditionals") that are used to build them. Then I'll go over a few

File Operations. Working with files in Python. Files are persistent data storage. File Extensions. CS111 Computer Programming

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

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

18.1. CS 102 Unit 18. Python. Mark Redekopp

Programming in Python 3

A Little Python Part 3

Chapter 2 Writing Simple Programs

for loops Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

Functions and Decomposition

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Advanced Python. Executive Summary, Session 1

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

SECOND EDITION SAMPLE CHAPTER. First edition by Daryl K. Harms Kenneth M. McDonald. Naomi R. Ceder MANNING

Python 3: Handling errors

Table of Contents EVALUATION COPY

COMP1730/COMP6730 Programming for Scientists. Exceptions and exception handling

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

Lecture 21. Programming with Subclasses

And Parallelism. Parallelism in Prolog. OR Parallelism

Programming with Python

Chapter 7. - FORTRAN I control statements were based directly on IBM 704 hardware

Embedding a Python interpreter into your program

Cosmology with python: Beginner to Advanced in one week. Tiago Batalha de Castro

Control of Flow. There are several Python expressions that control the flow of a program. All of them make use of Boolean conditional tests.

Part III Appendices 165

Chapter 9: Dealing with Errors

The current topic: Python. Announcements. Python. Python

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

Exception Handling. Genome 559

Structure and Flow. CS 3270 Chapter 5

Lecture 3. Functions & Modules

CSE : Python Programming

File Operations. Working with files in Python. Files are persistent data storage. File Extensions. CS111 Computer Programming

Python Programming: An Introduction to Computer Science

Introduction to python

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

for loops Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

Transcription:

Python Tutorial Day 2 1

Control: Whitespace in perl and C, blocking is controlled by curly-braces in shell, by matching block delimiters, if...then...fi in Python, blocking is controlled by indentation lots of people whine about this, remembering FOR- TRAN horrors well-written code should indent anyway 2

class Sysinfo: def init (self): self.db = {} self.getinfo() def getinfo(self): f = os.popen(sysinfo, r ) for line in f.readlines(): m = line.split(" ") # Only note lines with all the fields. if len(m) >= 4: self.db[m[2]] = m[4].strip() f.close() 3

Control: Decisions, decisions if works as expected a colon indicates a block is coming, so... if spam > 3: statement1 elif eggs <= 42: statement2 statement3 else: statement4 4

Control: Conditionals expected tests: > >= < <= ==!= these work on numbers and strings comparing other sequences tests in parallel booleans: and or not sequence membership: in, not in identity (same location in memory): is, is not 5

>>> "wow" > "nee" True >>> "wow" < "nee" or 3 < 2 False >>> (1, 2, 3) > (0, 1, 2) True >>> (1, 2, 3) < (0, 1, 2) False >>> [1, 2, 3] == [1, 2, 3] True >>> "spam" in [1, 2, "spam", 4] True >>> "a" in "spam" True >>> "f" not in "eggs" True 6

Special type of Nothing where perl has undefined, python often uses None many functions may return this normally, we don t use is an is not test one common idiom however: data = some_function() if data is not None: play_with(data) else: print "Shut er down, Clancy!" 7

While works as expected, with one additional surprise optional else clause for when the condition is false >>> f = 3 >>> while f > 0:... print f,... f -= 1 # same as: f = f - 1... else:... print "done"... 3 2 1 done >>> Loop forever: while True: 8

Looping over Sequences again, works as expected, with the addition of an optional else clause >>> for item in [3, 2, 1]:... print item,... else:... print "done"... 3 2 1 done no separate for and foreach syntax 9

Looping over Integers the range function produces an integer sequence technically, produces an iterator object, which is memory efficient range(100000) not waste of memory range([start,] stop[, step]) >>> range(4) [0, 1, 2, 3] >>> range(4, 0, -1) [4, 3, 2, 1] 10

Loops: Cutting out early both for and while loops may be exited early continue causes the rest of the block to be skipped, and the loop to go on to the next stage break cause control to jump out of the loop, skipping the else block 11

>>> for item in "spam":... if item == "a": break # one-line if statement... print item,... s p >>> for item in "spam":... if item == "a": continue... print item,... s p m 12

Functions defined with def without a return statement, the function returns None function arguments may be given default values >>> def mult(x, y=1):... return x * y... >>> mult(5, 3) 15 >>> mult(5) 5 >>> 13

Documenting Functions functions can (should) have doc strings by convention, triple quoted, may cross several lines first thing after def line def frobnify(x, y, monkey): """frobnify(x, y, monkey) -> list. Cast monkey into 2D hilbert-space. If monkey is less than zero, throws InfiniteMonkeys exception. """ l2 = frobnosticate(x, monkey) ** dogma_dance(y, monkey)... 14

Input and Output: Terminal input reads from terminal but evaluates input raw_input does not evaluate input >>> spam = input() eggs Traceback (most recent call last): File "<stdin>", line 1, in? File "<string>", line 0, in? NameError: name eggs is not defined >>> spam = raw_input() eggs >>> spam eggs >>> viking = input("how many Vikings? ") How many Vikings? 33 >>> viking 33 15

Input and Output: Files like unix: open takes file name and mode mode: r, w, a for read, write or append open returns a file object, with several methods readline() reads a single line (up to newline) readlines() for iterating over every line 16

write(str) write the string to the file writelines(seq) write sequence of strings neither write form adds newlines close() to close file flush() to force buffered data into file

Silly Function Example: Counting The def count_the(filename): """count_the(filename) -> integer. Count word "the" in a file.""" thes = 0 f = open(filename, "r") for line in f.readlines(): words = line.split() for word in words: # Not very smart: should clean up punctuation, or better, # this should be turned into a regular expression test. if word.lower() == "the": thes += 1 f.close() return thes 17

Python s Libraries called modules in Python lingo many are hierarchical there are modules to do nearly everything modules have their own documentation trail many third-party tools 18

Import: Safest Version import modulename is safest to your namespace the module functions will be called modulename.function() requires a lot of typing good for infrequently called functions 19

Import: Into the Global Namespace when you define a function in your program, then function name is in the global namespace using from MODULE import FUN1, FUN2, FUN3,... you import module functions into the global namespace there is a danger of name-clash but for functions you use a lot, it saves a lot of typing 20

Useful module: sys normally just use import sys useful function is sys.exit(error_code), exits the program immediately (say, for a nonrecoverable error) the input and raw_input functions are crude full file methods available for sys.stdin, sys.stdout and sys.stderr for line in sys.stdin.readlines(): do_something_with(line) 21

When things go bad: Exceptions when python encounters a fatal error, it raises an exception there are many sorts of exception exceptions are just classes you can write your own there are control structures to watch for and clean up after exceptions 22

Exception Handling dangerous code goes into try block if anything in that fails, matching except clause run try: f = open(filename, "r") except: sys.stdout.write("can t open %s!\n" % filename) sys.exit(1) 23

you can check for particular exceptions the catch-all, default except clause must be last try: f = open(filename, "r") except IOError: sys.stdout.write("io: can t open %s!\n" % filename) sys.exit(1) except: sys.stdout.write("mystery error!\n") sys.exit(2) 24

Many Exceptions you can extract more information exceptions have a class hierarchy, so an exception might have several matches e.g. any OverflowError, ZeroDivisionError or FloatingPointError is also an ArithmeticError I ll introduce more of these as we move along 25

A Taste of Class no real object orientation this week an object in python is just another namespace as with modules, you grab object elements with the dot notation, f.close() these are technically called properties you can can create a dummy class just to hold properties 26

Class like C struct # When a block is required, like in class, use # pass - a no-operation command - as a placeholder. Useful in loops # and conditionals during development, too >>> class info: pass... >>> m = info() >>> spam = info() >>> spam.name = "Michael Palin" >>> spam.name Michael Palin >>> spam.goo Traceback (most recent call last): File "<stdin>", line 1, in? AttributeError: info instance has no attribute goo 27