python. introduction python is a computer programming language conceived in the late 1980s by guido...

59
Python

Upload: juliet-lee

Post on 25-Dec-2015

236 views

Category:

Documents


0 download

TRANSCRIPT

Python

Introduction

• Python is a computer programming language conceived in the late 1980s by Guido van Rossum.

• Python's name is derived from the television seriesMonty Python's Flying Circus. 

• # comments

• print 'hello world‘• enter quit() at the interactive chevron >>> prompt to quit.• Strings —characters enclosed by a pair of single or

double quotes.• Strings are one kind of data in Python. Their data type is

denoted str.

Introduction

• There are two kinds of numerical data in Python: integers and decimal numbers.

• Integers correspond to the data type int. Decimal numbers are represented by floating-point numbers corresponding to the data type float.

• Floating-point numbers have around 15 decimal digits of accuracy.

• Find out the type:print type(3), type(3.14159)type(3.0)

Introduction

• convert between data types using int() and float()• # note that int() takes the "whole" part of a decimal

number and doesn't round• print int(3.14159), int(-2.8)• print float(3), float(-1)• 76trombones is illegal variable name because it does not

begin with a letter. • more@ is illegal because it contains an illegal character,

@. • class is illegal because class is one of Python’s reserved

keywords.

Introduction

• Python reserves 31 keywords: and del from not while as elif global or with assert else if pass yield break except import print class exec in raise continue finally is return def for lambda try

http://www.codeskulptor.org/

• # arithmetic operators• # + plus addition• # - minus subtraction• # * times multiplication• # / divided by division• # ** power exponentiation• print 1 + 2, 3 - 4, 5 * 6, 2 ** 5• # If one operand is a decimal (float), the answer is

decimal• print 1.0 / 3, 5.0 / 2.0, -7 / 3.0

http://www.codeskulptor.org/

• # If both operands are ints, the answer is an int (rounded down)

• print 1 / 3, 5 / 2, -7 / 3• # minus is also a unary operator and can be applied to a

single expression• print 1 + 2 * 3, 4.0 - 5.0 / 6.0, 7 * 8 + 9 * 10• # operator precedence - (), **, *, /, +,-• print 1 * 2 + 3 * 4• print "Ex. 9: ", 4.0 / 3.0

http://www.codeskulptor.org/

• Variable names consist of a sequence of letters, number and underscores (_).

• Variable names start with a letter or underscore and are case sensitive.

• Single equals (=) is used for assignment to variables. Double equals (==) is used for testing equality.

• # legal names - ninja, Ninja, n_i_n_j_a• # illegal names - 1337, 1337ninja• # Python convention - multiple words joined by _• # legal names - elite_ninja, leet_ninja, ninja_1337• # illegal name 1337_ninja

http://www.codeskulptor.org/

• temp_Fahrenheit = 212temp_Celsius = 5.0 / 9.0 * (temp_Fahrenheit - 32)print temp_Celsius

• #my_age += 1

http://www.codeskulptor.org/

• Functions are reusable pieces of programs that take an input and produce an output.

• A function definition is a compound statement consisting of a header and a body.

• The header includes the keyword def, a sequence of parameters enclosed by parentheses, followed by a colon :.

• The body consists of a sequence of statements, all indented by 4 spaces.

• Functions may return a value using the keyword return or have a side effect (e.g., print).

http://www.codeskulptor.org/

• # computes the area of a triangle• def triangle_area(base, height): # header - ends in colon• area = (1.0 / 2) * base * height # body - all of body is indented• return area # body - return outputs value• a1 = triangle_area(3, 8)• print a1• a2 = triangle_area(14, 2)• print a2

http://www.codeskulptor.org/

• Indentation consists of whitespace formed by blanks, tabs, and newlines.

• Leading white space indicates indentation level (4 spaces per level) and specifies logical grouping of statements in Python.

• Incorrect indentation can lead to errors.

http://www.codeskulptor.org/

• Standard long division yields a quotient and a remainder. The integer division operator // computes the quotient. The operator % computes the remainder.

• For any integers a and b, a == b * (a // b) + (a % b).• In Python, a % b always returns an answer that is between 0 and b (even

if a and/or b is negative).• Remainders and modular arithmetic are very useful in games for the

purpose of "wrapping" the canvas, i.e; causing objects that pass off of one side of the canvas to reappear on the opposite side of the canvas.

• Modules — More Operations• Modules are libraries of Python code that implement useful operations not

included in basic Python.• Modules can be accessed via the import statement.• CodeSkulptor implements parts of the standard Python modules math and

random.

http://www.codeskulptor.org/

• The constants True and False of the type bool.• These constants can be combined to form Boolean expressions via

the logical operators and, or, and not.• The and of two Boolean expressions is True if both of the

expressions are True.• he values of two arithmetic expressions can be compared using the

operators ==, !=, <, >, <=, >=.• These comparisons return either True or False .

http://www.codeskulptor.org/

• Conditional statements are compound statements consisting one or more clauses headed by the keywords if, elif, and else.

• Each if or elif clause is followed by a Boolean expression and a colon :.

• If the Boolean expression for a clause is True, the body of the clause is executed

Events

Events

• Input: Button, Text box

• Keyboard: key down, key up

• Mouse: Click, Drag

• Timer

Events

# Example of a simple event-driven program

import simplegui

# Event handler

def tick():

print "tick!"

# Register handler

timer = simplegui.create_timer(1000, tick)

# call function tick every second

# Start timer

timer.start()

Local vs. global variables• Assignment to a variable inside a Python function creates a local

variable. The scope of the variable is the body of function.• # num1 is a global variable

num1 = 1

print num1 # 1

# num2 is a local variable

def fun():

num1 = 2

num2 = num1 + 1

print num2 # 3

fun()

print num1 # 1

# the scope of the variable num2 is fun(), num2 is now undefined

print num2 # Line 22: NameError: name 'num2' is not defined

Local vs. global variables• Variables defined outside functions are global variables. Their values may be accessed

inside functions without declaration.• To modify to a global variable inside a function, the variable must be declared inside the

function using the keyword global.• Global variables are a convenient (but dangerous) way for event handlers to share

information in event-driven programming.• num = 4

def fun1():

global num

num = 5

def fun2():

global num

num = 6

print num # 4

fun1()

print num # 5

fun2()

print num # 6

SimpleGUI• SimpleGUI allows creations of frames and timers as well as loading

sounds and images.• Frames include a control panel (with buttons and input fields), a status

area (for monitoring keyboard and mouse events) and a canvas (with simple 2D drawing operations).

• # SimpleGUI program template

# Import the module

import simplegui

# Define global variables (program state)

# Define "helper" functions

# Define event handler functions

# Create a frame

# Register event handlers

# Start frame and timers

Calculator• # calculator with all buttons

• import simplegui

• # intialize globals

• store = 0

• operand = 0

• # event handlers for calculator with a store and operand

• def output():

• """prints contents of store and operand"""

• print "Store = ", store

• print "Operand = ", operand

• print ""

• def swap():

• """ swap contents of store and operand"""

• global store, operand

• store, operand = operand, store

• output()

• def add():

• """ add operand to store"""

• global store

• store = store + operand

• output()

• def sub():

• """ subtract operand from store"""

• global store

• store = store - operand

• output()

• def mult():

• """ multiply store by operand"""

• global store

• store = store * operand

• output()

• def div():

• """ divide store by operand"""

• global store

• store = store / operand

• output()

• def enter(t):

• """ enter a new operand"""

• global operand

• operand = float(t)

• output()

• # create frame

• f = simplegui.create_frame("Calculator",300,300)

• # register event handlers and create control elements

• f.add_button("Print", output, 100)

• f.add_button("Swap", swap, 100)

• f.add_button("Add", add, 100)

• f.add_button("Sub", sub, 100)

• f.add_button("Mult", mult, 100)

• f.add_button("Div", div, 100)

• f.add_input("Enter", enter, 100)

• # get frame rolling

• f.start()

Calculator• Lists can be constructed as a sequence of objects inside square brackets; e.g;

[2,4,6]. The list function also converts other types of sequence data such as strings into lists.

• Sequence operations such as indexing l[i], concatenation +, length len(l) and slicing apply to lists.

• As opposed to strings, an element of a list can be mutated via assignment l[i] = x.

Python on Windows

• Visit python.org/download/ and download the appropriate Python Windows installer.

• Python comes in two modern flavors, version 2 and version 3. In practice, almost everyone uses version 2.

• Install Wing 101, a free version of a more fully-featured IDE.

• Select IDLE to run the interactive Python Shell.• DOCUMENTATION STRINGS: Triple quotes signify a

multi-line string. Everything between the start and end quotes is part of a single string, including carriage returns, leading white space, and other quote characters.

Python on Windows

• Comments begin with #.• Everything in Python is an object, and everything can

have attributes and methods. All functions have a builtin attribute __doc__, which returns the docstring defined in the function’s source code.

• THE import SEARCH PATH:>>> import sys

• > cat hello.py print 'Hello world!' > python hello.py Hello world!

The Interactive Shell

• Type help() for interactive help (the prompt changes to help>), or help(object) for help about object.

• help> quit # leaves help and returns to the Python interpreter.• >>> 1 + 1

2>>> print 'hello world' hello world>>> x = 1>>> y = 2>>> x + y3

• All names in Python are case-sensitive • >>> mystr = "Hello, World!"

>>> print mystr >>> print len(mystr)

Indexing and Slicing• >>> mystr = "Dogs in outer space"• >>> print mystr[0] • D

• mystr = "Dogs in outer space" • print mystr[-1] # Get the last element of a string • print mystr[len(mystr)-1] • e • e • print mystr[1:3] • print mystr[3:] • print mystr[:-3] • og • s in outer space • Dogs in outer sp

Including Other Packages

• >>> import math• >>> print math.sin(math.pi)• 1.22464679915e-16

• to import something into your namespace:from math import * print sin(pi) 1.22464679915e-16

Objects and methods

• str = "THE World is A BIG and BEAUTIFUL place. " • print str.upper() • name = "Alex Storer" • print name.swapcase() • THE WORLD IS A BIG AND BEAUTIFUL PLACE. • aLEX sTORER

Declaring Functions • Note that the keyword def starts the function declaration, followed

by the function name, followed by the arguments in parentheses. Multiple arguments are separated with commas.

• def approximate_size(size, a_kilobyte_is_1024_bytes=True):• in Python, everything is a function• Python functions do not specify the datatype of their return value. • Every Python function returns a value; if the function ever executes

a return statement, it will return that value, otherwise it will return None, the Python null value.

• The argument, params, doesn't specify a datatype. In Python, variables are never explicitly typed.

• The second argument, a_kilobyte_is_1024_bytes, specifies a default value of True. This means the argument is optional; you can call the function without it.

Declaring Functions def square(num): return num * num

def convertTemp(temp, scale): if scale == "c": return (temp - 32.0) * (5.0/9.0) elif scale == "f": return temp * 9.0/5.0 + 32

def onePerLine(str): for i in str: print(i)

number = 12print(square(number))

temp = int(input("Enter a temperature: "))scale = input("Enter the scale to convert to: ")converted = convertTemp(temp, scale)print("The converted temp is: " + str(converted))

word = input("Enter a word: ")onePerLine(word)

Declaring Functions

• def buildConnectionString(params): """Build a connection string from a dictionary of parameters.

Returns string.""" • Everything between the triple quotes is the

function's doc string, which documents what the function does. A doc string, if it exists, must be the first thing defined in a function (that is, the first thing after the colon).

• The doc string is available at runtime as an attribute of the function.

The Interactive Shell

• >>> numbers =range(1,11)>>> for i in numbers:

print(i)

12345678910>>>

The Interactive Shell

• >>> sum = 0• >>> for i in numbers:• sum += I

• >>> print(sum)• 55• >>>

The Interactive Shell

• Python uses == for comparison and = for assignment.• if __name__ == '__main__':

print(approximate_size(1000000000000, False)) print(approximate_size(1000000000000))

• all modules have a built-in attribute __name__.• Since you run the module directly as a standalone

program, in which case __name__ will be a special default value, __main__.

DATATYPES• You don’t need to declare the datatype of variables.

Datatype is based on each variable’s original assignment.

• Booleans are either True or False.>>> flag = true # illegal in PythonTraceback (most recent call last): File "<pyshell#19>", line 1, in <module> flag = trueNameError: name 'true' is not defined

• >>> flag = 100 < 1

• >>> flatFalse

DATATYPES• booleans can be treated as numbers. True is 1; False is

0.• >>> True + True

2• >>> True – False

1• >>> True * False

0

DATATYPES• Numbers can be integers (1 and 2), floats (1.1 and 1.2), fractions

(1/2 and 2/3), or even complex numbers.• Python supports both integers and floating point numbers. There’s

no type declaration to distinguish them; Python tells them apart by the presence or absence of a decimal point.

• >>> type(1)<class 'int'>

• >>> isinstance(1, int)True

• >>> 1 + 1.02.0

• >>> type(2.0)<class 'float'>

DATATYPESJane Q Public 27

Jane Q Public 29

JQP

>>>

DATATYPES• >>> 11 // 2 # The // operator performs a quirky kind of integer

division. When the result is positive, truncating (not rounding) to 0 decimal places5

• >>> -11 // 2 # the // operator rounds down to the nearest integer-6

• >>> 11.0 // 2 # The // operator doesn’t always return an integer. If either the numerator or denominator is a float, it will still round to the nearest integer, but the actual return value will be a float.5.0

• >>> 11 ** 2• 121• >>> 11 % 2

1

DATATYPES• Strings are sequences of Unicode characters, e.g. an H T M L

document. Example:>>> str='string‘>>> str[0]'s‘>>> str[1:]'tring‘

• Mike’s should be >>> “Mike’s”• Bytes and byte arrays, e.g. a J P E G image file.• Tuples are ordered, immutable sequences of values.• Sets are unordered bags of values.

List and dictionary constructors• A list is an ordered list of any type of value, and it is constructed with

square brackets:mixed_list=['a', 3, 'c', 8]

• >>> number =[1,2,3,4]• >>> number[0] + number[2]

4• >>> len(number)

4• >>> string1=['a', 'b', 'c', 'd']• >>> string1[2:4]

['c', 'd']• >>> string1[1:]

['b', 'c', 'd']• >>> string1[0:2] # second index defaults to the size of the string being

sliced['a', 'b']

List and dictionary constructors• sorted(string1)• string1.sorted() # permanently change the list• S• string1.reverse()• string1.append(‘pete’) # append an item to the end of list• >>> string1.pop()

'pete'• >>> string1

['a', 'b', 'c', 'd']• >>> ind = string1.index('c')• >>> ind

2• >>> del string1[ind]• >>> string1

['a', 'b', 'd']

List and dictionary constructors• A dictionary is an unordered set of key/value pairs, similar to a hash

map in other languages. It is constructed with curly braces:>>> ages={'John':24,'Sarah':28,'Mike':31} # key:value pairs

• Not interested in order.• >>> ages['Sarah']

28• >>> len(ages)

3• >>> list(ages.keys())

['Sarah', 'Mike', 'John']• >>> list(ages.values())

[28, 31, 24]

List and dictionary constructors• >>> for name in ages.keys():

print(name + ' is ' + str(ages[name]) + ' years old.')• Sarah is 28 years old.

Mike is 31 years old.John is 24 years old.

• >>> print(ages.get('John'))24

• >>> ages['John'] = [34] # change value• >>> print(ages.get('John'))

[34]• >>> ages['Pete'] = 50 # add a new element to the dictionary• >>> ages

{'Sarah': 28, 'Pete': 50, 'Mike': 31, 'John': [34]}

List and dictionary constructors• >>> ages.pop('Pete') # remove Pete

50• >>> ages

{'Sarah': 28, 'Mike': 31, 'John': [34]}• >>> ages['Pete'] = [50, 60, 70]• >>> ages

{'Sarah': 28, 'Pete': [50, 60, 70], 'Mike': 31, 'John': [34]}

List comprehensions

• A list comprehension is a convenient way of converting one list to another by filtering and applying functions to it. A list comprehension is written as:[expression for variable in list] or:[expression for variable in list if condition]

• For example, the following code:l1=[1,2,3,4,5,6,7,8,9]print [v*10 for v in l1 if l1>4]would print this list:[50,60,70,80,90]

• The other manner in which they are often used is with the dict constructor:l1=[1,2,3,4,5,6,7,8,9]timesten=dict([(v,v*10) for v in l1])This code will create a dictionary with the original list being the keys and each item multiplied by 10 as the value:{1:10,2:20,3:30,4:40,5:50,6:60,7:70,8:80,9:90}

Significant Whitespace

• Unlike most languages, Python actually uses the indentation of the code to define code blocks. Consider this snippet:if x==1: print 'x is 1‘ print 'Still in if block‘print 'outside if block‘

• the first two print statements are executed when x is 1 because the code is indented.

• Indenting starts a block and unindenting ends it. • Indentation can be any number of spaces, whitespace is

significant, and must be consistent.• an if statement is followed by a code block. If the if expression

evaluates to true, the indented block is executed, otherwise it falls to the else block (if any).

Control statements – if .. else

num = 12denom = 0if denom != 0: print(num/denom)else: print('Division by zero!')

Control statements – if .. elif …else

grade = 99if grade >= 90: letterGrade = 'A'elif grade >= 80: letterGrade = 'B'elif grade >= 70: letterGrade = 'C'elif grade >= 60: letterGrade = 'D'else: letterGrade = 'F'print(letterGrade)

Control statements – while

number = 1while number < 11: print(number) number += 1

balance = 1000rate = 1.02years = 0while balance < 5000: balance *= rate years += 1print("It takes " + str(years) + " years to reach $5000.")>>> It takes 82 years to reach $5000.

Control statements – for

for i in [1,2,3,4,5,6,7,8,9,10]: print(i)

for name in ["Jane", "John", "Matt", "George"]: print(name)

for i in range(1,11): print(i)

Exceptions

• Usually it’s an error, an indication that something went wrong.• Python uses try...except blocks to handle exceptions, and the raise

statement to generate them. Example:if size < 0: raise ValueError('number must be non-negative')

• try: import chardetexcept ImportError: chardet = None

• try: from lxml import etreeexcept ImportError: import xml.etree.ElementTree as etree

Exceptions

• Python will not let you declare a variable that has never been assigned a value. Trying to do so will raise a NameError exception.

Object Oriented Programming

• Python will not let you declare a variable that has never been assigned a value. Trying to do so will raise a NameError exception.

Inheritanceclass Shape: # base class

def __init__(self, xcor, ycor): # ceate a constructor with a self object

self.x = xcor

self.y = ycor

def __str__(self):

return 'x: ' + str(self.x) + ' y: ' + str(self.y) # str method to locate the coordinates of self

def move(self, x1, y1):

self.x = self.x + x1

self.y = self.y + y1

class Rectangle(Shape): # derived class

def __init__(self, xcor, ycor, width, height):

Shape.__init__(self, xcor, ycor) # use base class method here (inheritance)

self.width = width

self.height = height

def __str__(self):

retStr = Shape.__str__(self)

retStr += ' width: ' + str(self.width) + ' height: ' + \

str(self.height)

return retStr

rec = Rectangle(5,10,8,9) # create a rectangle object rec

print(rec) # display rec

rec.move(10,12) # move rec

print(rec)

Writing to CSVimport csv

f = open('/tmp/blah.csv','w')

nums = [1,2,3]

c = csv.DictWriter(f,nums)

for i in range(0,10):

c.writerow(dict([(x, x**i) for x in nums]))

f.close()

This writes out the following csv file:

1,1,1

1,2,3

1,4,9

1,8,27

1,16,81

1,32,243

1,64,729

1,128,2187

1,256,6561

1,512,19683

File Objects

English Python Output

Open blah.txt just for reading f = open('blah.txt','r') file object f

Get the next line in a file str = f.readline()string containing a single line

Get the entire file str = f.read()string containing entire file

Go to the beginning of a file f.seek(0) None

Close blah.txt f.close() None

References

• A good starting point for finding more web sites with open APIs is ProgrammableWeb (http://www.programmableweb.com).