Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

9

Share

Download to read offline

Python (basic)

Download to read offline

A brief introduction to Python (basic level)

Python (basic)

  1. 1. Python (Basic) Sabyasachi Moitra Ph.D. Scholar(Techno India University)
  2. 2. Introduction CompilingandInterpreting FirstPythonProgram OVERVIEW
  3. 3. Introduction Developed by Guido van Rossum in the early 1990s. Features: • High-level powerful programming language • Interpreted language • Object-oriented • Portable • Easy to learn & use • Open source • Derived from many other programming languages 3
  4. 4. Introduction (2) Uses: • Internet Scripting • Image Processing • Database Programming • Artificial Intelligence ….. 4
  5. 5. Compiling and Interpreting • Many languages compile (translate) the program into a machine understandable form. • Python is directly interpreted into machine instructions. 5 compile execute ----------> ----------> Source code Intermediate code Output interpret ----------> Source code Output
  6. 6. Compiling and Interpreting (2) Compiler Interpreter Scans the entire program and translates it as a whole into machine code. Translates program one statement at a time. It takes large amount of time to analyze the source code but the overall execution time is comparatively faster. It takes less amount of time to analyze the source code but the overall execution time is slower. Generates intermediate object code which further requires linking, hence requires more memory. No intermediate object code is generated, hence are memory efficient. It generates the error message only after scanning the whole program. Hence debugging is comparatively hard. Continues translating the program until the first error is met, in which case it stops. Hence debugging is easy. Programming language like C, C++ use compilers. Programming language like Python, Ruby use interpreters. 6
  7. 7. First Python Program (Hello.py) 7
  8. 8. Output 8
  9. 9. InteractiveModeProgrammingVSScriptModeProgramming Identifiers ReservedWords LinesandIndentation SomemoreBasicSyntax BASIC SYNTAX
  10. 10. Interactive Mode Programming VS Script Mode Programming Interactive Mode Programming Script Mode Programming Invoking the interpreter without passing a script file as a parameter brings up the Python prompt. Type a python statement at the prompt and press Enter. Invoking the interpreter with a script parameter, & begins execution of the script and continues until the script is finished. When the script is finished, the interpreter is no longer active (assuming that user have Python interpreter set in PATH variable). C:Usersmoitra>python Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit ( Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> print("Hello World") Hello World G:2. DOCUMENTSPythonPrograms>pytho n test.py Hello World 10
  11. 11. Identifiers • A Python identifier is a name used to identify a variable, function, class, module or other object. • An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9). • Python does not allow punctuation characters such as @, $, and % within identifiers. • Python is a case sensitive programming language. Manpower and manpower are two different identifiers in Python. 11
  12. 12. Reserved Words and exec not assert finally or break for pass class from print continue global raise def if return del import try elif in while else is with except lambda yield and exec not 12
  13. 13. Lines and Indentation • Python provides no braces to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation. • The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount. 13 Correct Erroneous if True: print "True" else: print "False" if True: print "Answer" print "True" else: print "Answer" print "False"
  14. 14. Basic Syntax (5) Example Multi-Line Statements total = item_one + item_two + item_three Comments in Python print "Hello World" # comment Multiple Statements on a Single Line x = 'foo'; print(x + 'n') ….. 14
  15. 15. StandardDataTypes OtherOperations SomeTypeConversions VARIABLE TYPES
  16. 16. Standard Data Types Standard Data Type Example Numbers counter = 100 miles = 1000.0 String name = "John" List tinylist = [123, 'john'] Tuple tinytuple = (123, 'john') Dictionary tinydict = {'name': 'john','code':6734, 'dept': 'sales'} 16
  17. 17. Other Operations Operation Example Multiple Assignment a = b = c = 1 a,b,c = 1,2,"john" Delete del var1[,var2[,var3[....,varN]]]] 17 Some Type Conversions Function Description int(x) Converts x to an integer number str(x) Converts x to a string representation list(s) Converts s to a list tuple(s) Converts s to a tuple dict(d) Creates a dictionary d …..
  18. 18. TypesofOperator BASIC OPERATORS
  19. 19. Types of Operator Type Operators Arithmetic Operators +, -, *, /, %, ** (exponent), // (floor division) Relational Operators ==, !=, >, <, >=, <= Assignment Operators =, +=, -=, *=, /=, %=, **=, //= Logical Operators and, or, not Bitwise Operators &, |, ~, ^, <<, >> Membership Operators in, not in Identity Operators is, not is 19
  20. 20. Addition of two nos. add.py #addition of two numbers a=raw_input("Enter 1st no.: ") b=raw_input("Enter 2nd no.: ") c=int(a)+int(b) print('The sum of {0} and {1} is {2}'.format(a, b, c)) Output G:2. DOCUMENTSPythonPrograms>python add.py Enter 1st no.: 1 Enter 2nd no.: 2 The sum of 1 and 2 is 3 20
  21. 21. Simpleifstatement if…elsestatement nestedifstatement elif Statement DECISION MAKING
  22. 22. Simple if statement simple_if.py #even no. check a=input("Enter a no: ") if(a%2==0): print('{0} is even'.format(a)) Output 22 if even if not even G:2. DOCUMENTSPythonPrograms >python simple_if.py Enter a no: 10 10 is even G:2. DOCUMENTSPythonPrograms >python simple_if.py Enter a no: 11
  23. 23. if…else statement if_else.py #even-odd no. check a=input("Enter a no: ") if(a%2==0): print('{0} is even'.format(a)) else: print('{0} is odd'.format(a)) Output 23 if even if not even G:2. DOCUMENTSPythonPrograms >python if_else.py Enter a no: 10 10 is even G:2. DOCUMENTSPythonPrograms >python if_else.py Enter a no: 11 11 is odd
  24. 24. nested if statement (nested_if.py) 24
  25. 25. Output 25
  26. 26. elif Statement (else_if_ladder.py) 26
  27. 27. Output 27
  28. 28. while Loop forLoop nestedLoop LOOPING
  29. 29. while Loop while_loop.py i=1 while(i<=5): print(i) i=i+1 Output G:2. DOCUMENTSPythonPrograms>python while_loop.py 1 2 3 4 5 29
  30. 30. for Loop for_loop.py for i in range(1,6): print(i) Output G:2. DOCUMENTSPythonPrograms>python for_loop.py 1 2 3 4 5 30
  31. 31. nested Loops (prime_factor.py) 31
  32. 32. Output 32
  33. 33. NumericalTypes NumericFunctions MathematicalConstants PYTHON NUMBERS
  34. 34. Python Numbers (1) • Python supports four different numerical types: • Python also includes some predefined numeric functions: 34 int long float complex 10 51924361L 15.20 -.6545+26J Type Function Description Example Mathematical pow(x, y) The value of x**y import math print "math.pow(2, 4) : ", math.pow(2, 4) math.pow(2, 4) : 16.0 abs(x) The absolute value of x print "abs(-45) : ", abs(-45) abs(-45) : 45 …..
  35. 35. Python Numbers (2) Type Function Description Example Random Number choice(seq) A random item from a list, tuple, or string import random print "choice([1, 2, 3, 5, 9]) : ", random.choice([1, 2, 3, 5, 9]) choice([1, 2, 3, 5, 9]) : 2 shuffle(lst) Randomizes the items of a list in place. Returns None import random list = [20, 16, 10, 5]; random.shuffle(list) print "Reshuffled list : ", list Reshuffled list : [16, 5, 10, 20] ….. 35
  36. 36. Python Numbers (3) Type Function Description Example Trigonometric sin (x) Return the sine of x radians import math print "sin(3) : ", math.sin(3) sin(3) : 0.14112000806 cox (x) Return the cosine of x radians import math print “cos(3) : ", math.cos(3) sin(3) : 0.14112000806 ….. 36
  37. 37. Python Numbers (4) • Python also supports two mathematical constants: pi e 37
  38. 38. Example Built-inStringMethods PYTHON STRINGS
  39. 39. Python Strings (1) str = 'Hello World!' print str # Prints complete string print str[0] # Prints first character of the string print str[2:5] # Prints characters starting from 3rd to 5th print str[2:] # Prints string starting from 3rd character print str * 2 # Prints string two times print str + "TEST" # Prints concatenated string print "Updated String :- ", str[:6] + 'Python' Output Hello World! H llo llo World! Hello World!Hello World! Hello World!TEST Updated String :- Hello Python 39
  40. 40. Python Strings (2) 40 Python includes some built-in methods to manipulate strings: String Method Description Example capitalize() Capitalizes first letter of string str = "this is string example....wo w!!!"; print "str.capitali ze() : ", str.capitaliz e() str.capitalize() : This is string example....wow!!! len() Returns the length of the string str = "this is string example....wo w!!!"; print "Length of the string: ", len(str) Length of the string: 32 …..
  41. 41. Example BasicListOperations FunctionsVSMethods Built-inListFunctions Built-inListMethods PYTHON LISTS
  42. 42. Python Lists (1) list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] tinylist = [123, 'john'] print list # Prints complete list print list[0] # Prints first element of the list print list[-1] # Prints last element of the list print list[1:3] # Prints elements starting from 2nd till 3rd print list[2:] # Prints elements starting from 3rd element print tinylist * 2 # Prints list two times print list + tinylist # Prints concatenated lists list[0] = 'efgh'; # updating list print list del list[2]; # deleting list element print list 42
  43. 43. Python Lists (2) Output ['abcd', 786, 2.23, 'john', 70.2] abcd 70.2 [786, 2.23] [2.23, 'john', 70.2] [123, 'john', 123, 'john'] ['abcd', 786, 2.23, 'john', 70.2, 123, 'john'] ['efgh', 786, 2.23, 'john', 70.2] ['efgh', 786, 'john', 70.2] 43
  44. 44. Python Lists (3) Other Basic List Operations 44 Expression Result Description len([1, 2, 3]) 3 Length 3 in [1, 2, 3] True Membership for x in [1, 2, 3]: print x, 1 2 3 Iteration
  45. 45. Functions VS Methods Function Method A function is a piece of code that is called by name. A method is a piece of code that is called by name that is associated with an object. It can pass data to operate on (i.e., the parameters) and can optionally return data (the return value). It is able to operate on data that is contained within the class. All data that is passed to a function is explicitly passed. It is implicitly passed for the object for which it was called. def sum(num1, num2): return num1 + num2 class Dog: def my_method(self): print "I am a Dog" dog = Dog() dog.my_method() # Prints "I am a Dog" 45
  46. 46. Python Lists (4) Some Built-in List Functions 46 Function Description Example max(list) Returns item from the list with max value. list = [456, 700, 200] print "Max value element : ", max(list) Max value element : 700 min(list) Returns item from the list with min value. list = [456, 700, 200] print "Min value element : ", min(list) Min value element : 200 …..
  47. 47. Python Lists (5) Some Built-in List Methods 47 Method Description Example list.append(obj) Appends a passed obj into the existing list. aList = [123, 'xyz', 'zara', 'abc']; aList.append( 2009 ); print "Updated List : ", aList Updated List : [123, 'xyz', 'zara', 'abc', 2009] list.count(obj) Returns count of how many times obj occurs in list. aList = [123, 'xyz', 'zara', 'abc', 123]; print "Count for 123 : ", aList.count(123) print "Count for zara : ", aList.count('zara') Count for 123 : 2 Count for zara : 1 …..
  48. 48. Example BasicTupleOperations Built-inTupleFunctions ListsVSTuples PYTHON TUPLES
  49. 49. Python Tuples (1) tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) tinytuple = (123, 'john') print tuple # Prints complete tuple print tuple[0] # Prints first element of the tuple print tuple[-1] # Prints last element of the tuple print tuple[1:3] # Prints elements starting from 2nd till 3rd print tuple[2:] # Prints elements starting from 3rd element print tinytuple * 2 # Prints tuple two times print tuple + tinytuple # Prints concatenated tuples 49
  50. 50. Python Tuples (2) Output ('abcd', 786, 2.23, 'john', 70.2) abcd 70.2 (786, 2.23) (2.23, 'john', 70.2) (123, 'john', 123, 'john') ('abcd', 786, 2.23, 'john', 70.2, 123, 'john') 50
  51. 51. Python Tuples (3) Other Basic Tuple Operations 51 Expression Result Description len((1, 2, 3)) 3 Length 3 in (1, 2, 3) True Membership for x in (1, 2, 3): print x, 1 2 3 Iteration
  52. 52. Python Tuples (4) Some Built-in Tuple Functions 52 Function Description Example max(tuple) Returns item from the tuple with max value. tuple = (456, 700, 200) print "Max value element : ", max(tuple) Max value element : 700 min(tuple) Returns item from the tuple with min value. tuple = (456, 700, 200) print "Min value element : ", min(tuple) Min value element : 200 …..
  53. 53. Lists VS Tuples Lists Tuples Lists are enclosed in brackets ( [ ] ). Tuples are enclosed in parentheses ( ( ) ). Lists' elements and size can be changed. Tuples' elements and size cannot be changed. Support item deletion. Example list = [123, 'john'] print list del list[1] print list [123, 'john'] [123] Doesn't support item deletion. Example tuple = (123, 'john') print tuple del tuple[1] print tuple (123, 'john') Traceback (most recent call last): File "main.py", line 6, in del tuple[1] TypeError: 'tuple' object doesn't support item deletion 53
  54. 54. Introduction Example PropertiesofDictionaryKeys Built-inDictionaryFunctions Built-inDictionaryMethods PYTHON DICTIONARY
  55. 55. Python Dictionary (1) • Python's dictionaries are kind of hash table type. • They work like associative arrays or hashes found in PHP and Perl respectively. • It consists of key-value pairs. • A dictionary key can be almost any Python type, but are usually numbers or strings, & values can be any arbitrary Python object. • Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]). 55
  56. 56. Python Dictionary (2) dict = {} dict['one'] = "This is one" dict[2] = "This is two" tinydict = {'name': 'john','code':6734,'dept':'sales'} print dict['one'] # Prints value for 'one' key print dict[2] # Prints value for 2 key print tinydict # Prints complete dictionary print tinydict.keys() # Prints all the keys print tinydict.values() # Prints all the values tinydict['name']="Peter" # update existing entry tinydict['org']="abcd" # Add new entry print tinydict del dict[2]; # remove entry with key 2 print "dict: ", dict dict.clear(); # remove all entries in dict print "dict: ", dict del dict ; # delete entire dictionary print "dict: ", dict 56
  57. 57. Python Dictionary (3) Output This is one This is two {'dept': 'sales', 'code': 6734, 'name': 'john'} ['dept', 'code', 'name'] ['sales', 6734, 'john'] {'dept': 'sales', 'code': 6734, 'name': 'Peter', 'org': 'abcd'} dict: {'one': 'This is one'} dict: {} dict: 57
  58. 58. Properties of Dictionary Keys • More than one entry per key not allowed, i.e., no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins. • Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but something like ['key'] is not allowed. 58
  59. 59. Python Dictionary (4) Some Built-in Dictionary Functions 59 Function Description Example len(dict) Gives the total length of the dictionary. dict = {'Name': 'Zara', 'Age': 7}; print "Length : %d" % len (dict) Length : 2 str(dict) Produces a printable string representation of a dictionary. dict = {'Name': 'Zara', 'Age': 7}; print "Equivalent String : %s" % str (dict) Equivalent String : {'Age': 7, 'Name': 'Zara'} …..
  60. 60. Python Dictionary (5) Some Built-in Dictionary Methods 60 Method Description Example dict.clear() Removes all elements of dictionary dict. dict = {'Name': 'Zara', 'Age': 7};print "Start Len : %d" % len(dict) dict.clear() print "End Len : %d" % len(dict) Start Len : 2 End Len : 0 dict.copy() Returns a shallow copy of dictionary dict. dict1 = {'Name': 'Zara', 'Age': 7}; dict2 = dict1.copy() print "New Dictinary : %s" % str(dict2) New Dictinary : {'Age': 7, 'Name': 'Zara'} …..
  61. 61. SomeExamples PYTHON DATE & TIME
  62. 62. Python Date & Time (1) import time; # This is required to include time module. ticks = time.time() # returns the current system time in ticks # since 12:00am, January 1, 1970 print "Number of ticks since 12:00am, January 1, 1970:", ticks Output Number of ticks since 12:00am, January 1, 1970: 1498320786.91 62
  63. 63. Python Date & Time (2) import calendar cal = calendar.month(2017, 6) print "Here is the calendar:" print cal Output Here is the calendar: June 2017 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 63
  64. 64. WhatisaFunction? Example PassbyReference VSPass byValue TypesofFunctionArguments ThereturnStatement GlobalVariableVSLocalVariable PYTHON FUNCTION
  65. 65. What is a Function? A function is a block of organized, reusable code that is used to perform a single, related action. Syntax def function_name( parameters ): #function_body 65
  66. 66. Example #python function def test(str): print (str) test("Hello World!!!") Output Hello World!!! 66
  67. 67. Pass by Reference VS Pass by Value Pass by Reference Pass by Value # Function definition is here def changeme( mylist ): # This changes a passed list into this function" mylist.append([1,2,3,4]); print "Values inside the function: ", mylist return # Now you can call changeme function mylist = [10,20,30]; changeme( mylist ); print "Values outside the function: ", mylist Output Values inside the function: [10, 20, 30, [1, 2, 3, 4]] Values outside the function: [10, 20, 30, [1, 2, 3, 4]] # Function definition is here def changeme( mylist ): # This changes a passed list into this function" mylist = [1,2,3,4]; # This would # assign new reference in mylist print "Values inside the function: ", mylist return # Now you can call changeme function mylist = [10,20,30]; changeme( mylist ); print "Values outside the function: ", mylist Output Values inside the function: [1, 2, 3, 4] Values outside the function: [10, 20, 30] 67
  68. 68. Types of Function Arguments Function Argument Description Example Required Arguments The arguments passed to a function in correct positional order. The number of arguments in the function call should match exactly with the function definition. def test(str): print (str) test() Traceback (most recent call last): File "python_func.py", line 4, in <module> test() TypeError: test() takes exactly 1 argument (0 given) Keyword Arguments When use keyword arguments in a function call, the caller identifies the arguments by the parameter name. Thus, allowing the arguments to place in any order. def printinfo( name, age ): print "Name: ", name print "Age ", age printinfo( age=50, name="miki" ) Name: miki Age 50 68
  69. 69. Types of Function Arguments (2) Function Argument Description Example Default Arguments An argument that assumes a default value if a value is not provided in the function call for that argument. def printinfo( name, age = 35 ): print "Name: ", name print "Age ", age printinfo( age=50, name="miki" ) printinfo( name="miki" ) Name: miki Age 50 Name: miki Age 35 69
  70. 70. Types of Function Arguments (3) Function Argument Description Example Variable-length Arguments We may need to process a function for more arguments than specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition def printinfo( arg1, *vartuple ): print "Output is: " print arg1 for var in vartuple: print var printinfo( 10 ) printinfo( 70, 60, 50 ) Output is: 10 Output is: 70 60 50 NOTE: The asterisk (*) placed before the variable vartuple holds the values of all non- keyword variable arguments. 70
  71. 71. The return Statement def add(x,y): sum=x+y return sum total=add(10,20) print total Output 30 71
  72. 72. Global Variable VS Local Variable 72 total = 0; # This is global variable # Function definition is here def sum( arg1, arg2 ): # Add both the parameters and return them total = arg1 + arg2; # Here total is local variable print "Inside the function local total : ", total return total; # Now you can call sum function sum( 10, 20 ); print "Outside the function global total : ", total Output Inside the function local total : 30 Outside the function global total : 0
  73. 73. PYTHON RECURSION
  74. 74. What is Recursion? • When function is called within the same function, it is known as recursion. • The function which calls the same function, is known as recursive function. 74
  75. 75. Example 75
  76. 76. WhatisaModule? importStatement from…importStatement NamespacesandScoping SomeFunctions PythonPackages PYTHON MODULES
  77. 77. What is a Module? • A module is a file consisting of Python code. • A module can define functions, classes and variables. It can also include runnable code. • A module allows you to logically organize your Python code. • A module is a Python object with arbitrarily named attributes that you can bind and reference. 77 Example tmodule.py def print_func( par ): print "Hello : ", par
  78. 78. import Statement # Import module tmodule import tmodule # Now you can call defined function that # module as follows tmodule.print_func("Zara") Output Hello : Zara 78
  79. 79. from…import Statement Python's from statement allows you to import specific attributes from a module into the current namespace. 79 Syntax Example from modname import name1[, name2[, ... nameN]] tmodule.py def print_func( par ): print "Hello : ", par def print_func_2(str) : print "Good Morning ",str from_import_module.py from tmodule import print_func_2 print_func_2("Zara") Output Good Morning Zara
  80. 80. Namespaces and Scoping • Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable names (keys) and their corresponding objects (values). • A Python statement can access variables in a local namespace and in the global namespace. If a local and a global variable have the same name, the local variable shadows the global variable. • Each function has its own local namespace. • Python assumes that any variable assigned a value in a function is local. • Therefore, in order to assign a value to a global variable within a function, you must first use the global statement. • The statement global VarName tells Python that VarName is a global variable. Python stops searching the local namespace for the variable. 80
  81. 81. Example Money = 2000 def AddMoney(): # Uncomment the following line # to fix the code: # global Money Money = Money + 1 print Money AddMoney() print Money Money = 2000 def AddMoney(): # Uncomment the following line # to fix the code: global Money Money = Money + 1 print Money AddMoney() print Money Output 2000 Traceback (most recent call last): File "namespace_scoping.py", line 8, in <module> AddMoney() File "namespace_scoping.py", line 5, in AddMoney Money = Money + 1 UnboundLocalError: local variable 'Money' referenced before assignment Output 2000 2001 81
  82. 82. Some Functions Function Description Example dir( ) Returns a sorted list of strings containing the names defined by a module. import tmodule print dir(tmodule) Output ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'print_func', 'print_func_2'] locals() Returns all the names that can be accessed locally from the function, in which its called. total = 0; def sum( arg1, arg2 ): total = arg1 + arg2; print "locals(): ",locals() print "globals(): ",globals() sum( 10, 20 ); Output locals(): {'arg1': 10, 'arg2': 20, 'total': 30} globals(): {'__builtins__': <module '__builtin__' (built-in)>, '__file__': 'loc al_global.py', '__package__': None, 'sum': <function sum at 0x017638F0>, '__name __': '__main__', 'total': 0, '__doc__': None} globals() Returns all the names that can be accessed globally from the function, in which its called. ….. 82
  83. 83. Python Packages A package is a hierarchical file directory structure that defines a single Python application environment that consists of modules and subpackages and sub-subpackages, and so on. G:. └──phone __init__.py (required to make Python treat phone as a package) g3.py isdn.py pots.py 83
  84. 84. Example pots.py def pots_func(): print "I'm Pots Phone" isdn.py def pots_func(): print "I'm ISDN Phone" g3.py def pots_func(): print "I'm G3 Phone" 84
  85. 85. Example (contd…) __init__.py from pots import pots_func from isdn import isdn_func from g3 import g3_func package.py import sys sys.path.append('G:2. DOCUMENTSPythonPrograms') import phone phone.pots_func() phone.isdn_func() phone.g3_func() 85
  86. 86. Output I'm Pots Phone I'm ISDN Phone I'm G3 Phone 86
  87. 87. Introduction Example SomeMoreFileOperationFunctions PYTHON FILE MANAGEMENT
  88. 88. Introduction • Until now, we have been reading and writing to the standard input and output. This works fine as long as the data is small. • However, many real life problems involve large volumes of data & in such situations the standard I/O operations poses two major problems: - It becomes cumbersome & time consuming to handle large volumes of data through terminals. - The entire data is lost either the program is terminated or the computer is turned off. • Thus, to have a more flexible approach where data can be stored on the disks & read whenever necessary without destroying, the concept of file is employed. 88
  89. 89. Introduction (2) • Like most other languages, Python supports a number of functions that have the ability to perform basic file operations: - Naming a file - Opening a file (fileobject = open(file_name [, access_mode][, buffering])) - Reading a file (string = fileobject.read([count])) - Writing to a file (fileobject.write(string)) - Closing a file (fileobject.close()) access_mode = r, rb, r+, rb+, w, wb, w+, wb+, a, ab,a+, ab+ buffering = <1, 0, >1 count = number of bytes to be read from the opened file string = content to be written into the opened file 89
  90. 90. Example # Open a file in write mode fo = open("foo.txt", "wb") fo.write( "Python is a great language.nYeah its great!!n"); # Close opened file fo.close() # Open the file in read mode fo = open("foo.txt", "rb") string = fo.read() print string # Close opened file fo.close() 90
  91. 91. Output Python is a great language. Yeah its great!! 91
  92. 92. Some More File Operation Functions 92 Function Name Description tell() Gives the current position within the file seek(offset[, from]) Changes the current file position. The offset argument indicates the number of bytes to be moved. The from argument specifies the reference position from where the bytes are to be moved. …..
  93. 93. Example (tell()) 93
  94. 94. WhatisException? HandlinganException try.....except.....else try.....finally ArgumentofanException User-Defined Exceptions PYTHON EXCEPTION HANDLING
  95. 95. What is Exception? • An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. • When a Python script encounters a situation that it cannot cope with, it raises an exception. • An exception is a Python object that represents an error. • When a Python script raises an exception, it must either handle the exception immediately otherwise it terminates and quits. 95
  96. 96. Handling an Exception • If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block. • After the try: block, include an except: statement, followed by a block of code which handles the problem as elegantly as possible. • After the except clause(s), you can include an else-clause. The code in the else-block executes if the code in the try: block does not raise an exception. 96
  97. 97. try.....except.....else (Syntax) try: You do your operations here; ...................... except ExceptionI: If there is ExceptionI, then execute this block. except ExceptionII: If there is ExceptionII, then execute this block. ...................... except ExceptionN: If there is ExceptionN, then execute this block. else: If there is no exception then execute this block. 97
  98. 98. try.....except.....else (Example) Example I Example II try: fh = open("testfile", "w") fh.write("This is my test file for exception handling!!") except IOError: print "Error: can't find file or read data" else: print "Written content in the file successfully" fh.close() try: fh = open("testfile_2", "r") string = fh.read() except IOError: print "Error: can't find file or read data" else: print string fh.close() Output Written content in the file successfully Output Error: can't find file or read data 98
  99. 99. try.....finally • You can use a finally: block along with a try: block. • The finally block is a place to put any code that must execute, whether the try-block raised an exception or not. Syntax try: You do your operations here; ...................... [except ExceptionI: If there is ExceptionI, then execute this block. except ExceptionII: If there is ExceptionII, then execute this block. ...................... except ExceptionN: If there is ExceptionN, then execute this block. else: If there is no exception then execute this block.] finally: This would always be executed. ...................... 99
  100. 100. Example Example I Example II try: fh = open("testfile", "w") fh.write("This is my test file for exception handling!!") except IOError: print "Error: can't find file or read data" else: print "Written content in the file successfully" finally: print "Closing the file" fh.close() try: fh = open("testfile_2", "r") string = fh.read() except IOError: print "Error: can't find file or read data" else: print string finally: print "Closing the file" fh.close() Output Written content in the file successfully Closing the file Output Error: can't find file or read data Closing the file 100
  101. 101. Argument of an Exception • An exception can have an argument, which is a value that gives additional information about the problem. • This argument receives the value of the exception mostly containing the cause of the exception. Syntax try: You do your operations here; ...................... except ExceptionType, Argument: You can print value of Argument here... 101
  102. 102. Example # Define a function here. def temp_convert(var): try: return int(var) except ValueError, Argument: print "The argument does not contain numbersn", Argument # Call above function here. temp_convert("xyz"); Output The argument does not contain numbers invalid literal for int() with base 10: 'xyz' 102
  103. 103. User-Defined Exceptions Python also allows you to create your own exceptions by deriving classes from the standard built-in exceptions. 103 Example # user-defined exception class LevelError(ValueError): def __init__(self, arg): self.arg = arg try: level=input("Enter level: ") if(level<1): # Raise an exception with argument raise LevelError("Level less than 1") except LevelError, le: # Catch exception print 'Error: ', le.arg else: print level Output Enter level: 0 Error: Level less than 1
  104. 104. References • Courtesy of YouTube – ProgrammingKnowledge. URL: https://www.youtube.com/user/ProgrammingKnowledge, Python Tutorial for Beginners (For Absolute Beginners) • Courtesy of TutorialsPoint – Python Tutorial. URL: http://www.tutorialspoint.com/python • Courtesy of W3Resource – Python Tutorial. URL: http://www.w3resource.com/python/python-tutorial.php 104
  • akshatjain448

    Jun. 20, 2020
  • SimthasMohammed

    Mar. 8, 2020
  • KaveriKudagi

    Oct. 21, 2019
  • krupali_19

    Aug. 27, 2019
  • DipaliSahane

    Jul. 20, 2019
  • KhaledMoustafa21

    Jul. 6, 2019
  • KUMARISUKRITI

    Jun. 26, 2019
  • JAFFARALI45

    Jun. 26, 2019
  • Syedhaiderzaidi4

    Jun. 24, 2019

A brief introduction to Python (basic level)

Views

Total views

687

On Slideshare

0

From embeds

0

Number of embeds

0

Actions

Downloads

136

Shares

0

Comments

0

Likes

9

×