Python: Quick Revision

Quick Revision: Python

I plan to consolidated the very basics of Python under this blog-post in a handy & concise notes for quick revision. Here is hoping it proves useful to someone.

Python:

  • Has 2 versions: 2.x & 3.x (latest & preferred)
  • This course is for the latest version (3.x)
  • Python is special language that doesn't use brackets({}) or semi-colons for code formatting, rather it uses indentation
  • Commenting Code:
    #Single Line

    #Multi
    #line

    ''' triple quote is a string but can be used for multi line comments
    as it's ignored by interpreter if not assigned to a variable
    '''

Pre-requisite: 

  • Install python3 and any code editor
  • python comes with its own package/module manager (pip)
  • use pip3 for python3.x
  • check for setup: python3 --version & pip3 --version

Operations (Arithmetic):

  1. Add(+)
  2. Substract(-)
  3. Divide(/)
  4. Modulus(%)
  5. Exponent (**)

Variables:

  • Way of storing value to be used by the code
  • Naming convention:
    • Can only contain ([a-zA-Z0-9_]) --> but can't start with a number(0-9)
    • '_' is also used in classes for defining access level (_singl= private & __double= public etc.)
    • Case-sensitive
    • Python is loosely typed just as JavaScript, so no need to define type of variable, also there is no special character like var or let required.
    • Syntax:
      x=5 #int
      y=2.5 #float
      x='Hello' #str , same variable can take other type of values later in program 
      is_cool= True #bool

Data Types:

  • int: holds any non-fraction number(negative & positive)
  • float: decimal values
  • str: any string, can be defined using single('s'), double("d") or triple quote ('''triple s''') or ("""triple d""")
  • bool: True or False
  • Collections:
    • list: Array equivalent, heterogeneous(different types, even other collections)
    • tuple: Like list but read-only
    • set: Just like list but doesn't allow duplicates and not-indexed, can't access values using index
    • dict: Just like map & object from other languages, stores a key-value pair, keys are unique

Programming Constructs:

  • Conditional:

    • if … elif … else
      • syntax:
        x=6
        print('starting if below')
        if x==5:
           #do something
           print('inside if')
        elif x==10:
           #do something else
           print('inside elif')
        else:
           #do else handling
           print('inside else')
        print('this is again back to outside if')
    • ternary:Evaluates the condition and if true returns 'value before if' otherwise 'value after else' is returned
      • syntax:
        s='True'
        x= '1' if s=='True' else '2'
        print(x)
    • Condition operators:
      • logical( ==, !=, >, >=, <, <=)
      • membership (in, not in)
      • comparison (is, is not)
      • conjunction (and, or, not) : if (x>5 and x<=10): etc.
  • Loop/Iteration:

    • 2 main forms of looping available in Python (for & while)
    • for:

      num_list=[1, 2, 3, 4, 5]
      for x in num_list:
          print(x) #print each item from a list

      for i in range(1,11):
          print(i) #prints from 1 to 10.

      **range is a special method that generates a list, given start and end value (end value is not included in list)

    • while:

      counter=0
      while counter<10:
          print(counter)
          counter+=1

        **Just like other languages: Python also supports break (exit the nearest loop) and continue (skip current iteration of nearest loop) keywords 

  • Class:

    • Python supports object oriented programming, which can be achieved with help of classes,
    • Classes are blueprint for creating objects and each object can have properties and methods.
    • Syntax:
      #defining a class
      class User:
           #__init__ is a special function defined in each class,
           #this is equivalent to constructors in other languages
           def __init__(self, name, age):
                self.name=name
                self.age=age
           def greeting(self):
                print( 'My name is {0} and I am {1}'.format(self.name, self.age) )

      #using classes to create/instantiate objects
      user1=User('PK', 30)
      user1.greeting() # output: My name is PK and I am 30
    • Inheritance:
      • Python supports class inheritance
      • Syntax:
        #define a new Customer(child) class which extends User(Parent) class
        class Customer(User):
             def __init__(self, name, age, brand):
                  #call the parent constructor
                  super().__init__(name, age) #also User(name, age) #or User.__init__(name, age)
                  self.breed=breed

        #instantiating Customer
        customer1= ('cust1', 40, 'Brand1')
        customer1.greeting() #this method is available from the parent due to inheritance, we could also override it just by re-defining it in Customer class (Python doesn't use any special character like override etc. like other languages)

Modules:

  • Apart from its concise syntax and powerful data-manipulation methods, another main reason for python's popularity is, its large set of open source libraries/modules for various functionality (working with data, OS, files, collection, network request, we have libraries for everything)
  • Modules are basically '.py' files, containing a set of functions, which can be included in your app, 
  • Along with core modules , external ones can be installed using 'pip' - pip3 install package_name
  • To use modules, we need to import it first:

    Syntax1:

      import datetime
      today=datetime.date.today()
      print(today)

    Syntax2:

      from datetime import date
      today=date.today()
      print(today)

**We can also create our own modules, we just need to package our code-files as a .py

Working with files:

  • Python provides in-line functions to work with files:
  • Open:
    myFile= open('filename.txt', 'w') #opens file in write mode, creates if file doesn't exist already
  • Writing:
    myFile.write('I live Python')
  • Close file:
    myFile.close()
  • Read:
    myFile= open('filename.txt', 'r+')
    text= myFile.read(100) # read 100 characters
    print(text)
    myFile.close() #always close the file after read/write to avoid conflict later
  • File Modes:

         'w' -> writing
         'a' -> appending
         'r+' -> reading & writing

Working with JSON:

  • Just like other languages Python provides way of parsing its map/object (dict) to string and a json string to dictionary
  • Need to import json module
  • Syntax:
         import json
         userJson = '{"first_name":"John", "last_name":"Doe", "age":30}'

         #convert json string to dictionary
         user = json.loads(userJson)
         print(user)

         #convert a dictionary to json string
         userJsonStr= json.dumps(user)
         print(userJsonStr)

Error and Exception handling:

  1. try...except...finally construct:
    try:
       print('in the try block')
       print(1/0) #divide by zero error
    except:
       print('in the catch block')
    finally:
       print('in the finally block, always executed')
  2. raise: keyword used to throw custom error
    try:
       if(val is None):
         raise ValueError('Please give proper value')

**Special Python Features & Methods:

  1. dir(module_name) # lists all methods and properties inside a module

  2. help(module.funct_name) # displays a the manual page for a particular function with details of parameter & return value etc.

  3. print(val1, val2, val3, sep="$", end="line-end") # print is a powerful method of python, which can display n number of values and giving users the control over separator and line end type

  4. input() # This method can be used to accept user input, always saves in string format so a conversion would be required to other types as per requirement

  5. pass: Special keyword to skip block body, helpful in preparing high-level code, eg pass a 'class' or 'function' or 'if' body 

  6. isinstance(4.5, float) : checking instance

  7. type(4) : int, check type of value stored by a variable

  8. len(str) or len(lst) or len(dict): get length of a string or collection

  9. del var_name or del lst[indx] or del dict[key]: deleting items from collection

  10. Python also provides many short-hand syntax for generating collections like list, dictionary etc.:
    1. List comprehension: create a list using single line code
      list1 = [x**2 for x in range(1,6)] #=[1, 4, 9, 16, 25] # list of x square, where x in range 1 to 5
      print(list1)
    2. Dictionary Comprehension:
      dict1= { k:k**2 for k in range(1,6) } #={1:1, 2:4, 3:9, 4:16, 5:25} # a dictionary with key as number and value=num square
      print(dict1)

Comments

Popular posts from this blog

Android Emulator Setup for Salesforce

Few Basic & Advanced Git Commands: Possibly necessary, Definitely helpful