Python & Perl                           Lecture 06                      Vladimir Kulyukin               Department of Comp...
Outline   ●       Strings   ●       Object Comparison   ●       Loopswww.youtube.com/vkedco     www.vkedco.blogspot.com
Stringswww.youtube.com/vkedco         www.vkedco.blogspot.com
Strings      ●       Strings are immutable sequences, i.e. they cannot       be modified after they are created     >>> x ...
Strings      ●          Let us print a 2-D matrix:          matrix = [[1,    2,    3],                    [11,   22,   33]...
String Formatting      ●          C                – printf()                – sprintf()      ●          C++              ...
Basic Syntax      ●   format_str % values             –   format_str is a string to be formatted             –   % is a re...
Formatting Specifiers      ●   Full (and rather lengthy) list of specifiers is at          http://docs.python.org/library/...
Example 01        >>> x, y = 20, 5 ## x is assigned 20, y is        assigned 5        >>> "John is %d years old." % x     ...
Example 02       >>> a, b = 10, 50       >>> a       10       >>> b       50       >>> "%d is %d%% of %d" % (a, a/float(b)...
Specifier Width      ●   Specifier width is optional      ●   The width specifies the minimum number of          character...
Specifier Width      ●   The asterisk (*) is used to indicate that the          width should be read from a tuple (this is...
Specifier Precision      ●   Specifier precision is optional      ●   Precision follows width and is preceded by a period ...
Precision Examples        >>> "%f" % 123.4567 ## 10 slots are allocated by default        123.456700          ## so two ze...
Precision Examples        ## allocate a string of 10 characters and        ## take 2 characters from night.        >>> "%*...
Optional Conversion Flags      ●   The purpose of conversion flags is to convert a          specific value before it is in...
Conversion Flags: Dash (-)      ●   The value is left adjusted          ## no dash, so value is right adjusted by default....
Conversion Flags: Pound (#)      ●   Convert the value according to the specification that          follows #          ## ...
Conversion Flags: Zero (0)      ●          Pad numerical values with 0s on the left          >>> "%*d" % (10, 5)   ## defa...
Conversion Flags: Space    ●        A blank should be left before a positive number        >>> "% d" % 3         3        ...
String Module    ●   To use the string module, execute import string    ●        In general, many methods can be called as...
Functions vs. Object Methods      >>> import string      >>> string.upper("hello") ## depricated function, but still works...
String Module Constants    ●   The string module contains some useful constants           –   ascii_letters, ascii_lowerca...
string.capwords()    ●        Some methods can only be called as the string module        functions        >>> s = "poetry...
String Building    ●        String building is turning a sequence (e.g. a list or a        tuple) of characters into a str...
Obvious Solution      chars = [k, n, i, g, h, t]      myStr =  ## string to be built      for ch in chars: ## loop thru ch...
join() Solution      >>> chars = [k, n, i, g, h, t]      >>> myStr = .join(chars)      >>> myStr      knightwww.youtube.co...
Comments on Obvious Solution    ●        Obvious solutions get the job done    ●        But, they are verbose    ●        ...
Object Comparisonwww.youtube.com/vkedco          www.vkedco.blogspot.com
Object Comparison     ●         The operators <, >, ==, >=, <=, and != compare the values of         two objects     ●    ...
Object Comparison   ●       Numbers are compared arithmetically   ●       Strings are compared lexicographically using the...
Loopswww.youtube.com/vkedco           www.vkedco.blogspot.com
C/C++ while vs. Python while      ●          Common C/C++ idiom:               while ((x = next()) != NULL) {             ...
Python while Example        ## print numbers from 1 upto 100        x = 1        while x <= 100:              print x     ...
Problem     Write a Python script that asks the user for his/her     name until the user actually enters a stringwww.youtu...
Coding Solution 1        ### keep asking for name until the user types        ### something; not  evaluates to True       ...
Coding Solution 2        ### keep asking for name until the user types        ### something that does not consist only of ...
for Loops      ●          Syntax               for targetList in IterableObject:                     code block      ●   I...
for Loop Example        ## prints (1, 2) and (3, 4) on separate        ## lines        for x in ((1, 2), (3, 4)):         ...
Loop Else      ●          Both for loops and while loops have an extended form not usually seen          in other language...
Using Loop Else    ●        The else block of a loop is run if the loop exits        normally    ●        Use of continue ...
Reading & References  ●      www.python.org  ●      Ch 03 (Strings), M. L. Hetland. Beginning Python From      Novice to P...
Feedback   Bugs, comments to vladimir dot kulyukin at usu dot eduwww.youtube.com/vkedco             www.vkedco.blogspot.com
Upcoming SlideShare
Loading in...5
×

Python & Perl: Lecture 06

991

Published on

Published in: Technology, Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
991
On Slideshare
0
From Embeds
0
Number of Embeds
19
Actions
Shares
0
Downloads
0
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Transcript of "Python & Perl: Lecture 06"

  1. 1. Python & Perl Lecture 06 Vladimir Kulyukin Department of Computer Science Utah State Universitywww.youtube.com/vkedco www.vkedco.blogspot.com
  2. 2. Outline ● Strings ● Object Comparison ● Loopswww.youtube.com/vkedco www.vkedco.blogspot.com
  3. 3. Stringswww.youtube.com/vkedco www.vkedco.blogspot.com
  4. 4. Strings ● Strings are immutable sequences, i.e. they cannot be modified after they are created >>> x = [1, 2, 3] >>> x[1] = 5555 # this is OK >>> y = (1, 2, 3) >>> y[1] = 9999 # error >>> z = spam >>> z[1] = P # errorwww.youtube.com/vkedco www.vkedco.blogspot.com
  5. 5. Strings ● Let us print a 2-D matrix: matrix = [[1, 2, 3], [11, 22, 33], [111, 222, 333]] for row in matrix: for col in row: print col, print ## this prints n ● If you run the above for loop, you notice that the numbers do not line up nicelywww.youtube.com/vkedco www.vkedco.blogspot.com
  6. 6. String Formatting ● C – printf() – sprintf() ● C++ <iomanip> – ● Python – string formatting is similar to Cwww.youtube.com/vkedco www.vkedco.blogspot.com
  7. 7. Basic Syntax ● format_str % values – format_str is a string to be formatted – % is a required operator – values specify formatting values – values must specify a value for every specifier that format_str contains.www.youtube.com/vkedco www.vkedco.blogspot.com
  8. 8. Formatting Specifiers ● Full (and rather lengthy) list of specifiers is at http://docs.python.org/library/stdtypes.html#string-formatting-operations ● Some common specifiers that you are likely to use in your programs are: – %d signed integer – %x unsigned hexadecimal – %f floating point decimal format – %s string (converted using str()) – %% a percent signwww.youtube.com/vkedco www.vkedco.blogspot.com
  9. 9. Example 01 >>> x, y = 20, 5 ## x is assigned 20, y is assigned 5 >>> "John is %d years old." % x John is 20 years old. >>> "John is %d years and %d months old." % (x, y) John is 20 years and 5 months old.www.youtube.com/vkedco www.vkedco.blogspot.com
  10. 10. Example 02 >>> a, b = 10, 50 >>> a 10 >>> b 50 >>> "%d is %d%% of %d" % (a, a/float(b)*100, b) 10 is 20% of 50www.youtube.com/vkedco www.vkedco.blogspot.com
  11. 11. Specifier Width ● Specifier width is optional ● The width specifies the minimum number of characters for the formatted value: >>> "%d" % 2 2 >>> "%2d" % 2 ### 2 characters wide 2 >>> "%3d" % 2 ### 3 characters wide 2www.youtube.com/vkedco www.vkedco.blogspot.com
  12. 12. Specifier Width ● The asterisk (*) is used to indicate that the width should be read from a tuple (this is a typical use of tuples) >>> "%*d" % (4, 2) 2 ● The above formatting instruction "%*d" % (4, 2) means: allocate 4 fields for the digit 2www.youtube.com/vkedco
  13. 13. Specifier Precision ● Specifier precision is optional ● Precision follows width and is preceded by a period ● You can use asterisk to get precision from a value tuple ● For numbers, precision specifies the number of decimals included in result ● For strings, precision specifies the maximum number of characterswww.youtube.com/vkedco www.vkedco.blogspot.com
  14. 14. Precision Examples >>> "%f" % 123.4567 ## 10 slots are allocated by default 123.456700 ## so two zeros are padded at the end >>> "%f" % 123.456789 123.456789 ## all ten slots are taken >>> "%.0f" % 123.456789 123 ## the decimal part is chopped off >>> "%.2f" % 123.456789 123.46 ## 2 decimal slots are preserved. Note the rounding >>> "%10.3f" % 12345.6789 12345.679 ## 10 slots before the decimal point and 3 after >>> "%2.3f" % 12345.6789 12345.679 ## we could not get 2 slots before the point.www.youtube.com/vkedco www.vkedco.blogspot.com
  15. 15. Precision Examples ## allocate a string of 10 characters and ## take 2 characters from night. >>> "%*.*s" % (10, 2, night) ni ## allocate a string of 10 characters and ## take 3 characters from night. >>> "%*.*s" % (10, 3, night) nig ## allocate a string of 5 characters and take 4 ## characters from night. >>> "%*.*s" % (5, 4, night) nighwww.youtube.com/vkedco www.vkedco.blogspot.com
  16. 16. Optional Conversion Flags ● The purpose of conversion flags is to convert a specific value before it is inserted into the format string ● A conversion flag, when present, must occur before width and precision ● Here are a few common conversion flags: dash (-), pound sign (#), zero (0), spacewww.youtube.com/vkedco www.vkedco.blogspot.com
  17. 17. Conversion Flags: Dash (-) ● The value is left adjusted ## no dash, so value is right adjusted by default. >>> "%4d" % 2 2 ## there is a dash, so value is left adjusted. >>> "%-4d" % 2 2 ## allocate 10 characters, take 2 characters from ## night and left adjust them. >>> "%-*.*s" % (10, 2, night) ni www.youtube.com/vkedco www.vkedco.blogspot.com
  18. 18. Conversion Flags: Pound (#) ● Convert the value according to the specification that follows # ## convert 17 into octal representation. >>> "%#o" % 17 021 ## convert 17 into hexadecimal representation. >>> "%#x" % 17 0x11www.youtube.com/vkedco www.vkedco.blogspot.com
  19. 19. Conversion Flags: Zero (0) ● Pad numerical values with 0s on the left >>> "%*d" % (10, 5) ## default behavior 5 >>> "%0*d" % (10, 5) ## allocate 10 slots and pad with 0s 0000000005 >>> "%*.*f" % (10, 2, 123.456789) ## default behavior 123.46 ## allocate 10 slots, take 2 numbers after the decimal ## point and pad the remaining left slots with 0s. >>> "%0*.*f" % (10, 2, 123.456789) 0000123.46www.youtube.com/vkedco www.vkedco.blogspot.com
  20. 20. Conversion Flags: Space ● A blank should be left before a positive number >>> "% d" % 3 3 >>> "% d" % -3 ## converts to empty string for ## negative numbers -3www.youtube.com/vkedco www.vkedco.blogspot.com
  21. 21. String Module ● To use the string module, execute import string ● In general, many methods can be called as functions of the string module (many of these are depricated) or as methods on string objects ● Calling methods on string objects is preferredwww.youtube.com/vkedco www.vkedco.blogspot.com
  22. 22. Functions vs. Object Methods >>> import string >>> string.upper("hello") ## depricated function, but still works HELLO >>> "hello".upper() ## preferred object method HELLO >>> x = " hello " >>> string.strip(x) ## depricated function, but still works hello >>> x hello >>> x.strip() ## preferred object method hellowww.youtube.com/vkedco www.vkedco.blogspot.com
  23. 23. String Module Constants ● The string module contains some useful constants – ascii_letters, ascii_lowercase, ascii_uppercase – digits, hexdigits, letters – lowercase, octdigits – punctuation, printable, uppercase, whitespace >>> import string >>> string.ascii_letters abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUV WXYZ >>> string.punctuation !"#$%&()*+,-./:;<=>?@[]^_`{|}~www.youtube.com/vkedco www.vkedco.blogspot.com
  24. 24. string.capwords() ● Some methods can only be called as the string module functions >>> s = "poetry, music, and math" >>> string.capwords(s) Poetry, Music, And Math >>> s.capwords() ## errorwww.youtube.com/vkedco www.vkedco.blogspot.com
  25. 25. String Building ● String building is turning a sequence (e.g. a list or a tuple) of characters into a string ● For example, start with this: [k, n, i, g, h, t] ● End with this: knightwww.youtube.com/vkedco www.vkedco.blogspot.com
  26. 26. Obvious Solution chars = [k, n, i, g, h, t] myStr = ## string to be built for ch in chars: ## loop thru chars myStr += ch ## print chars and myStr. print chars = , chars print myStr = , myStrwww.youtube.com/vkedco www.vkedco.blogspot.com
  27. 27. join() Solution >>> chars = [k, n, i, g, h, t] >>> myStr = .join(chars) >>> myStr knightwww.youtube.com/vkedco www.vkedco.blogspot.com
  28. 28. Comments on Obvious Solution ● Obvious solutions get the job done ● But, they are verbose ● We can solve both string building problems by using the join() methodwww.youtube.com/vkedco www.vkedco.blogspot.com
  29. 29. Object Comparisonwww.youtube.com/vkedco www.vkedco.blogspot.com
  30. 30. Object Comparison ● The operators <, >, ==, >=, <=, and != compare the values of two objects ● The objects need not have the same type ● If both are numbers, they are converted to a common type ● Objects of different types always compare unequal and are ordered consistently but arbitrarily: – (1) < [1] ### True – [1] < (1) ### Falsewww.youtube.com/vkedco www.vkedco.blogspot.com
  31. 31. Object Comparison ● Numbers are compared arithmetically ● Strings are compared lexicographically using the numeric equivalents of their characters ● Tuples and lists are compared lexicographically using comparison of corresponding elements ● Sequences, to compare equal, must be of the same type and have the same length and the corresponding elements must compare equal ● Mappings (dictionaries) compare equal if and only if their sorted (key, value) lists compare equalwww.youtube.com/vkedco www.vkedco.blogspot.com
  32. 32. Loopswww.youtube.com/vkedco www.vkedco.blogspot.com
  33. 33. C/C++ while vs. Python while ● Common C/C++ idiom: while ((x = next()) != NULL) { // Some code } ● Python while loops may not have assignments in the test statements: x = next() while x: ## some code x = next()www.youtube.com/vkedco www.vkedco.blogspot.com
  34. 34. Python while Example ## print numbers from 1 upto 100 x = 1 while x <= 100: print x x += 1www.youtube.com/vkedco www.vkedco.blogspot.com
  35. 35. Problem Write a Python script that asks the user for his/her name until the user actually enters a stringwww.youtube.com/vkedco www.vkedco.blogspot.com
  36. 36. Coding Solution 1 ### keep asking for name until the user types ### something; not evaluates to True name = while not name: name = raw_input(Please enter your name: ) print Hello, %s! % namewww.youtube.com/vkedco www.vkedco.blogspot.com
  37. 37. Coding Solution 2 ### keep asking for name until the user types ### something that does not consist only of white ### spaces; not evaluates to True name= while not name.strip(): name=raw_input(Please enter your name: ) print Hello, %s! % namewww.youtube.com/vkedco www.vkedco.blogspot.com
  38. 38. for Loops ● Syntax for targetList in IterableObject: code block ● IterableObject is (usually) a sequence and returns its elements one at a time in order ● targetList is one or more comma separated reference nameswww.youtube.com/vkedco www.vkedco.blogspot.com
  39. 39. for Loop Example ## prints (1, 2) and (3, 4) on separate ## lines for x in ((1, 2), (3, 4)): print x ## prints 1 2 and 3 4 on separate lines for x,y in ((1, 2), (3, 4)): print x, ywww.youtube.com/vkedco www.vkedco.blogspot.com
  40. 40. Loop Else ● Both for loops and while loops have an extended form not usually seen in other languages while expression: code block else: code block for targetList in IterableObject: code block else: code blockwww.youtube.com/vkedco www.vkedco.blogspot.com
  41. 41. Using Loop Else ● The else block of a loop is run if the loop exits normally ● Use of continue allows the loop to exit normally ● If the loop exits because of a break, the else block is not runwww.youtube.com/vkedco www.vkedco.blogspot.com
  42. 42. Reading & References ● www.python.org ● Ch 03 (Strings), M. L. Hetland. Beginning Python From Novice to Professional, 2nd Ed., APRESS ● Ch 05 (Object Comparison, Loops), M. L. Hetland. Begin- ning Python From Novice to Professional, 2nd Ed., APRESSwww.youtube.com/vkedco www.vkedco.blogspot.com
  43. 43. Feedback Bugs, comments to vladimir dot kulyukin at usu dot eduwww.youtube.com/vkedco www.vkedco.blogspot.com

×