And Now For Something Completely Different A Quick Tutorial of the Python Programming Language - PowerPoint PPT Presentation

1 / 48
About This Presentation
Title:

And Now For Something Completely Different A Quick Tutorial of the Python Programming Language

Description:

A Quick Tutorial of the Python Programming Language. Michael Scherger ... Python Basics and Language Elements. September 1, 2004 ... – PowerPoint PPT presentation

Number of Views:85
Avg rating:3.0/5.0
Slides: 49
Provided by: michaels85
Category:

less

Transcript and Presenter's Notes

Title: And Now For Something Completely Different A Quick Tutorial of the Python Programming Language


1
And Now For Something Completely DifferentA
Quick Tutorial of the Python Programming Language
  • Michael Scherger
  • Department of Computer Science
  • Kent State University

2
Contents
  • Python Resources
  • Python Basics and Language Elements
  • Statements and Control Structures
  • Input, Output, and File Access
  • Functions
  • Classes and Objects

3
Python Resources
4
Python Resources
  • Python Web Site http//www.python.org
  • Check out the tutorial at http//www.python.org/d
    oc/tut
  • Download current stable version for your PC
    (version 2.3.4)

5
Running Python
  • PC
  • c\gtpython
  • Use Python GUI called IDLE
  • Linux
  • python
  • Mac version available

6
Running Python
7
Running Python
8
Python Basics and Language Elements
9
Numbers
  • Integers
  • Decimal
  • At least 32 bit
  • Octal and hexadecimal
  • Long integers
  • Limited by memory size
  • Trailing L
  • Floating point
  • Complex
  • Use j instead of i
  • Boolean
  • gtgtgt 11
  • 2
  • gtgtgt 11.0
  • 2.0
  • gtgtgt 11e0
  • 2.0
  • gtgtgt
  • gtgtgt 999999999999999
  • 999999999999999L
  • gtgtgt 9999999999999999999999999999
  • 9999999999999999999999999999L
  • gtgtgt99999999999999999999999999999999999999999
  • 99999999999999999999999999999999999999999L
  • gtgtgt
  • gtgtgt 17
  • 17
  • gtgtgt 021
  • 17
  • gtgtgt 0x11

10
Variables
  • Variables do not have types
  • You do not declare variables
  • They appear when you assign them
  • They disappear when you do not use them anymore
  • gtgtgt x 1 1
  • gtgtgt x
  • 2
  • gtgtgt x 1 1.0
  • gtgtgt x
  • 2.0
  • gtgtgt
  • gtgtgt y
  • Traceback (most recent call last)
  • File "ltpyshell20gt", line 1, in -toplevel-
  • y
  • NameError name 'y' is not defined
  • gtgtgt y None
  • gtgtgt y
  • gtgtgt y None
  • True
  • gtgtgt del y
  • gtgtgt y

11
Lists
  • Pythons array like object is a list
  • Uses
  • Subscripted like arrays in C (zero based)
  • Mutable
  • Use len(L) to get the length of the list
  • gtgtgt z 4, 5, 6
  • gtgtgt z1
  • 5
  • gtgtgt z1 7
  • gtgtgt z
  • 4, 7, 6
  • gtgtgt len( z )
  • 3
  • gtgtgt

12
Lists
  • Indexing
  • Uses bracket notation
  • Indexes start at 0can have a negative index
  • name Cleese, John example of strings in
    a list
  • print name1, name0 prints John Cleese
  • name0 Smith
  • x1,2,3,y,z, example of lists in a
    list

0
1
2
3
4
A
B
C
D
E
-1
-5
-4
-3
-2
13
Lists
  • Slicing is similar to indexing except you
    indicate both the start and stop index separated
    by a colon
  • x "spam1","spam2","spam3","spam4","spam5","eggs
    ","and","spam6"
  • print x57 Prints the list "eggs","and"

0
1
2
3
4
5
A
B
C
D
E
-6
-1
-5
-4
-3
-2
14
Lists
  • More on slicing
  • x "spam1","spam2","spam3","spam4","spam5","eggs
    ","and","spam6"
  • x3 prints spam1, spam2, spam3
  • x3 prints spam4, spam5,
    eggs,and,spam6
  • x prints all of it!

15
List Methods
  • append() add an element to the end of the
    list
  • pop() remove an element from the end of a
    list
  • insert() add an element anywhere in the
    list
  • and list concatenation and replication
  • And a whole bunch morelook them up!

16
Strings
  • A string is a sequence of characters between
    quotes either or
  • There is no character data type in Pythononly
    string
  • Strings are not arrays of characters as in C/C!
  • Use subscript notation to read individual
    characters as a string
  • Strings are immutable
  • Use len(S) to get the length of the string
  • gtgtgt x "abc"
  • gtgtgt x0
  • 'a'
  • gtgtgt len(x)
  • 3
  • gtgtgt x0 'd'
  • Traceback (most recent call last)
  • File "ltpyshell34gt", line 1, in -toplevel-
  • x0 'd'
  • TypeError object doesn't support item assignment
  • gtgtgt

17
Converting Values
  • String values can be converted to integers using
    the int() function
  • String values can be converted to floating points
    using the float() function
  • Ints and floats can be converted to string values
    str() function
  • Example
  • x int( 10 )
  • y float( 10)
  • yy float (10)
  • Z str(3.14159)

18
String Methods
  • upper() Returns the uppercase version of the
    string
  • lower() Returns the lowercase version of the
    string
  • swapcase() Returns a new string where the case
    of each letter is switched
  • capitalize() Returns a new string with the first
    letter capitalized and the remaining letters
    are in lowercase
  • title() Returns a new string with the first
    letter of each word capitalized and all other
    letters are in lower case
  • strip() Returns a new string with leading and
    trailing white space removed.
  • replace( old, new, ,max) Returns a new string
    where occurrences of the string old are
    replaced by new up to max number of times

19
Tuples
  • Tuples are like lists
  • Immutable
  • Use ( ) notation instead of s for creation
  • Uses notation for indexing and slicing
  • gtgtgt x (1, "Mike", 2, Laurie", 3, "Sarah")
  • gtgtgt x
  • (1, 'Mike', 2, 'Laurie', 3, 'Sarah')
  • gtgtgt x1 'Michael'
  • Traceback (most recent call last)
  • File "ltpyshell46gt", line 1, in -toplevel-
  • x1 'Michael'
  • TypeError object doesn't support item assignment
  • gtgtgt

20
Dictionaries
  • Dictionaries are unordered lists
  • Associative array/list or table or map
  • List of key/value pairs
  • Use key to look up the element or value
  • person 'first name' "Robin",
  • 'last name "Hood",
  • 'occupation' "Scoundrel"
  • personlast name of Locksley

21
Dictionary Methods
  • keys() returns a list of keys
  • values() returns a list of values
  • items() returns a list of key value pairs
  • has_key() tests if a key exists
  • And a whole bunch morelook them up!

22
Assignments
  • Assignment uses
  • Equality uses
  • Not Equal uses ! or ltgt
  • x, y, z 1, 2, 3
  • first, second second, first
  • a b 123

23
Other Assignment Operators
  • Augmented assignment operators
  • A combination of assignment and a mathematical
    operation
  • x 5 x x 5
  • / x / 5 x x / 5
  • x 5 x x 5
  • x 5 x x 5
  • - x - 5 x x - 5

24
Logical Values
  • Python 2.3 has a Boolean type
  • Prior versions do not
  • False is zero or empty
  • True is not False (non-zero or not empty)
  • And, Or, Not are short-circuited
  • Can do lexicographic comparison of sequences
    (lists, strings, tuples)
  • 1 lt 2 True
  • 1 gt 2 False
  • 1,2 lt 3,4 False
  • 1,2 1,2 True
  • ab a b True
  • (1,2) 1,2 False
  • not True
  • not 1,2,3 False
  • not True
  • not ab False

25
Statements and Control Structures
26
Blocks
  • Blocks are indicated using indentation only
  • No BEGIN/END or
  • if x lt 5 or (x gt 10 and x lt 20)
  • print The value is OK.
  • if x lt 5 or 10 lt x lt 20
  • print The value is OK.

27
If-Elif-Else
  • if color Green
  • do_green_function()
  • elif color Blue
  • do_blue_function()
  • elif color Red
  • do_red_function()
  • else
  • report_error()

28
While Loops
  • Example of a while loops
  • x 10
  • while x gt 0
  • print x is still negative.
  • x x-1

29
For Loops
  • To make an ordinary for loop use the built-in
    function range()
  • Print out the values from 0
  • to 99 inclusive
  • for value in range(100)
  • print value

30
For Loops
  • More examples of for loops
  • print values in a list
  • for value in 1, 2, 3, 4, 5, 4, 3, 2, 1
  • print value
  • print 10 thru 19
  • for value in range(10,20)
  • print value
  • print 10 12 14 16 18
  • for value in range(10, 20, 2)
  • print value

31
Input, Output, and File Access
32
Getting User Input
  • The raw_input function returns a string.
  • Be careful!
  • 10 is not the same as 10
  • Other functions convert strings to integers and
    vice versa.
  • Example Personal Greeter

33
A Tiny Algorithm
  • Prompt user for a number
  • Print out the square of the number
  • x input( Please enter a number )
  • print The square of that number is, x x
  • Could also use
  • x raw_input( Please enter a number )
  • x int(x)
  • print The square of that number is, x x

34
File Input / Output
  • Example
  • filespec open( somefile, r )
  • s filespec.readline() read one line
  • s filespec.readlines() read all lines
  • filespec.close()

35
File Input / Output
  • Example
  • filespec open( somefile, w )
  • filespec.writeline(s) write one string
  • filespec.readlines(l) write string list
  • filespec.close()

36
Functions
37
Functions
  • Use the keyword def
  • Passing parameters
  • Named arguments
  • Default values
  • Variable scoping
  • def square(x)
  • return xx
  • print square(2) prints out 4

38
Functions
  • When you pass a parameter to a function, you bind
    the parameter to the value
  • Creates a new reference
  • def change(some_list)
  • some_list1 4
  • x 1,2,3
  • change(x)
  • print x Prints out 1,4,3

39
Functions
  • Another example
  • def nochange(x)
  • x 0
  • y 1
  • nochange(y)
  • print y Prints out 1
  • Example Balanced Parentheses and Fibonocci
    Numbers

40
Functions
  • Example
  • gtgtgtdef sumdif(a, b)
  • return ab, a-b
  • gtgtgtsumdif( 5, 7 )
  • (12,2)
  • gtgtgt

41
Putting It All Together
  • Write a Python version of wc (word count)
  • Writes the counts of the number of characters,
    words, and lines in a file
  • Algorithm
  • open the file
  • count the characters, words, and lines
  • write out the counts
  • close the file
  • Example wc
  • python wc.py somefile.ext

42
Classes and Objects
43
Classes and Objects
  • class Basket
  • def __init__(self, contentsNone)
  • self.contents contents or
  • def add(self, element)
  • self.contents.append(element)
  • def print_me(self)
  • result
  • for element in self.contents
  • result result element
  • print Contains result

44
Classes and Objects
  • All methods (functions in an object) received an
    additional argument at the start of the argument
    list containing the object itself. (Called self
    which is customary)
  • Methods are called like this object.method(
    arg1, arg2)
  • Some method names, like __init__ (two underscores
    on each side), are predefined and mean special
    things (constructor)
  • Some arguments are optional and given and default
    value
  • Short circuit evaluation and assignment
  • Backquotes convert an object to its string
    representation
  • Addition sign () is used for string concatenation

45
Classes and Objects
  • Instead of short circuit to assign contentscould
    have written the statement like this
  • if contents
  • self.contents contents
  • else
  • self.contents
  • def __init__(self,contents)
  • self.contents contents

46
Classes and Objects
  • To create an instance of a class (object)
  • a Basket()
  • b Basket( apple, lemon)
  • b.add( orange )
  • b.print_me()

47
Classes and Objects
  • Convert object to string
  • Use the __str__ method
  • def __str__(self)
  • result
  • for element in self.contents
  • result result element
  • return Contains result

48
Classes and Objects
  • Example Basket Class
  • gtgtgt b Basket()
  • gtgtgt b
  • lt__main__.Basket instance at 0x00A09B98gt
  • gtgtgt print b
  • Contains
  • gtgtgt b.add( "Foo" )
  • gtgtgt print b
  • Contains 'Foo'
  • gtgtgt b.add ("Foo", "Bar")
  • gtgtgt b.print_me()
  • Contains 'Foo' 'Foo', 'Bar'
  • gtgtgt b.add ((1,2,3))
  • gtgtgt print b
  • Contains 'Foo' 'Foo', 'Bar' (1, 2, 3)
  • gtgtgt
Write a Comment
User Comments (0)
About PowerShow.com