I PYTHON NTRODUCTION TO Sajid Gul Khawaja

Download Report

Transcript I PYTHON NTRODUCTION TO Sajid Gul Khawaja

INTRODUCTION TO PYTHON
Sajid Gul Khawaja
INTRODUCTION 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

Artificial Intelligence
2
INTRODUCTION 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

Artificial Intelligence
3
MORE DEFINITION



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
4
Artificial Intelligence

Python is cross platform (for many platforms).
The standard library is huge, very useful, and is very
well documented.
FEATURES OF PYTHON




Artificial Intelligence

o Useful error messages
o Automatic memory handling
o Independent of operating
 No compile/link stage
system
 Write and run
• Works on both Unix and
 Slow compared to C, C++
Windows
Elegant design; “tight”
• Even file system code can
Designed for
be made os-independent
 Quick-and-dirty scripts
o Large library of standard
 Reusable modules
modules
 Very large systems
o Large number of third-party
Object-oriented
modules
 Very well-designed
 But you don’t have to use it o Integration with external C
code
o Well documented
A script language
Interpreted
5
WHY 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”

Artificial Intelligence
Coordinating components
 Glue logic
 Artificial intelligence

6
WHY 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

Artificial Intelligence
7
PYTHON 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

Artificial Intelligence
8
IDLE – DEVELOPMENT ENVIRONMENT

IDLE helps you
program in Python by:
Artificial Intelligence
color-coding your
program code
 debugging
 auto-indent
 interactive shell

9
GENERAL INFORMATION
OBJECTS 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

Artificial Intelligence
11
VARIABLES
No need to declare
 Need to assign (initialize)


use of uninitialized variable raises exception
Not typed
if friendly: greeting = "hello world"
else: greeting = 12**2
print greeting

Artificial Intelligence

Everything is a "variable":

Even functions, classes, modules
12
REFERENCE SEMANTICS

Assignment manipulates references
x = y does not make a copy of y
 x = y makes x reference the object y references

>>> a = [1, 2, 3]
>>> b = a
>>> a.append(4)
>>> print b
[1, 2, 3, 4]
Artificial Intelligence
Very useful; but beware!
 Example:

13
CHANGING A SHARED LIST
a = [1, 2, 3]
a
2
3
1
2
3
1
2
3
Artificial Intelligence
1
a
b=a
b
a
a.append(4)
b
4
14
INDENTATION 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

Artificial Intelligence
15
WHITESPACE


Use \ when must go to next line prematurely.
No braces { } to mark blocks of code in Python…
Use consistent indentation instead.
Artificial Intelligence
Whitespace is meaningful in Python: especially
indentation and placement of newlines.
 Use a newline to end a line of code.
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.)
16
COMMENTS


def my_function(x, y):
“““This is the docstring. This
function does blah blah blah.”””
# The code would go here...
Artificial Intelligence

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: it’s good style to include one.
17
NONE
 “None”
Artificial Intelligence
represents the lack of a value.
 Like “NULL” in some languages or in
databases.
 For instance:
>>> if y!=0:
... fraction = x/y
... else:
... fraction = None
18
BASIC DATA TYPES
DATA TYPE
Boolean
 Integer
 Floating
 Character
 String
 Lists
 Dictionaries
 Tuples

Artificial Intelligence
22
BOOLEANS
True and False are the only values of type “bool”.
 True can be treated as “1” and False as “0” in
mathematical expressions:

Artificial Intelligence
>>> print True+True+True-False
3
>>> print False==0
True
23
BASIC DATA TYPES
Artificial Intelligence
24
NUMBERS
 The
12, 3.14, 0xFF, 0377, (-1+2)*3/4**5, abs(x), 0<x<=5
 C-style

shifting & masking
1<<16, x&0xff, x|1, ~x, x^y
Artificial Intelligence

usual suspects
25
STRINGS
"hello"+"world" "helloworld" # concatenation
 "hello"*3
"hellohellohello" # repetition
 "hello"[0]
"h"
# indexing
 "hello"[-1]
"o"
# (from end)
 "hello"[1:4]
"ell"
# slicing
 len("hello")
5
# size
 "hello" < "jello"
1
# comparison
 "e" in "hello"
1
# search
 "escapes: \n etc, \033 etc, \if etc"
 'single quotes' """triple quotes""" r"raw strings"

Artificial Intelligence
26
LISTS
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 var[index], index refers to order within set
(think card number, starting at 0)
 You can step through lists as part of a loop

Artificial Intelligence
27
LIST METHODS
 Adding

var[n] = object
replaces n with object
var.append(object)

adds object to the end of the list
 Removing

var[n] = []


empties contents of card, but preserves order
var.remove(n)


from the List
Artificial Intelligence


to the List
removes card at n
var.pop(n)

removes n and returns its value
28
LISTS
Artificial Intelligence
29
TUPLES
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

Artificial Intelligence
County Names
 Land Use Codes
 Ordered set of functions

30
TUPLES
key = (lastname, firstname)
 point = x, y, z
# parentheses optional
 x, y, z = point # unpack
 lastname = key[0]
 singleton = (1,)
# trailing comma!!!
 empty = ()
# parentheses!
 tuples vs. lists; tuples immutable

Artificial Intelligence
31
TUPLES
Artificial Intelligence
32
DICTIONARIES
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:

Artificial Intelligence
var[‘item’] = “apple”
 var[‘item’] = “banana”
 print var[‘item’] prints just banana

33
DICTIONARIES

Hash tables, "associative arrays"

Lookup:
d["duck"] -> "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"}

Artificial Intelligence

d = {"duck": "eend", "water": "water"}
34
DICTIONARY 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
Artificial Intelligence

Keys will be listed in arbitrary order

again, because of hashing
35
DICTIONARIES
Artificial Intelligence
36
BASIC FUNCTIONS
BOOLEAN OPERATORS
A && B
A || B
A == B
A != B
!A
Python
Operator
A and B
A or B
A == B
A != B
A <> B
not A
 Relational
operators are all
the same

5 <= 6
 Boolean


values
Artificial Intelligence
C/Java
Operator
True (case
sensitive)
False
38
MATHEMATICAL FUNCTIONS
 abs(x)
Artificial Intelligence
– 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.
39
LIST OPERATIONS
Operator
Meaning
Concatenation
<seq> * <int-expr>
Repetition
<seq>[]
Indexing
len(<seq>)
Length
<seq>[:]
Slicing
for <var> in <seq>:
Iteration
<expr> in <seq>
Membership (Boolean)
Artificial Intelligence
<seq> + <seq>
40
LIST OPERATIONS
Method
Meaning
Add element x to end of list.
<list>.sort()
Sort (order) the list. A comparison function may
be passed as a parameter.
<list>.reverse()
Reverse the list.
<list>.index(x)
Returns index of first occurrence of x.
<list>.insert(i, x)
Insert x into list at index i.
<list>.count(x)
Returns the number of occurrences of x in list.
<list>.remove(x)
Deletes the first occurrence of x in list.
<list>.pop(i)
Deletes the ith element of the list and returns
its value.
Artificial Intelligence
<list>.append(x)
41
FUNCTION DEFINITION
FUNCTIONS

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

Artificial Intelligence
>>> def my_function(x):
...
x = 5
...
print "X = ", x
43
FUNCTIONS
 Python
Artificial Intelligence
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
>>> my_function
<function my_function at 0x00ABDAF0>
>>> my_function(10)
10
44
FUNCTIONS, PROCEDURES
return
# from procedure
return expression
# from function
Artificial Intelligence
def name(arg1, arg2, ...):
"""documentation"""
# optional doc string
statements
45
EXAMPLE FUNCTION
Artificial Intelligence
def gcd(a, b):
"greatest common divisor"
while a != 0:
a, b = b%a, a # parallel assignment
return b
>>> gcd.__doc__
'greatest common divisor'
>>> gcd(12, 20)
4
46
DEFAULT VALUES

box(10, 10, 20)
box(10, 10, 0)
box(10, 10) # same as above
Artificial Intelligence
Parameters can have default values:
def box(width, height,depth=0):
...do something ...
47
FUNCTIONS – INNER BLOCK INDENTATION



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
Artificial Intelligence
Is a good habit to be consistent with the
indentation per level to avoid Python compiler
errors:
48
FUNCTIONS – SCOPE
 You
>>> y = 3
>>> def foo():
...
y = 2
...
print "Y = ", y
>>> foo()
>>> print "Y = ", y
# Prints 2
# Prints 3
Artificial Intelligence
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)
49
FUNCTIONS – RETURN VALUE
 Functions

If no return statement is given, Python will return
None when after executing the last statement of a
function
>>> def foo(x): x = x + 1
>>> print foo(5)
None
>>> if foo(5):
...
print "Impossible..."
... else:
...
print "None is like null in Java“
None is like null in Java
Artificial Intelligence
can have a return statement to
terminate the execution of a function and
return a value
50
BASIC FLOW CONTROL
BASIC FLOW CONTROL
if/elif/else (test condition)
 while (loop until condition changes)
 for (iterate over iteraterable object)
 Range
 Loop control statements

Artificial Intelligence
52
IF STATEMENT
Artificial Intelligence
if j=="Hello":
doSomething()
elif j=="World":
doSomethingElse()
else:
doTheRightThing()
53
WHILE STATEMENT
Artificial Intelligence
str=""
while str!="quit":
str = input();
print (str)
print ("Done“)
54
LOOPING “FOREVER”

Use a value that will always be true to loop until
a “break”.
Artificial Intelligence
while True:
string = input()
if string==“exit”:
break
print (string)
print ("Done”)
55
FOR STATEMENT
for i in range( 10 ):
print i
for i in range( len( myList ) ):
if myList[i]=="c":
myList[i]=None
 Can “break” out of for-loops.
 Can “continue” to next iteration.
Artificial Intelligence
myList = ["a", "b", "c", "d", "e"]
for i in myList:
print i
56
RANGE 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

Artificial Intelligence
57
RANGE 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 < a; x += c)
Artificial Intelligence

58
RANGE FUNCTION

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(5, 10)
Artificial Intelligence
The len and range functions can be combined to
get the index value of a list while iterating
through it
[5, 6, 7, 8, 9]
>>> range(1, 10, 2)
[1, 3, 5, 7, 9]
>>> for i in range(len(a)):
...
print i, a[i]
59
LOOP CONTROL STATEMENTS
Jumps out of the closest
enclosing loop
continue
Jumps to the top of the closest
enclosing loop
pass
Does nothing, empty
statement placeholder
Artificial Intelligence
break
60
BREAK AND CONTINUE STATEMENT
 For/While loops can have else statement
 Runs at the end of the for/while loop
 Break skips else statement, continue does not
>>>
...
...
...
>>>
...
...
...
for i in range(10):
if i == 9: continue
else:
print "bye“
# Bye is printed
for i in range(10):
if i == 9: break
else:
print "bye“
# Bye is not printed
Artificial Intelligence
 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
61
PASS STATEMENT

Is used to make the Python compiler happy when
you want an empty function or class
...
pass
...
# Do nothing
...
Artificial Intelligence
>>> for i in range(10):
>>> class DummyClass:
...
pass
62
TASK
TASKS

Factorial

Fibonacci series

Write a function fib that calculates the Fibonacci
series till N.
Artificial Intelligence

Write a function fact that calculates factorial of N.
64
IMPORTING AND MODULES
IMPORTING AND MODULES

A Python module is a file with the same name (plus the .py
extension)

Like Java import, C++ include.

Three formats of the command:
Artificial Intelligence

Use classes & functions defined in another file.
import somefile
from somefile import *
from somefile import className
What’s the difference?
What gets imported from the file and what name refers to it
after it has been imported.
66
IMPORT
…
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)
Artificial Intelligence

67
COMMONLY USED MODULES

Module: sys



- Lots of handy stuff.
Maxint
Module: os
Module: os.path
Artificial Intelligence

Some useful modules to import, included with
Python:
- OS specific code.
- Directory processing.
68
MORE COMMONLY USED MODULES

Module: math
- Mathematical code.
Exponents
 sqrt

Module: Random - Random number code.
Randrange
 Uniform
 Choice
 Shuffle

Artificial Intelligence

69