1 / 29

Writing Solid Code

Writing Solid Code. Introduction to Python. Program 1. python -c "print 'Hello World' “ python -c "import time; print time.asctime()“ Start an interactive session: python –v help(command/expression). Unix Executable Scripts. Most portable version: #!/usr/bin/env python. $ cat first.py

aldona
Download Presentation

Writing Solid Code

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. Writing Solid Code Introduction to Python

  2. Program 1 • python -c "print 'Hello World' “ • python -c "import time; print time.asctime()“ • Start an interactive session: • python –v • help(command/expression)

  3. Unix Executable Scripts • Most portable version: • #!/usr/bin/env python $ cat first.py #!/usr/bin/env python # A comment print 'Hello World‘ print 2**100 $ chmoda+x first.py $ ./first.py Hello World 1267650600228229401496703205376

  4. Basic Elements • Keywords: and assert break class continue def del elif else except exec finally for from global if import in is lambda not or pass print raise return try while with yield • Operators: + - * / % ** // << >> & | ^ ~ < <= > >= <> != == • Delimiters: ( ) [ ] { } , : . ' = ; += -= *= /= //= %= &= |= ^= >>= <<= **=

  5. Data Types • All data values are objects • type(obj) returns the type. • Numbers • Integer: 23, 027 (octal), 0xDA5 (hex) • Floating points : 1.00, 1.0e2 • Complex numbers: 5+6j

  6. Data Types • Sequences • Iterables: All sequences are iterable. (for) • Strings: • Can use “” or ‘’ to specify. “abc” ‘abc’ (Same thing.) Unmatched ones can occur within the string. “matt’s” • Use triple double-quotes for multi-line strings or strings than contain both ‘ and “ inside of them: “““a‘b“c””” • Many Methods built into the string, for example: “hello”.upper() gives ‘HELLO’ • Tuples • (x,y) • (100,200,300)

  7. Sequences • Lists • [42, 3.14, ‘hello’] • list(‘wow’) gives [‘w’,’o’,’w’] • Dictionaries ( key:value pairs ) uses Hash. • D = { ‘x’ : 42, ‘y’:3.14, ‘z’:7} • {1:2 , 3:4} • A single dictionary can store values of different types • D[‘x’] is 42. • del D[‘x’] removes the key from D.

  8. Sequences • Concatenation: • S1 + S2 • S1 * n gives n copies of S1 concatenated. • Membership • x in S : tests to check whether x is in S. • x not in S : Guess? • For strings: x in S means if x is a substring of S • Indexing • x = [1,2,3,4] then x[1] is 2 and x[-1] is 4

  9. Sequences • Slicing a sequence: • S[i:j]: from item i (included) to item j (excluded) • x = [1,2,3,4] • x[1:3] # [2, 3] • x[1:] # [2, 3, 4] • x[:2] # [1, 2]

  10. List Methods

  11. List Methods

  12. List Methods

  13. List Methods • >>> a + [‘whites'] [‘blend','eggs‘,2,234,‘whites'] • >>> a.append('!') [‘blend','eggs‘,2,234,'!'] • >>> 2*a [‘blend','eggs',2,234,'!',‘blend','eggs',2,234,'!']

  14. Dictionary Methods

  15. Dictionary Methods

  16. Control Flow • if expression: statement(s) elif expression: statement(s) elif expression: statement(s) ... else: statement(s)

  17. Control Flow • if x < 0: print "x is negative" elif x % 2: print "x is positive and odd" else: print "x is even and non-negative"

  18. Control Flow : while x = 64 count = 0 while x > 0: x = x // 2 # truncating division count += 1 print "The approximate log2 is", count # if count == 6: break

  19. Control Flow : for for target in iterable: statement(s) for letter in "ciao": if letter == ‘c’: continue print "give me a", letter, "...“ for key, value in d.items( ): # cannot use iteritems if not key or not value: # keep only true keys and values del d[key] for x in range(1,5): print x # output: 1 2 3 4

  20. Sample Code #!/usr/bin/env python import string, sys # If no arguments were given, print a helpful message if len(sys.argv)==1: print 'Usage: celsius temp1 temp2 ...' sys.exit(0) # Loop over the arguments for i in sys.argv[1:]: fahrenheit=float(string.atoi(i)) celsius=(fahrenheit-32)*5.0/9.0 print '%i\260F = %i\260C' % (int(fahrenheit), int(celsius+.5))

  21. Functions def function-name(parameters): statement(s) def double(x): return x*2 Calling Functions in python function-object(arguments) print double(432) def f(x, y): x = 23 y.append(42) a = 77 b = [99] f(a, b) print a, b

  22. Import statement • A Typical python program is made up of several source files. • Each source file corresponds to a module. • “import” keyword allows to include other modules into a python program. • Modules • sys: stdin, stderr, argv • os: system, path • string: split • re: match compile • math: exp, sin, sqrt, pow

  23. Calling External programs • import os • subprocess.Popen(["ls", "-la"]).wait()

  24. Sample Program # average4.py # A program to average a set of numbers # Illustrates sentinel loop using empty string as sentinel def main(): sum = 0.0 count = 0 xStr = raw_input("Enter a number (<Enter> to quit) >> ") while xStr != "": x = eval(xStr) sum = sum + x count = count + 1 xStr = raw_input("Enter a number (<Enter> to quit) >> ") print "\nThe average of the numbers is", sum / count

  25. Output Enter a number (<Enter> to quit) >> 34 Enter a number (<Enter> to quit) >> 23 Enter a number (<Enter> to quit) >> 0 Enter a number (<Enter> to quit) >> -25 Enter a number (<Enter> to quit) >> -34.4 Enter a number (<Enter> to quit) >> 22.7 Enter a number (<Enter> to quit) >> The average of the numbers is 3.38333333333

  26. Sample Program # average5.py # Computes the average of numbers listed in a file. def main(): fileName = raw_input("What file are the numbers in? ") infile = open(fileName,'r') sum = 0.0 count = 0 for line in infile.readlines(): sum = sum + eval(line) count = count + 1 print "\nThe average of the numbers is", sum / count

  27. Sample Program # average6.py # Computes the average of numbers listed in a file. def main(): fileName = raw_input("What file are the numbers in? ") infile = open(fileName,'r') sum = 0.0 count = 0 line = infile.readline() while line != "": sum = sum + eval(line) count = count + 1 line = infile.readline() print "\nThe average of the numbers is", sum / count

  28. Assignment for today • Implement: closest_pair([(0,0),(7,6),(2,20),(12,5),(16,16),(5,8),(19,7),(14,22),(8,19),(7,29),(10,11),(1,13)]) returns: (7,6),(5,8) Should run in O(nlogn)

  29. Pointers • Learn Python in 10 minutes: • http://www.poromenos.org/tutorials/python • Dive into Python • http://www.diveintopython.org/

More Related