Title: Introduction to PYTHON
1Introduction to PYTHON
2Introduction to Python
- Python is a high-level programming language
- Open source and community driven
- Standard distribution includes many modules
- Dynamic typed
- Source can be compiled or run just-in-time
- Similar to perl, tcl, ruby
3Introduction to Python contd
- Interpreted scripting language
- Object Oriented
- No pointers garbage collection
- Exception handling stack trace for each error
- Syntax features for manipulating lists (lists,
dictionaries, sets, list comprehensions, etc.) - Uses indentation instead of brackets for grouping
blocks
4More definition
- Python is cross platform (for many platforms).
- The standard library is huge, very useful, and is
very well documented. - http//docs.python.org/library/
- Many companies make significant use of it
- Google uses it for a lot of their internal
software projects - NASA is using Python to implement a system which
will be the core infrastructure for its next
generation collaborative engineering environment
5Features of Python
- A script language
- Interpreted
- No compile/link stage
- Write and run
- Slow compared to C, C
- Elegant design tight
- Designed for
- Quick-and-dirty scripts
- Reusable modules
- Very large systems
- Object-oriented
- Very well-designed
- But you dont have to use it
6Why scripting instead of C/Assembly?
- For performance critical computations (graphics,
networking), optimized code (C/Assembly)
outperforms script/interpreted languages - Video games often require code for Business
Logic - Coordinating components
- Glue logic
- Artificial intelligence
7Why scripting instead of C/Assembly?
- The priorities of this business logic are
mostly - Development time (Time to write code)
- Coding/output latency (Good for troubleshooting)
- Readability
- Reusability
- Maintenance
- Scripting/interpreted language is often preferred
for this case
8Python Interfaces
- IDLE a cross-platform Python development
environment - PythonWin a Windows only interface to Python
- Python Shell running 'python' from the Command
Line opens this interactive shell - For the exercises, we'll use IDLE, but you can
try them all and pick a favorite
9IDLE Development Environment
- IDLE helps you program in Python by
- color-coding your program code
- debugging
- auto-indent
- interactive shell
10General Information
11Objects All the Way Down
- Everything in Python is an object
- Integers are objects.
- Characters are objects.
- Complex numbers are objects.
- Booleans are objects.
- Functions are objects.
- Methods are objects.
- Modules are objects
12Variables
- No need to declare
- Need to assign (initialize)
- use of uninitialized variable raises exception
- Not typed
- if friendly greeting "hello world"
- else greeting 122
- print greeting
- Everything is a "variable"
- Even functions, classes, modules
13Reference Semantics
- Assignment manipulates references
- x y does not make a copy of y
- x y makes x reference the object y references
- Very useful but beware!
- Example
- gtgtgt a 1, 2, 3
- gtgtgt b a
- gtgtgt a.append(4)
- gtgtgt print b
- 1, 2, 3, 4
14Changing a Shared List
a 1, 2, 3
b a
a
1
2
3
4
a.append(4)
b
15Indentation and Blocks
- Python uses whitespace and indents to denote
blocks of code - Lines of code that begin a block end in a colon
- Lines within the code block are indented at the
same level - To end a code block, remove the indentation
- You'll want blocks of code that run only when
certain conditions are met
16Whitespace
- Whitespace is meaningful in Python especially
indentation and placement of newlines. - Use a newline to end a line of code.
- Use \ when must go to next line prematurely.
- No braces to mark blocks of code in Python
Use consistent indentation instead. - The first line with less indentation is outside
of the block. - The first line with more indentation starts a
nested block - Often a colon appears at the start of a new
block. (E.g. for function and class
definitions.)
17Comments
- Start comments with the rest of line is
ignored. - Can include a documentation string as the first
line of any new function or class that you
define. - The development environment, debugger, and other
tools use it its good style to include one. - def my_function(x, y)
- This is the docstring. This function does
blah blah blah. The code would go here...
18None
- None represents the lack of a value.
- Like NULL in some languages or in databases.
- For instance
- gtgtgt if y!0... fraction x/y... else...
fraction None
19Introduction to Attributes
- Attributes are bits of information attached to
objects. - gtgtgt x complex(3, 5)gtgtgt x.real3.0gtgtgt x.imag5
.0
20Introduction to Methods
- Methods are behaviours associated with objects.
- gtgtgt x complex(3,5) gtgtgt x (35j)
gtgtgt x.conjugate() (3-5j)
21Basic Data Types
22Data Type
- Boolean
- Integer
- Floating
- Character
- String
- Lists
- Dictionaries
- Tuples
23Booleans
- True and False are the only values of type
bool. - True can be treated as 1 and False as 0 in
mathematical expressions - gtgtgt print TrueTrueTrue-False3gtgtgt print False
0True
24Basic Data Types
25Numbers
- The usual suspects
- 12, 3.14, 0xFF, 0377, (-12)3/45, abs(x),
0ltxlt5 - C-style shifting masking
- 1ltlt16, x0xff, x1, x, xy
26Strings
- "hello""world" "helloworld" concatenation
- "hello"3 "hellohellohello" repetition
- "hello"0 "h" indexing
- "hello"-1 "o" (from end)
- "hello"14 "ell" slicing
- len("hello") 5 size
- "hello" lt "jello" 1 comparison
- "e" in "hello" 1 search
- "escapes \n etc, \033 etc, \if etc"
- 'single quotes' """triple quotes""" r"raw
strings"
27Lists
- Think of a list as a stack of cards, on which
your information is written - The information stays in the order you place it
in until you modify that order - Methods return a string or subset of the list or
modify the list to add or remove components - Written as varindex, index refers to order
within set (think card number, starting at 0) - You can step through lists as part of a loop
28List Methods
- Adding to the List
- varn object
- replaces n with object
- var.append(object)
- adds object to the end of the list
- Removing from the List
- varn
- empties contents of card, but preserves order
- var.remove(n)
- removes card at n
- var.pop(n)
- removes n and returns its value
29Lists
30Tuples
- Like a list, tuples are iterable arrays of
objects - Tuples are immutable once created, unchangeable
- To add or remove items, you must redeclare
- Example uses of tuples
- County Names
- Land Use Codes
- Ordered set of functions
31Tuples
- key (lastname, firstname)
- point x, y, z parentheses optional
- x, y, z point unpack
- lastname key0
- singleton (1,) trailing comma!!!
- empty () parentheses!
- tuples vs. lists tuples immutable
32Tuples
33Dictionaries
- Dictionaries are sets of key value pairs
- Allows you to identify values by a descriptive
name instead of order in a list - Keys are unordered unless explicitly sorted
- Keys are unique
- varitem apple
- varitem banana
- print varitem prints just banana
34Dictionaries
- Hash tables, "associative arrays"
- d "duck" "eend", "water" "water"
- Lookup
- d"duck" -gt "eend"
- d"back" raises KeyError exception
- Delete, insert, overwrite
- del d"water" "duck" "eend", "back" "rug"
- d"back" "rug" "duck" "eend", "back"
"rug" - d"duck" "duik" "duck" "duik", "back"
"rug"
35Dictionary Details
- Keys must be immutable
- numbers, strings, tuples of immutables
- these cannot be changed after creation
- reason is hashing (fast lookup technique)
- not lists or other dictionaries
- these types of objects can be changed "in place"
- no restrictions on values
- Keys will be listed in arbitrary order
- again, because of hashing
36Dictionaries
37Basic Functions
38Boolean 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 ltgt B
!A not A
- Relational operators are all the same
- 5 lt 6
- Boolean values
- True (case sensitive)
- False
39Mathematical Functions
- abs(x) absolute value
- divmod(a, b) - divide a by b and return both the
quotient and the remainder - hex( x) - Convert an integer number (of any size)
to a hexadecimal string. - oct( x) - Convert an integer number (of any size)
to an octal string. - round( x, n) - Return the floating point value
x rounded to n digits after the decimal point.
40List Operations
Operator Meaning
ltseqgt ltseqgt Concatenation
ltseqgt ltint-exprgt Repetition
ltseqgt Indexing
len(ltseqgt) Length
ltseqgt Slicing
for ltvargt in ltseqgt Iteration
ltexprgt in ltseqgt Membership (Boolean)
41List Operations
Method Meaning
ltlistgt.append(x) Add element x to end of list.
ltlistgt.sort() Sort (order) the list. A comparison function may be passed as a parameter.
ltlistgt.reverse() Reverse the list.
ltlistgt.index(x) Returns index of first occurrence of x.
ltlistgt.insert(i, x) Insert x into list at index i.
ltlistgt.count(x) Returns the number of occurrences of x in list.
ltlistgt.remove(x) Deletes the first occurrence of x in list.
ltlistgt.pop(i) Deletes the ith element of the list and returns its value.
42Function Definition
43Functions
- Function syntax consist of
- The def keyword
- Function name
- Parenthesis with arguments separated by commas
- Sequence of statements with an indentation higher
than the function definition statement - gtgtgt def my_function(x)
- ... x 5
- ... print "X ", x
44Functions
- Python separates memory for this sequence of
statements and gives the pointer to the variable
given in the function definition - Printing the variable containing the pointer
(my_function) will print the pointer value - Parenthesis (with all needed arguments) are
needed to deference the pointer - gtgtgt my_function
- ltfunction my_function at 0x00ABDAF0gt
- gtgtgt my_function(10)
- 10
45Functions, Procedures
- def name(arg1, arg2, ...)
- """documentation""" optional doc string
- statements
- return from procedure
- return expression from function
46Example Function
- def gcd(a, b)
- "greatest common divisor"
- while a ! 0
- a, b ba, a parallel assignment
- return b
- gtgtgt gcd.__doc__
- 'greatest common divisor'
- gtgtgt gcd(12, 20)
- 4
47Default Values
- Parameters can have default values
- def box(width, height,depth0) ...do something .
..box(10, 10, 20)box(10, 10, 0)box(10, 10) s
ame as above
48Functions inner block indentation
- Is a good habit to be consistent with the
indentation per level to avoid Python compiler
errors - Level 1 3 spaces, level 2 6 spaces, level 3
9 spaces, etc. - Tabs are not recommended, because they are
interpreted differently between text editors and
operating systems
49Functions Scope
- You can not modify a variable of an outer scope,
because the Python interpreter will think that it
is a local variable and will create a new
variable instead - This can be avoided by using dot notation on an
outside module or object (more on this later) - gtgtgt y 3
- gtgtgt def foo()
- ... y 2
- ... print "Y ", y
- gtgtgt foo() Prints 2
- gtgtgt print "Y ", y Prints 3
50Functions Return value
- Functions can have a return statement to
terminate the execution of a function and return
a value - If no return statement is given, Python will
return None when after executing the last
statement of a function - gtgtgt def foo(x) x x 1
- gtgtgt print foo(5)
- None
- gtgtgt if foo(5)
- ... print "Impossible..."
- ... else
- ... print "None is like null in Java
- None is like null in Java
51Basic Flow Control
52Basic Flow Control
- if/elif/else (test condition)
- while (loop until condition changes)
- for (iterate over iteraterable object)
- Range
- Loop control statements
53IF Statement
- if j"Hello" doSomething()elif j"World"
doSomethingElse()else doTheRightThing()
54WHILE Statement
- str""while str!"quit" str
input() print (str)print ("Done)
55Looping Forever
- Use a value that will always be true to loop
until a break. - while True
- string input()
- if stringexit
- break
- print (string)
- print ("Done)
56FOR Statement
- myList "a", "b", "c", "d", "e"for i in myLis
t print ifor i in range( 10 )
print ifor i in range( len( myList ) )
if myListi"c" myListiNone
- Can break out of for-loops.
- Can continue to next iteration.
57Range function
- Creates a list of integer values usually used to
iterate in a for loop - range(n) will give 0, 1, 2, ., (n 2), (n
1) - Starting value and increment/decrement can be
provided - These features allows to do any type of iteration
as a C for statement would allow
58Range function
- range(a, b, c)
- a Starting value, default value is 0
- b Terminating condition, must always be given
- c Increment/decrement, default value is 1
- Equivalent in C to
- for(int x b x lt a x c)
-
59Range function
- The len and range functions can be combined to
get the index value of a list while iterating
through it - gtgtgt range(10)
- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
- gtgtgt range(5, 10)
- 5, 6, 7, 8, 9
- gtgtgt range(1, 10, 2)
- 1, 3, 5, 7, 9
- gtgtgt for i in range(len(a))
- ... print i, ai
60Loop Control Statements
break Jumps out of the closest enclosing loop
continue Jumps to the top of the closest enclosing loop
pass Does nothing, empty statement placeholder
61Break and Continue Statement
- Break and continue work like in C/Java
- break statement allows you to jump out of the
middle of a loop - The continue statement is a short-cut way of
jumping to the top of the loop - For/While loops can have else statement
- Runs at the end of the for/while loop
- Break skips else statement, continue does not
- gtgtgt for i in range(10)
- ... if i 9 continue
- ... else
- ... print "bye Bye is printed
- gtgtgt for i in range(10)
- ... if i 9 break
- ... else
- ... print "bye Bye is not printed
62Pass Statement
- Is used to make the Python compiler happy when
you want an empty function or class - gtgtgt for i in range(10)
- ... pass
- ... Do nothing
- ...
- gtgtgt class DummyClass
- ... pass
63Task
64Tasks
- Factorial
- Write a function fact that calculates factorial
of N. - Fibonacci series
- Write a function fib that calculates the
Fibonacci series till N.
65Importing and Modules
66Importing and Modules
- Use classes functions defined in another file.
- A Python module is a file with the same name
(plus the .py extension) - Like Java import, C include.
- Three formats of the command
- import somefile
- from somefile import
- from somefile import className
- Whats the difference? What gets imported from
the file and what name refers to it after it has
been imported.
67import
- import somefile
- Everything in somefile.py gets imported.
- To refer to something in the file, append the
text somefile. to the front of its name - somefile.className.method(abc)
- somefile.myFunction(34)
68Commonly Used Modules
- Some useful modules to import, included with
Python - Module sys - Lots of handy stuff.
- Maxint
- Module os - OS specific code.
- Module os.path - Directory processing.
69More Commonly Used Modules
- Module math - Mathematical code.
- Exponents
- sqrt
- Module Random - Random number code.
- Randrange
- Uniform
- Choice
- Shuffle