Download presentation
Presentation is loading. Please wait.
1
Programming in Python
2
Basics What is Python Numeric Types String Types and Variables
Built-in Functions Data Structures Conditionals Loops Functions DELL CONFIDENTIAL
3
Module 1 What is python DELL CONFIDENTIAL
4
Origin of Python Created by Guido Van Rossum 1986-1991.
Created by Guido Van Rossum Named after the Monty Python show. Most stable at version 2.7.x. Current version is DELL CONFIDENTIAL
5
More About Python Very clear, readable syntax.
Interpreted, Object-Oriented, Interactive Dynamically typed Rich standard and 3-rd party library set Extensible in C/C++/Java Embeddable C/C++/Java Portable – Linux / Windows / etc. Open / GPL-ed DELL CONFIDENTIAL
6
Why would I use it? Easy to learn, yet very powerful
Promotes modularity, code reuse, maintenance. No compilation step: edit->test->debug cycle is fast. No seg fault’s, interpreter always throws exceptions. It is cross platform. Many large companies using it– also internal Dell support Free! DELL CONFIDENTIAL
7
Complexity Gauge – Hello World – asm-32
; Hello World for Intel Assembler (MSDOS) mov ax,cs mov ds,ax mov ah,9 mov dx, offset Hello int 21h xor ax,ax int 21h Hello: db "Hello World!",13,10,"$" DELL CONFIDENTIAL
8
Complexity Gauge – Hello World - Java
// Hello World in Java class HelloWorld { static public void main( String args[] ) { System.out.println( "Hello World!" ); } DELL CONFIDENTIAL
9
Complexity Gauge – Hello World – C#
// Hello World in Microsoft C# ("C-Sharp"). using System; class HelloWorld { public static int Main(String[] args) { Console.WriteLine("Hello, World!"); return 0; } DELL CONFIDENTIAL
10
Complexity Gauge – Hello World – Python
# Hello World in Python print “Hello World” Python Motto: “Simple things simple, complex things possible” DELL CONFIDENTIAL
11
Who uses it? Dell – Test Automation
Google – Many components of Google are written in Python. 1 of 3 std languages (C++, Java). Yahoo – Yahoo maps, Yahoo Groups (180k lines) Red Hat / Fedora – The anaconda (Installer) is written in python, both GUI and Text mode. Many other pieces of Red Hat config tools are in Python as well. NASA – Johnson Space center, standard language for the Integrated Planning System. Efforts underway to migrate older Perl and shell code to Python. Industrial Light and Magic – Every CG generated was touched by Python somewhere in the process. (Pirates, Transformers, Evan Almighty, Harry Potter) Games – Civilization IV, Battlefield 2 Rackspace – PHP -> Python for their CORE infrastructure National Weather Service – Main computer system, 120 sites DELL CONFIDENTIAL
12
What can I use it for? Test automation Deployment automation
System administration task automation Enabling a high level interface to a C/C++ DLL/.SO Text processing Web sites Etc. DELL CONFIDENTIAL
13
How do I get it? Python - http://www.python.org/download
PyScripter - Q: The most downloaded version of Python (by OS) is: A: Win32 (Windows 2K, XP, Vista)! Q: Why Windows and not Linux? A: Because Python is already bundled with most Linux distributions including RedHat / SuSe / Ubuntu, etc. DELL CONFIDENTIAL
14
What version? Minimum: Python 2.7.x Python in Linux distributions:
RHEL4 – Python 2.3.4 RHEL5 – Python 2.4.3 RHEL 6 – Python 2.6.6 RHEL 7– Python 2.7.5 Fedora 7 – Python 2.5 SuSE 10 – Python 2.4.2 Windows need to download… DELL CONFIDENTIAL
15
Interactive mode To start python interactively, on lin32, type:
<path>/python2 (or <path>/python25 Python 2.5 (#1, Aug 2006, 12:15:30) [GCC (Red Hat Linux Rawhide 3.2-4)] Type “help”, “copyright”, or “license” for more… >>> To start python interactively, on win32, type: <path>\python.exe Python (#34, Apr , 19:34:33) [MSC 32 bit (Intel)] on win32] DELL CONFIDENTIAL
16
Lab Install python 2.7.x interpreter (if needed)
Start interpreter, type: 2+2 What was the output? Type: print “hello world!” Type: 2+a Type: 1/0 Using a text editor / IDLE create a file: lab1.py with the above commands. Run the file with a python interpreter… DELL CONFIDENTIAL
17
Module 2 Numeric types DELL CONFIDENTIAL
18
Overview There are four numeric types:
integers, long integers, floating point numbers, complex numbers Integers are implemented as longs in C (>=32 bit) They have *unlimited* precision (till you run out of memory) Floats are implemented as a C double Complex numbers are also double (real and imaginary) DELL CONFIDENTIAL
19
Operations Built-in operations: +,-,*,/,% -x
abs(),int(),long(),float() pow(x,y), x**y divmod(x,y)=(x/y, x%y) Modules: math, cmath modules provide more operations, for eg: acos(),cos(),exp(),hypot(),log(),sin(),tan() ceil(),floor() e, and pi are defined… DELL CONFIDENTIAL
20
Examples 1 print 2+2 # this is a comment
4 print 9/4 # integer division returns floor* 2 width = 4 height = 2+2 area = width * height print area 16 DELL CONFIDENTIAL
21
Examples 2 x=y=z=2 # serial assignment print x amount=6.25 tax=8.25
total=amount+(amount*(tax/100)) print round(total, 2) 6.77 DELL CONFIDENTIAL
22
Augmented Assignment Operators
AAO’s “simplify” math and *other* object operations. List of AAOs: += = x = x + 5 -= = x = x - 5 *= = x = x * 5 /= = x = x / 5 %= = x = x % 5 Python does not have ++ or -- DELL CONFIDENTIAL
23
String type AND VAriables
Module 3 String type AND VAriables DELL CONFIDENTIAL
24
Overview Strings are specified by “string” or ‘string’
Unicode Strings are specified by u”string” or u’string’ Strings support many methods: capitalize(), expandtabs(), lower(), swapcase(), title(), translate(), upper(), zfill() replace(), split(), splitlines() center(), join(), ljust(), rjust(), rstrip(), strip(), lstrip(), count(), endswith(), find() , index(), rfind(), rindex(), startswith(), isalnum(), isalpha(), isdigit(), islower(), isspace(), istitle(), isupper() decode(), encode() DELL CONFIDENTIAL
25
Strings Strings are defined w/ quotes. Either single quotes: ‘ Or
Double quotes: “ A string defined with single quotes DO NOT have any different meaning than strings defined with double quotes. DELL CONFIDENTIAL
26
Triple Quoted Strings Text formatting can be preserved with Triple quoted strings: “““Copyright (C) 2007, Dell, Inc. All Rights Reserved.””” In a python file, unassigned triple quoted strings can be comments! Single line comments are signified with the # character. DELL CONFIDENTIAL
27
Examples Valid? “““ ____ __ __ __ _____ / __| / | / | / | | ___| | | / / | | / / | / | | | |__ | | _ / _ | / / |_/ | | | __| | |_| | / / | | / / | | | |___ \___ / /_/ |_| /_/ |_| |_____| ____ _ _ ____ ____ / _ \ | | / / | ___| | _ \ | | | | | | / / | |__ | |_| | | | | | | | / / | __| | _ / | |_| | | | / / | |___ | | \ \ \____/ |___/ |_____| |_ | \_\ ””” YES DELL CONFIDENTIAL ASCII ART* -
28
Examples Valid? > s=“hello” # hello > s = # hello
Yes > s = # hello No > “““hello””” > s=“““hello””” > s=“hello” “““hello””” Yes > s=“““he said, ““I can’t””” > s=“““he said, ““I cant””””” DELL CONFIDENTIAL
29
Concatenation / Repetition
String concatenation operator is: + String repeat operator is: * For concatenation string + string: “AA” + “AA” = “AAAA” For repetition: string * integer: “BA” * 2 = “BABA” DELL CONFIDENTIAL
30
Same-line / Newline separators
Newline separator is: \ print \ “hello world” Same-line separator is: ; print “hello”; print “world” hello world DELL CONFIDENTIAL
31
Suppressing Newline It is possible to suppress new line with: ,
print “hello”, ; print “world” # hello world NOTE: comma, puts a *space* instead of a \n at end of string. NOTE: after comma, no operations possible (such as + or *). DELL CONFIDENTIAL
32
Formatting Strings (plain and unicode) can be formatted using %:
format % values Examples: “abc = %s” % “def” ‘abc = def’ “my_age = %d” % 102 ‘my_age = 102’ “name = %s, age = %d” % (“bob”, 102) ‘name = bob, age = 102’ “name = %s, age = %d” % “bob”, 102 TypeError: not enough arguments for format string Conversion Meaning d signed decimal u unsigned decimal x hexadecimal (lowercase) f floating point (decimal format) s convert to string DELL CONFIDENTIAL
33
Escape Sequences Escape Sequence Meaning \\ \ \’ ’ \” ” \a ASCII BEL
ASCII BS \f ASCII FF \n ASCII LF \r ASCII CR \t ASCII tab DELL CONFIDENTIAL
34
Examples Output? > print “hello\rworld” > print “123alog\rcat”
catalog > print “\a\a\a\n” Three beeps, cursor.. >print “cat\br” car >print “\b|\b/\b-\b\\\b|” | >print “C:\\dell” C:\dell >print “\“Hello\” W” “Hello” W >print “\“Hello\’ W” “Hello’ W DELL CONFIDENTIAL
35
Examples > print “Hello” * 2 > print “Hello” + 2
HelloHello > print “Hello” + 2 Error > print “Hello”, 2 Hello 2 > print “Hello”, ; \ print “world” Hello world > print “Hello\n” ; \ Hello(blank line)world Output: > print “*” * 17; print \ “|\t\t|”; print “|\t\t|”; \ print “*” * 17 A rectangle (for some) > print “Hello” + ‘world’ Helloworld > print “Hello” * “2” Error DELL CONFIDENTIAL
36
Quotes in Quotes You can use quotes (of the other kind than the ones you are using to define your string) to have quotes in quotes… ‘He said, “Good morning,” to her.’ Question: Is below same as above? “He said, ‘Good morning,’ to her.” No! DELL CONFIDENTIAL
37
Naming variables Two rules: Some guidelines:
A variable name can contain only numbers, letters, and underscores. A variable name CANNOT start with a number. Some guidelines: Choose descriptive names. Be consistent. Follow conventions / standards. Keep length in check. DELL CONFIDENTIAL
38
Examples Valid variables? First_name first_name: name_first _name_
yes first_name: no name_first _name_ _!name no 1_2_3 i_2_3 yes 12x x12_rocket_number_ DELL CONFIDENTIAL
39
Module 4 Built-in functions DELL CONFIDENTIAL
40
Overview Some useful built-in functions: Type casting Console I/O
Introspection list operations DELL CONFIDENTIAL
41
Type casting Type casting: Examples: str(1) chr(97) “2”+“2”
str(obj), chr(x), repr(obj), unicode(object) int(s), float(s), long(s), coerce(x,y), hex(x), oct(x), ord(c) Examples: str(1) ‘1’ chr(97) a “2”+“2” “22” int(“2”)+float(“2”) 4.0 DELL CONFIDENTIAL
42
Console I/O print, raw_input examples: print “hello”+“ world”
print “The year is: ”+2004 TypeError: cannot concatenate ‘str’ and ‘int’ objects print “The year is: ”+str(2004) The year is: 2004 name=raw_input(“Enter your name: ”) Enter your name: bob age=raw_input(“Enter your age: ”) Enter your age: 102 print “Hello ”+name+“, you are ”+age+“ years old!” Hello bob, you are 102 years old! DELL CONFIDENTIAL
43
Introspection Introspection functions: Introspection examples: dir()
dir([obj), vars([obj]), globals(), locals(), isinstance(obj, class), type(obj) Introspection examples: dir() [‘__builtins__’, ‘__doc__’, ‘__name__’] dir(__builtins__) ... dir(“hello”) … print isinstance(“hello”, str) 1 print type(“hello”) <type ‘str’> n=1 print globals() … ‘n’: 1 DELL CONFIDENTIAL
44
Module 5 DATA Structures DELL CONFIDENTIAL
45
Overview Python Data Structures be classified into 3 categories of types: Sequence Types: strings, unicode strings, lists, tuples. Mapping Types: dictionaries *Set Types: set, frozenset. DELL CONFIDENTIAL
46
Sequences: Lists Lists ~ Arrays / Vectors (they can contain elements of mixed types) Lists are created using square brackets: [ ] For list s, items x and t, integer indexes i and j: s[i] = x # item at location i of s is replaced by x s[i:j] = t # items i to* j replaced by t del s[i:j] # delete items i to* j s.append(x) # add an item x at end of list s s.count(x) # return numbers of times x is found in s s.index(x) # return 1st i’th location of x in s s.insert(i, x) # insert x *AFTER* i s.pop([i]) # return & delete item in s at i, i default = -1 s.remove(x) # same as s.del(x) s.reverse() # reverses the items of x in place s.sort([cmpfnc]) # sorts the items of s in place # cmpfunc takes two args, returns -, 0, or + *(not through) DELL CONFIDENTIAL
47
List Examples 1 breakfast = [“eggs”, “milk”, “bacon”, “corissanwich”, 930] print breakfast [‘eggs’, ‘milk’, ‘bacon’, “croissanwich”, 930] print breakfast[0] eggs print breakfast[len(breakfast)-1] 930 breakfast[4] = breakfast[4] + 70 print breakfast[4] 1000 del breakfast[4] IndexError: list index out of range [‘eggs’, ‘milk’, ‘bacon’, “croissanwich”] del breakfast[3] breakfast.append(830) # time for python class [‘eggs’, ‘milk’, ‘bacon’, 830] DELL CONFIDENTIAL
48
Sequences: Tuples Tuples are like immutable lists.
Tuples are created using parentheses: ( ) Examples: alphabet = (‘a’, ‘e’, ‘i’, ‘o’, ‘u’, ‘h’, ‘k’, ‘l’, ‘m’, ‘n’, ‘p’, ‘w’) print alphabet (‘a’,’e’,’i’,’o’,’u’,’h’,’k’,’l’,’m’,’n’,’p’,’w’) print alphabet[8]+alphabet[0]+alphabet[4]+alphabet[2] maui alphabet.append(b) AttributeError: ‘tuple’ object has no attribute ‘append’ del alphabet[3] TypeError: object doesn’t support item deletion DELL CONFIDENTIAL
49
Sequences: Operations
Operations (apply to all sequence types): x is an item, s and t are sequences, i and j are integers: x in s # 1 if x is an item in s, otherwise 0 x not in s # 1 if x is not an item in s, otherwise 0 s + t # concatenation of s and t s * n # n copies of s s[i] # i’th item in s, indexed from 0 s[i:j] # slice of s from i to j len(s) # length of s min(s) # smallest item of s max(s) # largest item of s DELL CONFIDENTIAL
50
Slice Operator The Slice operation in more detail:
For a sequence s: s[i:j] # returns indexes k, such that: i <= k < j Rules: If i or j is negative, index is relative to end of sequence i.e. then len(s)+i or len(s)+j is substituted, note: -0 = 0 If i or j > len(s), use len(s) if i is omitted, use 0, if j is omitted, use len(s) if i >= to j, the slice is empty; string “”, list [ ], tuple ( ) DELL CONFIDENTIAL
51
Sequences: Examples 1 Strings (behave like tuples):
cool_show=“The Monty Python Show” print len(cool_show) 21 cool_name1=cool_show[4:9] cool_name2=cool_show[-11:-5] print cool_name2+ “ and ”+cool_name1+ “ are cool!” Python and Monty are cool! T h e M o n t y P S w 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 -21 -20 -19 -18 -17 -16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 DELL CONFIDENTIAL
52
Sequences: Examples 2 PE6850 PE6800 PE2800 PE2850 PE1855MC PE1850
More fun with Lists: PowerEdge8G = [“PE6850”, “PE6800”, “PE2800”, “PE2850”, “PE1855MC”, “PE1850”] print max(PowerEdge8G) PE6850 print min(PowerEdge8G) PE1850 print “PE2850” in PowerEdge8G 1 print “PE1800” not in PowerEdge8G PE6850 PE6800 PE2800 PE2850 PE1855MC PE1850 1 2 3 4 5 -6 -5 -4 -3 -2 -1 DELL CONFIDENTIAL
53
Dictionary Overview Python has one mapping type: Dictionary
A Dictionary contains key, value pairs mydict[key] = value The values can be any python object The keys must be python objects that can be compared by value, often strings, ints, tuples. Dicts are created using curly brackets: { } DELL CONFIDENTIAL
54
Dictionary: Operations
a and b are dicts, k is a key, v is a value: len(a) # number of items in dict a a[k] # get value for key k in a del a[k] # delete key, value a[k] from a a.clear() # delete all items in a a.copy() # shallow copy of a a.has_key(k) # 1 if k in a else, 0 a.items() # list of (key,value) pairs in a a.keys() # list of keys in a a.update(b) # for k in b.keys(): a[k] = b[k] a.values() # list of values in a a.get(k,x) # get value for k in a, otherwise x if None a.popitem() # remove and return an arbitrary k,v pair DELL CONFIDENTIAL
55
Dictionary: Examples toyota_91 = {‘sport’: “supra”, ‘midsize’: “camry”, ‘compact’: “corolla”, ‘subcompact’: “tercel”, ‘fullsize’: “cressida”} print toyota_91 {‘sport’: ‘supra’, ‘midsize’: ‘camry’, ‘compact’: ‘corolla’, ‘subcompact’: ‘tercel’, ‘fullsize’: ‘cressida’ } toyota_07 = toyota_91.copy() print toyota_07 toyota_07[‘fullsize’] = ‘avalon’ del toyota_07[‘sport’] toyota_07[‘sporty’] = ‘matrix’ toyota_07[‘pickup’] = ‘tacoma’ toyota_07[‘subcompact’] = ‘yaris’ {‘midsize’: ‘camry’, ‘compact’: ‘corolla’, ‘subcompact’: ‘yaris’, ‘fullsize’: ‘avalon’, ‘sporty”: ‘matrix’, ‘pickup’: ‘tacoma’} DELL CONFIDENTIAL
56
Deep Copying Mutable types change in place.
Must deep copy else shared reference. List: newl = l[:] # using slice, or newl = list(l) # using list casting fn Dictionary: newd = {} for k, v in d.items(): # traversal newd[k] = v Or copy module: import copy x = copy.copy(y) # make a shallow copy of y x = copy.deepcopy(y) # make a deep copy of y DELL CONFIDENTIAL
57
Module 5 Lab DATA STRUCTURES DELL CONFIDENTIAL
58
Module 5 Lab 1. Print following using a single print statement:
Copyright (C) 2007, Dell, Inc. All Rights Reserved 2. For the following string: string1 = “A quick brown fox jumps over the lazy dog.” a. what can ? be if string1[?] is dog. b. how about if string1[?] is jumps over the lazy dog. c. and what if it string1[?] is A 3. Does the code below work? mylist = [1,2,3] mylist.append(a) 4. How about this code: mylist = (1,2,3) mylist.append(4) DELL CONFIDENTIAL
59
Module 6 Python files DELL CONFIDENTIAL
60
Overview So far the code we have written was in the interpreter.
If we exit the interpreter all the code is lost! So we need to use a text editor and write the code to a file. The file is referred to as a Python: file module script program etc DELL CONFIDENTIAL
61
Syntax Typical Python module: #!/usr/bin/env python2 #
# – mfk – created def fn1(params): code… def fn2(params): Typical Python script: #!/usr/bin/env python2 # # – mfk – created def fn1(params): code… def fn2(params): if __name__ == “__main__”: code… fn1(args) fn2(args) code… fn1(args) fn2(args) DELL CONFIDENTIAL
62
Notes Tabs signify blocks.
Potential for Tab / Space confusion. Configure text editor to convert tabs to spaces. Eclipse, notepad, etc are ok. Vi needs configuration. No semicolon required to close end line of code. Can use semicolon to specify multiple instructions on same line. Multi-line separator is \. Comments are precede with a # DELL CONFIDENTIAL
63
Module 6 Lab Python FILES DELL CONFIDENTIAL
64
Module 6 Lab Are the following code blocks valid: block1.py: 2+2; 1+1
4 2 block2.py: 1+ \ 1 block3.py: 2+2 1+1 File "<stdin>", line 2 DELL CONFIDENTIAL
65
Module 7 Conditionals DELL CONFIDENTIAL
66
Overview Value testing Comparisons if statement if-else if-elif-else
DELL CONFIDENTIAL
67
Value Testing The following are considered false:
None # python’s null type False Zero of any numeric type, 0, 0.0, 0L An empty sequence [ ], ( ), ‘’, “” An empty mapping { } What is considered true? All other values including True *built-in constants DELL CONFIDENTIAL
68
True / False / None False + 99 99 True + 99 100 None + 1
Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' DELL CONFIDENTIAL
69
Comparisons Syntax for comparisons: Boolean:
>,>= # greater than, greater than or equal to <,<= # less than, less than or equal to == # equal !=, <> # not equal to is # is object identity is not # negated object identity Boolean: x or y # if x is false, then y, else x x and y # if x is false, then x, else y not x # if x is false, then 1, else 0 DELL CONFIDENTIAL
70
Comparisons Example 1==1 1==0 “a”>“b” 1 is 1 # confusing
“a”>“b” 1 is 1 # confusing word=“Hello” word2=word word is word2 > print id(word), id(word2) # why did it work? DELL CONFIDENTIAL
71
if statement Syntax for if statement: Examples: n=m=1 o=2 if n==o:
code… if comparison: code… # execute this regardless of if result Examples: n=m=1 o=2 if n==o: … print “n and o match!” *nothing!* if n==m: … print “n and m match!” n and m match! DELL CONFIDENTIAL
72
if-else statement Syntax for if-else: Examples: n=m=1 o=2 if n==o:
code… if comparison: else: Examples: n=m=1 o=2 if n==o: … print “n and o match!” … else: … print “n and m match!” n and m match! # not entirely true! DELL CONFIDENTIAL
73
if-elif-else statement
Syntax for if-elif-else: code… if comparison: elif comparison: # multiple elifs allowed (switch-case) else: Examples: n=m=1 o=2 if n==o: … print “n and o match!” … elif n==m: … print “n and m match!” … else: print “sorry no matches!” n and m match! DELL CONFIDENTIAL
74
Module 8 Loops DELL CONFIDENTIAL
75
Overview While statement For statement range() function
break, continue & pass statements DELL CONFIDENTIAL
76
while statement Syntax for while: ch=97 while ch <= 122:
code… while condition: # while condition is true else: # execute only if condition becomes false code… # execute this after while loop ch=97 while ch <= 122: … print chr(ch), # , means stay on same line … ch = ch + 1 # infinite loop w/o this line a b c d e f g h I j k l m n o p q r s t u v w x y z DELL CONFIDENTIAL
77
for statement for statement in Python != C, Pascal, Java etc, more = bash Syntax for for: code… for an_item in items: # while condition is true code… # loop till all items used else: # execute if all items used code… # execute after for loop list = [“a”, “b”, “c”] for item in list: … print item, a b c DELL CONFIDENTIAL
78
Traversals Traversing a sequence using for:
poweredge8g = [“PE6850”, “PE6800”, “PE2850”, “PE1850”, “PE1800”] for a_server in poweredge8g: … print a_server, PE6850 PE6800 PE2850 PE1850 PE1800 Traversing a mapping using for: > toyota_07={‘midsize’: ‘camry’, ‘compact’: ‘corolla’, ‘subcompact’: ‘yaris’, ‘fullsize’: ‘avalon’, ‘sporty”: ‘matrix’, ‘pickup’: ‘tacoma’} for k, v in toyota_07.items(): … print k+“=”+v, midsize=camry compact=corolla subcompact=echo fullsize=avalon sporty=matrix pickup=tacoma DELL CONFIDENTIAL
79
Traversals w/ enumerate
Traversing a sequence using for and show indices: poweredge8g = [“PE6850”, “PE6800”, “PE2850”, “PE1850”, “PE1800”] index = 0 for a_server in poweredge8g: … print str(index)+”:”, a_server, … index += 1 0: PE6850 1: PE6800 2: PE2850 3: PE1850 4: PE1800 w/ enumerate: for index, a_server in enumerate(poweredge8g): DELL CONFIDENTIAL
80
range() range() generates arithmetic progressions using lists:
Syntax for range: range([start],stop,[step]) if no start, 0 assumed, if no step, 1 assumed range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] range(5, 10) [5, 6, 7, 8, 9] range(0, 10, 2) [0,2,4,6,8] DELL CONFIDENTIAL
81
break, continue & pass The break statement will break out of the smallest enclosing for/while loop. The continue statement will go to next iteration of loop without running remaining code in current iteration. The pass statement is essentially a no-op. Loop statements can have an else clause; runs when: loop terminates through exhaustion of the list (with for) or condition becomes false (with while), but not when the loop is terminated by a break statement. DELL CONFIDENTIAL
82
for-else example for n in range(2, 10): # loop to search for primes
… for x in range(2, n): … if n % x == 0: … print n, ‘equals’, x, ‘*’, n/x … break … else: … print n, ‘is a prime number’ 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3 DELL CONFIDENTIAL
83
Module 8 Lab Loops DELL CONFIDENTIAL
84
Module 8 Lab 1. Select a number between 1 and Put this number in your program. Allow the user to guess the number from a prompt. The user should be prompted to guess the number until either they guess the correct number, or they hit “x” to exit the program. Extra Credit: Each time the user guesses, tell user whether they need to guess higher or lower When the user wins, tell them how many times they tried to guess the right number. 2. Write the Prime Number detection loop w/o the for-else syntax. DELL CONFIDENTIAL
85
Module 8 Lab 2 Make a dictionary program. Supporting following functions: Lookup a word (getting its definition). Add a word and its definition. Redefine a word’s definition. Delete a word (and its definition). List all words in dictionary. Provide a mechanism to quit from this program. DELL CONFIDENTIAL
86
Module 9 functions DELL CONFIDENTIAL
87
Overview Function syntax: def functionName([arg1, arg2…]): [“doc string”] # optional doc string describing fn code… # code block [return data] # function can optionally return data # return can return multiple items a, b, c = functionName() # function call DELL CONFIDENTIAL
88
Examples y=4 def func(y): … print y, … y = 3 … print y func(y) print y
4 3 print y 4 list=range(5) def func2(alist): ... print alist … alist.append(100) func2(list) [0, 1, 2, 3, 4] print list [0, 1, 2, 3, 4, 100] DELL CONFIDENTIAL
89
Parameter Formats Default values:
def car(make, model, doors=4, wheels=4): car(“Ford”, “Mustang”, 2) car(“Toyota”, “Corolla”) car(“Mr.”, “Bean’s”, 3, 3) What if I had a Ford F550 Supercrew Dually: 4 doors, 6 wheels, I don’t want to pass 4 for the doors, only the 6 for the wheels. Keyword values: car(“Ford”,“F550 Supercrew”, wheels=6) DELL CONFIDENTIAL
90
*,** parameters a * preceding an argument indicates an argument sequence or arbitrary length: def arbitrary(*a): return a print arbitrary(“a”,“b”,3) (a, b, 3) a ** preceding an argument indicates it will be a dictionary containing key/value pairs of all passed keyword args. def coolFunc(**optDict): return optDict > print coolFunc(abc=“def”, ghi=“jkl”) {‘abc’: ‘def’, ‘ghi’: ‘jkl’} DELL CONFIDENTIAL
91
Function helpers List/Sequence operations: Examples: five=[1,2,3,4,5]
filter(function, list), map(function, list), reduce(function, list) Examples: five=[1,2,3,4,5] def multiply(x,y): … return x*y reduce(multiply, five) #(((((1)*2)*3)*4)*5) ie 5! 120 def threeandup(x): … if x >= 3: … return 1 … else: … return 0 filter(threeandup, five) [3,4,5] def squares(x): … return x*x map(squares, five) [1, 4, 9, 16, 25] DELL CONFIDENTIAL
92
Module 9 Lab Functions DELL CONFIDENTIAL
93
Module 9 Lab A palindrome is a word that is spelled the same way forwards as it is backwards. Some examples include “radar”, “dad”, “malayalam” and “a man a plan a canal panama”. Write a function testPalindrome() that returns a True if the string is a palindrome and a False otherwise. Extra Credit: Use recursion. Modify dictionary program to use functions. Write a Jumble word program that randomly selects a string, jumbles it, and asks user to guess the word, interaction w/ user ~ guess a number game… DELL CONFIDENTIAL
94
Module 1: Exceptions DELL CONFIDENTIAL
95
Exceptions Overview When an error occurs
An exception is raised (=thrown in Java). The interpreter jumps out of code blocks till the exception is caught by a try block, or If the exception is not caught, interpreter quits code execution with the exception. All errors in Python are exceptions (hence no seg faults). For eg: 1/0, 3+“3”, (3, 4).append(“abc”) DELL CONFIDENTIAL
96
try…except syntax try: # program logic goes here.. except Exception1: # code to handle exception, Exception1 except Exception2, Exception3: # code to handle exceptions, 2 or 3.. except: # code to catch all other exception types. else: # run this if there were NO exceptions! DELL CONFIDENTIAL
97
try…except…finally try: # program logic goes here.. except Exception1: # code to handle exception, Exception1 except Exception2, Exception3: # code to handle exceptions, 2 or 3.. except: # code to catch all other exception types. else: # run this if there were NO exceptions! finally: # run this code REGARDLESS of exception or not DELL CONFIDENTIAL
98
example try: cc=open('carddata.txt',"r") lines=cc.readlines() except IOError: print "error reading file!" except: print "some other error“ finally: print “closing file…” cc.close() DELL CONFIDENTIAL [exception.py]
99
Trapping Ctr-C import sys import time try: while True:
print "processing stuff..." time.sleep(1) except KeyboardInterrupt: print "Ctrl-C pressed... exiting..." sys.exit(1) DELL CONFIDENTIAL [exception_trap.py]
100
Module 10 Modules DELL CONFIDENTIAL
101
Using modules You can load modules using the import statement:
import os from ConfigParser import ConfigParser from os import * # bad, pollutes namespace! mymodule.py: def hello(): print “hello world!” def hello2(): print “hello monty python!” import mymodule # importing mymodule.py dir(mymodule) [‘__builtins__’, ‘__doc__’, ‘__file__’, ‘__name__’, ‘hello’, ‘hello2’] mymodule.hello2() hello monty python! DELL CONFIDENTIAL
102
Dynamic execution You can also load modules dynamically: test.py:
print “abcdefg” if timeToImport==True: execfile(“c:\test.py”, globals(), locals()) abcdefg You can also run code dynamically: def bob(): print “My name is bob” name=raw_input() #dynamic function pointer bob exec(name+ “()”) My name is bob DELL CONFIDENTIAL
103
Module search path The Python module search path can be set dynamically: import sys sys.path.append(“c:\temp\my_python”) print sys.path […, “c:\temp\my_python”] DELL CONFIDENTIAL
104
Questions DELL CONFIDENTIAL
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.