Anúncio
Anúncio

Mais conteúdo relacionado

Anúncio

Python_Unit_III.pptx

  1. Built-in Data structures Strings
  2. Strings • Strings in Python have type str • They represent sequence of characters – Python does not have a type corresponding to character. • Strings are enclosed in single quotes(') or double quotes(“) – Both are equivalent • Backslash () is used to escape quotes and special characters
  3. Strings • More readable when print is used
  4. Length of a String • len function gives the length of a string n is a single character: the special character representing newline
  5. Concatenate and Repeat • In Python, + and * operations have special meaning when operating on strings • + is used for concatenation of (two) strings • * is used to repeat a string, an int number of time • Function/Operator Overloading
  6. Concatenate and Repeat
  7. Indexing • Strings can be indexed • First character has index 0
  8. Indexing • Negative indices start counting from the right • Negatives indices start from -1 • -1 means last, -2 second last, ...
  9. Indexing • Using an index that is too large or too small results in “index out of range” error
  10. Slicing • To obtain a substring • s[start:end] means substring of s starting at index start and ending at index end-1 • s[0:len(s)] is same as s • Both start and end are optional – If start is omitted, it defaults to 0 – If end is omitted, it defaults to the length of string • s[:] is same as s[0:len(s)], that is same as s
  11. Slicing
  12. More Slicing A c a d s 0 1 2 3 4 -5 -4 -3 -2 -1 Understanding Indices for slicing 5
  13. Out of Range Slicing • Out of range indices are ignored for slicing • when start and end have the same sign, if start >=end, empty slice is returned Why? A c a d s 0 1 2 3 4 -5 -4 -3 -2 -1
  14. Changing Case • string.capitalize() : returns a string with the first character capitalized and all the rest in lower case. >>> s1 = "eXamPLe tEXt" >>> s1.capitalize() Output: 'Example text' • string.title() : capitalize every single word in the string, leaving everything else as lowercase. >>> s1.title() Output: 'Example Text'
  15. Changing Case • string.upper() : convert the whole string to uppercase. >>> s1 = "eXamPLe tEXt" >>> s1.upper() Output: 'EXAMPLE TEXT‘ • string.lower() : convert the whole string to lowercase. >>> s1.lower() Output: ‘example text' • string.swapcase() : returns a copy of string with the uppercase characters converted to lowercase and vice versa. >>> s1.swapcase() Output: 'ExAMplE TexT'
  16. Editing Strings • string.strip([chars]) : returns a copy of the string with chars removed from the beginning and the end if the sequence is found. If no arguments are given, then remove whitespace characters by default. >>> s2=' hello world' >>> s2.strip() Output: 'hello world' >>> s2=' hello world ' >>> s2.strip() Output: 'hello world‘ >>> s2='hello world' >>> s2.strip('he') Output: 'llo world' >>> s2.strip('world') Output: 'hello '
  17. Editing Strings • string.lstrip([chars]): only strip characters from the start of the string. >>> s='hello worldhe' >>> s.strip('he') Output: 'llo world' >>> s.lstrip('he') Output: 'llo worldhe‘ • string.rstrip([chars]): only strip characters from the end of the string. • string.replace(old, new) : replace all occurrences of one substring with another. >>> s2='Hello World' >>> s2.replace('H', 'J') Output: 'Jello World‘
  18. Finding Strings • string.find([char]): get the position of the character in the string. >>> s='hello world' >>> s.find('h') Output: 0 >>> s.find('w') Output: 6 • string.count([chars]): count the number of times a substring occurs in a string. >>> s.count('o') Output: 2 • string.endswith([chars]): check the string, whether it ends with specified characters or not. (True/False) >>> s.endswith('d') Output: True >>> s.endswith('ld') Output: True >>> s.endswith('o') Output: False
  19. Assignment-1 Q1. Write a program that reads full name as a input and returns abbreviations of the first and middle names except the last name. (Note that the abbreviations must be in capitals. Also, only the first letter in the Surname must be in upper case). Example : Input: Sachin Ramesh Tendulkar Output: S. R. Tendulkar Q2. Write a program that reads names of two python files and strips the extension. The filenames are then concatenated to form a single string. The program then prints 'True' if the newly generated string is palindrome, or prints 'False' otherwise. Example : Input: malay.py aLam.py Output: True
  20. Lists • Ordered sequence of values • Written as a sequence of comma-separated values between square brackets • Values can be of different types – usually the items all have the same type • Lists are mutable, which means we can add or remove items from a list.
  21. Lists • List is also a sequence type – Sequence operations are applicable
  22. Lists • List is also a sequence type – Sequence operations are applicable Repetition ( )
  23. More Operations on Lists • L.append(x) • L.extend(seq) • L.insert(i, x) • L.remove(x) • L.pop(i) • L.pop() • L.index(x) • L.count(x) • L.sort() • L.reverse() • max(L) • min(L) • test x in L • test x not in L x is any value, seq is a sequence value (list, string, tuple, …), i is an integer value
  24. Programming Exercise Q16. Write a python program to perform following tasks: - Read a list of integers from a user. - Remove duplicate values from this list. We call it a super list. Display contents of the super list Q17. In a single scan of the super list (generated in Q16), perform following operations: - If the number is not perfectly divisible by 3, discard it. - If the number is greater than 30, add 5 to it. Else, subtract 5 from it. - Display contents of the list.
  25. Tuples • A tuple consists of a number of values separated by commas • Empty and Singleton Tuples
  26. Nested Tuples • Tuples can be nested • Note that course tuple is copied into student. – Changing course does not affect student
  27. More Operations on Tuples • Tuples can be concatenated, repeated, indexed and sliced
  28. Unpacking Sequences • Strings and Tuples are examples of sequences – Indexing, slicing, concatenation, repetition operations applicable on sequences • Sequence Unpacking operation can be applied to sequences to get the components – Multiple assignment statement – LHS and RHS must have equal length
  29. Unpacking Sequences ( )
  30. Programming Exercise Q18. Write a python program to perform following tasks: - Read tuple elements (integers) from a user. - Display the sum of tuple elements. - Count the number of occurrence of each element from a tuple
  31. Sets • An unordered collection with no duplicate elements • Supports – membership testing – eliminating duplicate entries – Set operations: union, intersection, difference, and symmetric difference.
  32. Sets Create a set from a sequence { }
  33. Set Operations { } { } { } { { }
  34. Dictionaries • Unordered set of key:value pairs, • Keys have to be unique and immutable • Key:value pairs enclosed inside curly braces {...} • Empty dictionary is created by writing {} • Dictionaries are mutable – add new key:value pairs, – change the pairing – delete a key (and associated value)
  35. Operations on Dictionaries Operation Meaning len(d) Number of key:value pairs in d d.keys() List containing the keys in d d.values() List containing the values in d k in d True if key k is in d d[k] Value associated with key k in d d.get(k, v) If k is present in d, then d[k] else v d[k] = v Map the value v to key k in d (replace d[k] if present) del d[k] Remove key k (and associated value) from d for k in d Iterate over the keys in d
  36. Operations on Dictionaries
  37. Operations on Dictionaries
  38. Operations on Dictionaries # Remember: for ... in iterates over keys only # Sort values in a list
  39. Dictionary Construction • The dict constructor: builds dictionaries directly from sequences of key-value pairs
  40. Programming Exercise Q19. Given a piece of text, write a program to build a frequency listing of words and display them in a sorted order on 'key'.
  41. File Operations in Python
  42. File I/O • A file is a place on disk where group of related data are stored. • Files are persistent storage • Allow data to be stored beyond program lifetime • The basic operations on files are – open(), close(), read(), write() • Python treat files as sequence of lines – sequence operations work for the data read from files
  43. File I/O: open and close open(filename, mode) • While opening a file, you need to supply – The name of the file, including the path – The mode in which you want to open a file – Common modes are r (read), w (write), a (append) • Mode is optional, defaults to r • open(..) returns a file object • close() on the file object closes the file – finishes any buffered operations
  44. • r+ opens a text file in both reading and writing mode • w+ opens a text file in both reading and writing mode • a+ opens a text file in both reading and append mode • rb opens a binary file in reading mode • wb opens or create a binary file in writing mode • ab opens a binary file in append mode • rb+ opens a binary file in both reading and writing mode • wb+ opens a binary file in both reading and writing mode • ab+ opens a binary file for both reading as well as appending.
  45. File I/O: Example • Do some writing
  46. File I/O: read, write and append • Reading from an open file returns the contents of the file – as sequence of lines in the program • Writing to a file – IMPORTANT: If opened with mode 'w', clears the existing contents of the file – Use append mode ('a') to preserve the contents – Writing happens at the end
  47. File I/O: Examples
  48. File I/O: Examples ( ( ) )
  49. File I/O: Examples Note empty line due to 'n' ( )
  50. File I/O: Examples Note the use of for ... in for sequence ] ( )
  51. File I/O: Examples ( ) ( ) ( )
  52. Random access to files • How to jump to a given position (byte number) in a file without reading all the previous data? • seek (offset, position); • position: 0 (beginning), 1 (current), 2 (end) • offset: number of locations to move from position Example: fo.seek(-m, 1); /* move back by m bytes from current position */ fo.seek(m,0); /* move to (m+1)th byte in file */ fo.seek(-10, 2); • fo.tell( ) returns current byte position in file
  53. Some more read & write functions • read() : This function reads the entire file and returns a string. • readline() : This function reads lines from that file and returns as a string. • readlines() : This function returns a list where each element is a single line of that file. • write() : This function writes a fixed sequence of characters to a file. • writelines() : This function write a list of string
  54. Programming Exercise Q20. Write a python program to read the content from the text file “file.txt” line by line and display the same on screen. Q21. Write a python program to count and display the total number of words in a text file “file.txt”. Q22. Write a python program to perform writing and reading few lines in a text file .
  55. Exception Handling in Python
  56. Syntax errors • Syntax errors are generated if the rules for syntax are not followed while writing a script in Python. • Syntax errors are the most basic type of errors. • There is no way to successfully execute a piece of code containing syntax errors. • Most syntax errors are typos (i.e., typing errors), incorrect indentation or incorrect arguments.
  57. Exception • An exception is an error, which happens during the execution of a program, that disrupts the normal flow of the program's instructions. • In general, when a Python script encounters a situation that it can't cope with, it raises an exception. • For example, trying to open a file that does not exist, division by zero and so on. Such types of errors might disrupt the normal execution of the program and are called exceptions.
  58. The raise Statement • The raise statement can be used to throw an exception. • The syntax of raise statement is: raise exception-name[(optional argument)] • The argument is generally a string that is displayed when the exception is raised. • The error detected may be a built-in exception or may be a user-defined one
  59. Built-in exceptions
  60. The assert Statement • An assert statement in Python is used to test an expression in the program code. • The syntax for assert statement is: assert Expression[,arguments] • If this expression is false, an AssertionError exception is raised which can be handled like any other exception.
  61. Example-The assert Statement print("use of assert statement") def negativecheck(number): assert(number>=0), "OOPS... Negative Number“ print(number*number) print (negativecheck(100)) print (negativecheck(-350)) use of assert statement 10000 None Traceback (most recent call last): File "C:/Python32/Assert.py", line 6, in <module> print (negativecheck(-350)) File "C:/Python32/Assert.py", line 3, in negativecheck assert(number>=0), "OOPS... Negative Number" AssertionError: OOPS... Negative Number
  62. Exception Handling • Every exception has to be handled by the programmer. • This is done by writing additional code in a program to give proper messages or instructions to the user on encountering an exception. • This process is known as exception handling.
  63. Catching Exceptions • Exceptions, if any, are caught in the try block and handled in the except block. • The syntax of try … except clause is as follows: try: [program statements where exceptions might occur] except [exception-name]: [code for exception handling if the exception-name error is Encountered]
  64. Example-Catching Exceptions print ("Practicing for try block") try: numerator=50 denom=int(input("Enter the denominator")) quotient=(numerator/denom) print ("Division performed successfully") except ZeroDivisionError: print ("Denominator as ZERO.... not allowed") print(“OUTSIDE try..except block”)
  65. Multiple except clauses print ("Handling multiple exceptions") try: numerator=50 denom=int(input("Enter the denominator: ")) print (numerator/denom) print ("Division performed successfully") except ZeroDivisionError: print ("Denominator as ZERO is not allowed") except ValueError: print ("Only INTEGERS should be entered")
  66. except without specifying an exception print ("Handling multiple exceptions") try: numerator=50 denom=int(input("Enter the denominator: ")) print (numerator/denom) print ("Division performed successfully") except ZeroDivisionError: print ("Denominator as ZERO is not allowed") except : print(" OOPS.....SOME EXCEPTION RAISED")
  67. try...except…else clause print ("Handling exception using try...except...else") try: numerator=50 denom=int(input("Enter the denominator: ")) quotient=(numerator/denom) print ("Division performed successfully") except ZeroDivisionError: print ("Denominator as ZERO is not allowed") except ValueError: print ("Only INTEGERS should be entered") else: print ("The result of division operation is ", quotient)
  68. finally clause • finally should always be placed at the end of try clause, after all except blocks and the else block. • The statements inside the finally block are always executed regardless of whether an exception has occurred in the try block or not.
  69. Example-finally clause try: print ("Handling exception using try...except...else...finally") numerator=50 denom=int(input("Enter the denominator: ")) quotient=(numerator/denom) print ("Division performed successfully") except ZeroDivisionError: print ("Denominator as ZERO is not allowed") except ValueError: print ("Only INTEGERS should be entered") else: print ("The result of division operation is ", quotient) finally: print ("OVER AND OUT“)
  70. Modules and Packages
  71. Modules • As program gets longer, need to organize them for easier access and easier maintenance. • Reuse same functions across programs without copying its definition into each program. • Python allows putting definitions in a file – use them in a script or in an interactive instance of the interpreter • Such a file is called a module – definitions from a module can be imported into other modules or into the main module
  72. Modules • A module is a file containing Python definitions and statements. • The file name is the module name with the suffix .py appended. • Within a module, the module’s name is available in the global variable __name__.
  73. Modules Example fib.py - C:
  74. Modules Example Within a module, the module’s name is available as the value of the global variable __name__.
  75. Importing Specific Functions • To import specific functions from a module • This brings only the imported functions in the current symbol table – No need of modulename. (absence of fib. in the example)
  76. Importing ALL Functions • To import all functions from a module, in the current symbol table • This imports all names except those beginning with an underscore (_).
  77. __main__ in Modules • When you run a module on the command line with python fib.py <arguments> the code in the module will be executed, just as if you imported it, but with the __name__ set to "__main__". • By adding this code at the end of your module if __name__ == "__main__": ... # Some code here you can make the file usable as a script as well as an importable module
  78. __main__ in Modules if __name__ == "__main__": import sys print (fib_iter(int(sys.argv[1]))) • This code parses the command line only if the module is executed as the “main” file: $ python fib.py 10 55 • If the module is imported, the code is not run: >>> import fib >>>
  79. Package • A Python package is a collection of Python modules. • Another level of organization. • Packages are a way of structuring Python’s module namespace by using dotted module names. – The module name A.B designates a submodule named B in a package named A. – The use of dotted module names saves the authors of multi-module packages like NumPy or Pillow from having to worry about each other’s module names.
  80. https://docs.python.org/3/tutorial/modules.html A sound Package
  81. https://docs.python.org/3/tutorial/modules.html A sound Package What are these files with funny names?
  82. __init.py__ • The __init__.py files are required to make Python treat directories containing the file as packages. • This prevents directories with a common name, such as string, unintentionally hiding valid modules that occur later on the module search path. • __init__.py can just be an empty file • It can also execute initialization code for the package
  83. Importing Modules from Packages https://docs.python.org/3/tutorial/modules.ht ml
  84. Importing Modules from Packages import sound.effects.echo • Loads the submodule sound.effects.echo • It must be referenced with its full name: sound.effects.echo.echofilter( input, output, delay=0.7, atten=4 )
  85. Importing Modules from Packages from sound.effects import echo • This also loads the submodule echo • Makes it available without package prefix • It can be used as: echo.echofilter( input, output, delay=0.7, atten=4 )
  86. Importing Modules from Packages from sound.effects.echo import echofilter • This loads the submodule echo, but this makes its function echofilter() directly available. echofilter(input, output, delay=0.7, atten=4)
Anúncio