1 / 67

Introduction to PYTHON

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.

erma
Download Presentation

Introduction to PYTHON

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to PYTHON Sajid Gul Khawaja

  2. 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

  3. 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

  4. 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

  5. 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

  6. 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

  7. 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

  8. 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

  9. IDLE – Development Environment • IDLE helps you program in Python by: • color-coding your program code • debugging • auto-indent • interactive shell Artificial Intelligence

  10. General Information

  11. 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

  12. 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

  13. 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

  14. 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

  15. 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

  16. 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

  17. 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

  18. 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

  19. Basic Data Types

  20. Data Type • Boolean • Integer • Floating • Character • String • Lists • Dictionaries • Tuples Artificial Intelligence

  21. 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

  22. Basic Data Types Artificial Intelligence

  23. 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

  24. 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

  25. 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

  26. 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

  27. Lists Artificial Intelligence

  28. 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

  29. 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

  30. Tuples Artificial Intelligence

  31. 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

  32. 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

  33. 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

  34. Dictionaries Artificial Intelligence

  35. Basic Functions

  36. Boolean Operators • Relational operators are all the same • 5 <= 6 • Boolean values • True (case sensitive) • False Artificial Intelligence

  37. 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

  38. List Operations Artificial Intelligence

  39. List Operations Artificial Intelligence

  40. Function Definition

  41. 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

  42. 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

  43. Functions, Procedures def name(arg1, arg2, ...): """documentation""" # optional doc string statements return # from procedure return expression # from function Artificial Intelligence

  44. 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

  45. 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

  46. 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

  47. 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

  48. 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

  49. Basic Flow Control

  50. Basic Flow Control • if/elif/else (test condition) • while (loop until condition changes) • for (iterate over iteraterable object) • Range • Loop control statements Artificial Intelligence

More Related