700 likes | 899 Views
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.
E N D
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
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
More 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 Artificial Intelligence
Useful error messages • Automatic memory handling • Independent of operating system • Works on both Unix and Windows • Even file system code can be made os-independent • Large library of standard modules • Large number of third-party modules • Integration with external C code • Well documented Features 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 don’t have to use it Artificial Intelligence
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” • Coordinating components • Glue logic • Artificial intelligence Artificial Intelligence
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
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
IDLE – Development Environment • IDLE helps you program in Python by: • color-coding your program code • debugging • auto-indent • interactive shell Artificial Intelligence
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
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 • Everything is a "variable": • Even functions, classes, modules Artificial Intelligence
Reference 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: >>> a = [1, 2, 3] >>> b = a >>> a.append(4) >>> print b [1, 2, 3, 4] Artificial Intelligence
a 1 2 3 1 2 3 a b Changing a Shared List a = [1, 2, 3] b = a Artificial Intelligence a 1 2 3 a.append(4) 4 b
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
Whitespace 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.) Artificial Intelligence
Comments • 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. defmy_function(x, y): “““This is the docstring. This function does blah blah blah.”””# The code would go here... Artificial Intelligence
None • “None” represents the lack of a value. • Like “NULL” in some languages or in databases. • For instance: >>>ify!=0:...fraction=x/y...else:...fraction=None Artificial Intelligence
Data Type • Boolean • Integer • Floating • Character • String • Lists • Dictionaries • Tuples Artificial Intelligence
Booleans • True and False are the only values of type “bool”. • True can be treated as “1” and False as “0” in mathematical expressions: >>>printTrue+True+True-False3>>>printFalse==0True Artificial Intelligence
Basic Data Types Artificial Intelligence
Numbers • The usual suspects • 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
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
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
List Methods • Adding to the List • var[n] = object • replaces n with object • var.append(object) • adds object to the end of the list • Removing from the List • var[n] = [] • empties contents of card, but preserves order • var.remove(n) • removes card at n • var.pop(n) • removes n and returns its value Artificial Intelligence
Lists Artificial Intelligence
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 • County Names • Land Use Codes • Ordered set of functions Artificial Intelligence
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
Tuples Artificial Intelligence
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: • var[‘item’] = “apple” • var[‘item’] = “banana” • print var[‘item’] prints just banana Artificial Intelligence
Dictionaries • Hash tables, "associative arrays" • d = {"duck": "eend", "water": "water"} • 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
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 • Keys will be listed in arbitrary order • again, because of hashing Artificial Intelligence
Dictionaries Artificial Intelligence
Boolean Operators • Relational operators are all the same • 5 <= 6 • Boolean values • True (case sensitive) • False Artificial Intelligence
Mathematical 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. Artificial Intelligence
List Operations Artificial Intelligence
List Operations Artificial Intelligence
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 >>> def my_function(x): ... x = 5 ... print "X = ", x Artificial Intelligence
Functions • 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 >>> my_function <function my_function at 0x00ABDAF0> >>> my_function(10) 10 Artificial Intelligence
Functions, Procedures def name(arg1, arg2, ...): """documentation""" # optional doc string statements return # from procedure return expression # from function Artificial Intelligence
Example Function 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 Artificial Intelligence
Default Values • Parameters can have default values: defbox(width,height,depth=0):...dosomething...box(10,10,20)box(10,10,0)box(10,10)# same as above Artificial Intelligence
Functions – 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 Artificial Intelligence
Functions – 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) >>> y = 3 >>> def foo(): ... y = 2 ... print "Y = ", y >>> foo() # Prints 2 >>> print "Y = ", y # Prints 3 Artificial Intelligence
Functions – 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 >>> 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
Basic Flow Control • if/elif/else (test condition) • while (loop until condition changes) • for (iterate over iteraterable object) • Range • Loop control statements Artificial Intelligence