introduction to python lecture 1. cs 484 – artificial intelligence2 big picture language features...

25
Introduction to Python Lecture 1

Upload: henry-harper

Post on 11-Jan-2016

226 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language

Introduction to Python

Lecture 1

Page 2: Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language

CS 484 – Artificial Intelligence 2

Big Picture Language Features

• Python is interpreted• Not compiled

• Object-oriented language• There are no declarations of variables

• Variables take a retain the type of the data assigned to it

• Whitespace is used as delimiters• no main method

Page 3: Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language

CS 484 – Artificial Intelligence 3

First Statement

• Hello World>>> print 'Hello World!'• Usually double and single quotes can be used

interchangeably• A string in double quotes cannot contain a "

• A string in single quotes cannot contain a '

• Put strings in """ if you need both or newlines

Try: outputting Hello World on two lines

Page 4: Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language

CS 484 – Artificial Intelligence 4

Python Calculator

• You can print the results of expressions (variables and functions)>>> print 6 + 5

>>> print ((8 % 3) ** (7 / 3)) * ( 5 – 1)

• Integer vs. Floating point division>>> print 15 / 4

>>> print 15 / 4.0

Page 5: Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language

CS 484 – Artificial Intelligence 5

Using Formatted Strings

• Combining strings and numbers>>> print 'The total is ', 24+53

• Combining strings with many numbers>>> print "The sum of %d and %d is %d" % (7, 18, (7 + 18))

• Just like printf in C, other example codes• %s – String• %x – Hexadecimal• %0.2f – A real number with two figures following the decimal

point• %4d – Leading spaces to pad the number to at least 4 digits• %04d – Leading 0's to pad the number to at least 4 digits

Page 6: Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language

CS 484 – Artificial Intelligence 6

Other important features

• Comments begin with a #>>> print 7 + 5 # This should print 12

• Making use of libraries or other functions and methods you have written>>> import sys

>>> sys.exit()

>>> from random import *

>>> from pyrobot.brain import Brain

Page 7: Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language

CS 484 – Artificial Intelligence 7

Python Error Messages

>>> print 'fred' + 7Traceback (innermost last):File "<stdin>", line 1, in ?

TypeError: cannot concatenate 'str' and 'int' objects

• Errors only reported when line is encountered• Python's error messages are often wrong

• Inspect the line of the error and a few above

Page 8: Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language

CS 484 – Artificial Intelligence 8

Variables

• Variables are not declared• Can change types with new assignments>>> q = 7 # q is currently a number

>>> print q

>>> q = 'Seven' # q is reassign to a string

>>> print q

Page 9: Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language

CS 484 – Artificial Intelligence 9

String Operators

• + operator: String Concatenation>>> print 'Again' + ' and again'

• * operator: String repetition>>> print 'repeat ' * 3

• Combining operators>>> print 'Again' + (' and again' * 3)

• String methods are documented here http://docs.python.org/lib/string-methods.html

Page 10: Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language

CS 484 – Artificial Intelligence 10

Boolean Operators

C/Java Operator

Python

Operator

A && B A and B

A || B A or B

A == B A == B

A != B A != B

A <> B

!A not A

• Relational operators are all the same• 5 <= 6

• Boolean values• True (case sensitive)

• False

Try print ((5 <= 6) == true)

Page 11: Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language

CS 484 – Artificial Intelligence 11

Lists

• A sequence of items• Has the ability to grow (unlike array)• Use indexes to access elements (array notation)• examples

aList = []another = [1,2,3]

• You can print an entire list or an elementprint anotherprint another[0]

• index -1 accesses the end of a list

Page 12: Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language

CS 484 – Artificial Intelligence 12

List operation• append method to add elements (don't have to be the same type)

aList.append(42)aList.append(another)

• del removes elementsdel aList[0] # removes 42

• Concatenate lists with +• Add multiple elements with *

zerolist = [0] * 5• Multiple assignments

point = [1,2]x , y = point

• More operations can be found at http://docs.python.org/lib/types-set.html

Page 13: Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language

CS 484 – Artificial Intelligence 13

Control Statements

• Conditionalsif <condition>:<tab><statement(s)>elif <condition>:<tab><statement(s)>else:<tab><statement(s)>• Example:

name = "Jane"if "a" in name:

print "There is an 'a'"else:

print "There is not an 'a'"

• There is no switch statement

Page 14: Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language

CS 484 – Artificial Intelligence 14

Control Statements

• Loopswhile <condition>:<tab><statement(s)>for <var> in range(i,j): # up to but # not including j<tab><statement(s)>• Example:

name = "Jane"for c in name:print c

• no do while loops

Page 15: Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language

CS 484 – Artificial Intelligence 15

Interacting with user

• Obtaining data from a user• Use function raw_input for strings or input for numbers• Example

name = raw_input("What's your name?")

• Command Line arguments• Example:

import sysfor item in sys.argv:print item

• Remember sys.argv[0] is the program name

Page 16: Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language

CS 484 – Artificial Intelligence 16

Defining New Functions

• Syntaxdef <function name>(<argument list>):<tab><statements>

• Remember there is not type checking• Function may or may not return something

• Exampledef times(n):for i in range(1,13): print "%2d x %2d = %3d" % (i, n, i*n)

Page 17: Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language

CS 484 – Artificial Intelligence 17

Classes• Begin with header line

class <className>:• Constructor and methods

• tabbed over once• first argument is "self"

• Constructordef __init__(self, <other arguments>):<tab><statement(s)>

• Methodsdef <method name> (self, <other arguments>):<tab><statement(s)>

• Class variablesself.<variable name>

Page 18: Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language

CS 484 – Artificial Intelligence 18

Example Class

class Message:

def __init__(self, aString):

self.text = aString

def printIt(self):

print self.text

def getMessage(self):

return self.text Use:from Message import *

msg = Message("hi")msg.printIt()

Use:from Message import *

msg = Message("hi")msg.printIt()

Page 19: Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language

CS 484 – Artificial Intelligence 19

Using Files• Function open opens a file in the mode specified by the argument

<file handle> = open(<file name>, <mode>)• file name is a string with path and name of the file• Possible modes

• "r" to read• "w" to write• "rb" to read a binary file• "wb" to write a binary file

• Exampleinput = open("myFile.txt", "r")output = open("copy.txt", "w")for line in input.readlines(): output.write(line)input.close()output.close()

Page 20: Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language

CS 484 – Artificial Intelligence 20

Sample Program# file: createDict.py# by: Dawn Lawrie# date: September 8, 2005

# Reads the standard dictionary and creates a simpler# dictionary that only includes words in all lowercase letters# without aprostrophes

# Opens the input and output filesinput = open("/usr/share/dict/american-english", "r")output = open("simpleDict", "w")

# Reads each lines of the dictionaryfor line in input.readlines(): # Assumes that the word should not be in the simpler # dictionary good = False

Page 21: Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language

CS 484 – Artificial Intelligence 21

Sample Program # Accepts the word if it contains at least one lowercase # letter lowercase = "abcdefghijklmnopqrstuvwxyz" for c in lowercase: if not good and c in line: good = True

# Rejects the word if there is an apostrophe if "'" in line: good = False

# Rejects the word if it contains a uppercase letter if good: caps = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for c in caps: if good and c in line: good = False

Page 22: Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language

CS 484 – Artificial Intelligence 22

Sample Program con't

# Outputs the word if it is acceptable

if good:

output.write(line)

Page 23: Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language

CS 484 – Artificial Intelligence 23

Using String Methods# file: createDict2.py# by: Dawn Lawrie# date: September 8, 2005

… code the opens files has been removed

# Reads each lines of the dictionaryfor line in input.readlines(): # Removes all leading and trailing whitespace word = line.strip()

# Outputs the word if all the characters are alphabetic # and they are all lowercase if word.isalpha() and word.islower(): output.write(word + "\n")

Page 24: Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language

CS 484 – Artificial Intelligence 24

Pitfalls

• My common mistakes• Forgetting ":" in a condition or loop especially after

else• Emacs helps because it won't tab over

• Forgetting "self" before class variables• Without it python creates a new variable

• Forgetting the return statement• This turned up as a type mismatch when I tried to use the

results of the function which I had stored in another variable (Very Confusing)

Page 25: Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language

CS 484 – Artificial Intelligence 25

Lab Exercise

• Write a program in python that plays hangman