Python Basics

Python

Python is an interpreted, high-level, general-purpose programming language. It was created by Guido van Rossum and first released in 1991. he started Python as a hobby project to keep him occupied in the week around Christmas. Got its name from the name of British comedy troupe Monty Python. It is used in :

  1. Software Development
  2. Web Development
  3. System Scripting
  4. Mathematics

Features of Python

  1. Easy to use: Due to simple syntax, it is very easy to implement anything and everything
  2. Interpreted language: In this, every code is executed line by line.
  3. Cross-platform language: It can run on Windows, Linux, Macintosh, Raspberry Pi, etc.
  4. Expressive language: It supports a wide range of library
  5. Free & open source: It can be downloaded free of cost and the source code can be modified for improvement

Shortcomings of Python

  1. Lesser libraries: As compared to other programming languages like C++, java, .Net, etc. it has a lesser number of libraries, but libraries of other libraries can easily be implemented and imported
  2. Slow language: Since being an interpreted language, the code is executed slowly
  3. Weak on type-binding: A variable that is initially declared int can be changed to string at any point in the program without any typecasting.

Installing Python

  1. Python's latest version can be downloaded from https://www.python.org/downloads/.
  2. At the time of writing this, the latest version was 3.7.4.
  3. Download the installer file according to your operating system and execute the installer commands according to your Operating System.

Python 2 vs Python 3

Python 2 Python 3
1. The output of the division operator is an integer 1. The output of the division operator is Float
2. print "hello" is the implementation of the print function here 2. print("hello") is the implementation of the print function here
3. Here Bytes and String is the same 3. Here Bytes and String is different
4. Implicit String type here is ASCII 4. Implicit String type here is Unicode
5. raise IOError, “your error message” is used to raise an exception 5. raise IOError(“your error message”) is used for raising an exception
6. The syntax here is comparatively difficult to understand. 6. The syntax is simpler and easily understandable.
7. The xRange() function is used to perform iterations. 7. The new Range() function introduced to perform iterations.
8. The value of the global variable will change while using it inside the for-loop. 8. The value of variables never changes.
9. Python 2 code can be converted to Python3 code 9. It is not backward compatible
10. It uses raw_input() for taking inputs from the command line 10. It uses input() for taking inputs from the command line


Flavors of Python

  1. CPython: Written in C, the most common implementation of Python.
  2. JPython: Written in Java, compiles to bytecode.
  3. IronPython: Implemented in C#, an extensibility layer to frameworks written in. NET.
  4. Brython: Browser Python, runs in the browser.
  5. RubyPython: A bridge between Python and Ruby interpreters.
  6. PyPy: Implementation in Python.
  7. MicroPython: Runs on a Microcontroller.

Python character set

The following are the character sets recognized by Python. It uses the traditional ASCII character set.

  1. Letters: A-Z, a-z
  2. Digits: 0-9
  3. Special symbols: Special Symbols available over the Keyboard (some of the symbols like the rupee symbol may not be available)
  4. White spaces: Blank space, tab, carriage return, newline, form feed
  5. Other characters: Unicode

Python tokens

The smallest individual unit in a program is known as a token.

  1. Keywords: There are in total of 31 reserved keywords. Ex: and, finally, not, etc.
  2. Identifiers: A Python identifier is a name used to identify a variable, function, class, module, or other objects. Ex: MyBook, myBook, my book, etc.
  3. Literals: Literals in Python can be defined as numbers, text, or other data that represent values to be stored in variables. Ex: age = 22, escape sequence, etc.
  4. Operators: These can be defined as symbols that are used to perform operations on operands. Ex: arithmetic operators, etc.
  5. Punctuators: Used to implement the grammatical and structure of a Syntax. Ex: &=, >>=, <<=, etc.

Python keywords

Python keywords

Rules to define Python Identifiers

  1. 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).
  2. Python does not allow special characters
  3. An identifier must not be a keyword of Python.
  4. Python is a case-sensitive programming language.
  5. Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
  6. Starting an identifier with a single leading underscore indicates that the identifier is private.
  7. Starting an identifier with two leading underscores indicates a strongly private identifier.
  8. If the identifier also ends with two trailing underscores, the identifier is a language-defined special name.

Python punctuators

Python punctuators

Barebone of a Python program

  1. Expression is evaluated and hence produces results. Ex: (20=4)/4
  2. Statements Instructs that we are doing something. Ex: a=20 print("Calling in proper sequence")
  3. Comments This is readable for a programmer but ignored by the Python interpreter. a. Single line comment (#) b. Multi-line comment (''' ''') Ex: #this is a single-line comment ''' this is multiple '''
  4. Function a code that has some name and it can be reused. Ex: KetArgFunc()
  5. Block & Indentation A group of statements in block indentation at the same level creates a block. Ex: all the statements that are under the function KetArgFunc()

Python variables

A variable can be considered as a container that holds value. Python is a type-infer language i.e. one which can detect data types automatically in other words it means you don't need to specify the data type of variable.

Note. Although Python supports unlimited variable length, following PEP-8, we keep the maximum length to 79 characters

For example

name = 'python' # String Data Type
sum =None # a variable without a value
a = 23 # integer
b = 6.2 # Float
sum = a+b
print(sum)

Multiple assignments

  1. a =b =c =1 #single value to multiple variables
  2. a,b = 1, 2 #multiple value to multiple variable
  3. a,b = b,a #value of a and b is swapped

Variable scope and lifetime

  1. Local Variable
    def fun():
       x=8
    print(x)
    fun()
    print(x) #error will be shown
  2. Global Variable
    x = 8
    def fun():
       print(x) #Calling variable 'x' inside fun()
    fun()
    print(x) #Calling variable 'x' outside fun()

Python Data Types

  1. Number: It is used to store numeric values. Python has 3 numeric types:
    • Integers
      Ex. a = 10
    • Floating Point numbers
      Ex. a = 10.0
    • Complex numbers
      Ex. a = complex(10,5) # 10+5j
  2. String: A string is a sequence of characters. In Python, we can create a string using a single ( ' ' ) or double quotes (" "). Both are the same in Python.
    str = 'computer science'
    print('str- ', str)          # print string
    print('str[0]-', str[0])      # print 1st char
    print('str[1:3]-', str[1:3])  # print string from position 1 to 3
    print('str[3:]-', str[3:])    # print string starting from 3rd char
    print('str*2-', str*2)        # print string two times
    print('str + yes-', str + 'yes')  # concatenated string
    
  3. Boolean: It is used to store two possible values either true or false.
    str = "comp sc"
    b = str.isupper()
    print(b)
  4. List: Lists are collections of items and each item has its index value. Denoted by [].
    list = [6,9]
    list[0] = 55
    print(list[0])
    print(list[1])
  5. Tuple: A tuple is an immutable Python Object. Immutable Python objects mean you cannot modify the contents of a tuple once it is assigned. Denoted by ().
    tup = (66,99)
    Tup[0] = 3 #error will be displayed
    print(tup[0])
    print(tup[1])
  6. Set: It is an unordered collection of unique and immutable items. Denoted by {}.
    set1 = {11, 22, 33, 22}
    print(set1)
  7. Dictionary: It is an unordered collection of items and each item consists of a key and a value.
    dict = {'subject' : 'comp sc", 'class' : '11'}
    print(dict)
    print( "Subject :", dict["subject"])
    print("class :", dict.get('class'))

Python operators

  1. The Precedence of Operators in Python can be found in the rule PEMDAS ( Parenthesis, Exponential, Multiply, Division, Addition, Subtraction). Operators with the same precedence are evaluated from left to right.
  2. Python Arithmetic Operator It is used for mathematical operations.
    x = 5
    y = 4
    print('x + y =',x+y) #Addition
    print('x - y =',x-y) #Substraction
    print('x * y =',x*y) #Multiplication
    print('x / y =',x/y) #Division
    print('x // y =',x//y) #Floor Division
    print('x ** y =',x**y) #Exponent
  3. Python Comparison Operators are used to compare values.
    x = 101
    y = 121
    print('x > y is',x>y) #Greater than
    print('x < y is',x<y) #Less than
    print('x == y is',x==y) #Equal to
    print('x != y is',x!=y) #Not Equal to
    print('x >= y is',x>=y) #Greater than equal to
    print('x <= y is',x<=y) #Less than equal to
  4. Python Logical Operators.
    x = True
    y = False
    print('x and y is',x and y) #if both are true
    print('x or y is',x or y) #if either one is true
    print('not x is',not x) #returns the complement
  5. Python Bitwise Operators Used to manipulate bit values.
    a = 6
    b = 3
    print ('a=',a,':',bin(a),'b=',b,':',bin(b)) c = 0
    c = a & b
    print ("result of AND is ", c,':',bin(c))
    c = a | b
    print ("result of OR is ", c,':',bin(c))
    c = a ^ b
    print ("result of EXOR is ", c,':',bin(c))
    c = ~a
    print ("result of COMPLEMENT is ", c,':',bin(c))
    c = a << 2
    print ("result of LEFT SHIFT is ", c,':',bin(c))
    c = a>>2
    print ("result of RIGHT SHIFT is ", c,':',bin(c))
  6. Python Membership Operators Test for membership in a sequence.
    a = 5
    b = 10
    list = [1, 2, 3, 4, 5 ]
    if ( a in list ):
        print ("Line 1 - a is available in the given list")
    else:
        print ("Line 1 - a is not available in the given list")
    if ( b not in list ):
        print ("Line 2 - b is not available in the given list")
    else:
        print ("Line 2 - b is available in the given list")
  7. Python Identity Operators They check if values on either side of the equality operator point to the same object.
    a = 10
    b = 10
    print ('Line 1','a=',a,':',id(a), 'b=',b,':',id(b))
    if ( a is b ):
       print ("Line 2 - a and b have same identity")
    else:
       print ("Line 2 - a and b do not have same identity")
    1. Unary Operator
    1. Method
    1. -
    1. __neg__(self)
    1. +
    1. __pos__(self)


Python Operator Overloading

In computer programming, operator overloading, sometimes termed operator ad hoc polymorphism, is a specific case of polymorphism, where different operators have different implementations depending on their arguments. Operator overloading is generally defined by a programming language, a programmer, or both.

Python Control Statements

  1. Control statements: Control statements are used to control the flow of execution depending upon the specified condition/logic.
  2. If- Statement: An if statement is a programming conditional statement that, if proved true, performs a function or displays information
    If statement
  3. In the above code, we are checking if noofbooks is equal to 2, then execute the given code.
    noofbooks = 2
    if (noofbooks == 2):
        print(" You have")
        print("two books")
    print("outside of if statement")
    
  4. if-else statement: The if-else statement executes some code if the test expression is true (non-zero) and some other code if the test expression is false
    If else statement
  5. In the above code, we are checking if a is less than 100, else will print "more than equal 100"
    a=10  
    if a<100:   
          print('less than 100')  
    else:  
          print('more than equal 100')
  6. Nested If-Else Statement: The nested if ... else statement allows you to check for multiple test expressions and executes different codes for more than two conditions
    Nested if else statement
  7. In the above code, we are first checking if the num is greater than or equal to 0, and then if it is zero if both the conditions are met, "zero" is printed, otherwise "Negative number".
    num = float(input("enter a number:"))  
    if num >=0:  
         if num==0:  
             print("zero")  
    else:  
         print("Negative number")

Python control loops

  1. While Loop: It is used to execute a block of a statement as long as a given condition is true. And when the condition becomes false, the control will come out of the loop. The condition is checked every time at the beginning of the loop
    While loop
  2. In the above code, we are printing all the values from 1 to 4.
    x=1  
    while x<=4 :  
          print(x)  
          x = x+1 
  3. For Loop: It is used to iterate over items of any sequence, such as a list or a string.
    For loop
    for i in range (3,5):  
          print(i) 
  4. In the above code, we are printing numbers from 3 to 5.
  5. Nested For Loop: For loop within for loop is what we mean by nested for loops
    Nested for loop
    for i in range (1,3):  
        for j in range(1,11):  
              k=i*j  
              print(k, end = ' ')  
        print() 
  6. In the above code, we are running our loop firstly from 1 to 3 and then for each iteration running for another 10 times.

Python Jump Statements

  1. They are used to transfer the program's control from one location to another. This means these are used to alter the flow of a loop like to skip a part of a loop or terminate a loop.
  2. Break It is used to terminate the loop
    Break
    for val in "string":  
          if val == "i":  
                 break  
          print(val) 
  3. In the above code, we break the loop as soon as "i" is encountered, hence printing "str"
  4. Continue: It is used to skip all the remaining statements in the loop and move controls back to the top of the loop.
    Continue
    for val in "init":  
          if val == "i":  
                continue  
           print(val)  
    print(" The End") 
  5. In the above article, we will be printing "nt", because for "i" it will skip.
  6. Pass: This statement does nothing. It can be used when a statement is required syntactically but the program requires no action.
    for i in "initial":  
          if(i == "i"):  
                pass  
          else:  
               print(i) 
  7. Continue forces the loop to start the next iteration while pass means "there is no code to execute here" and will continue through the remainder of the loop body. The output will be "ntal"

Python Errors & Exception


Errors

A Syntax error is an error in the syntax of a sequence of characters or tokens that are intended to be written in a particular programming language.

For Example

while True: 
      print ('Hello world')

In the above code, it is an Invalid Syntax error. It should be as.

while True:
    print('Hello world')

Standard Errors available in Python are

IndentationError, SystemExit, ValueError, TypeError, RuntimeError

Exceptions

The other kind of error in Python are exceptions. Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions

For Example

10 * (1/10)

The above code is syntactically okay, but when we execute it, it will result in ZeroDivisionError: integer division or modulo by zero.

Standard Exceptions available in Python are

SystenExit, OverflowError, FloatingPointError, ZeroDivisonError, EOFError, KeyboardInterrupt, IndexError, IOError

Handling an Exception

If we see some suspicious code that may raise an exception, we can defend our program by placing the code in the try block

Syntax

try:
   you do your operation here
except Exception1:
   if there is Exception1, then execute this block
except Exception2:
   if there is Exception2, then execute this block 
.........
else:
   if there is no exception, then execute this block. 
try:  
   fh = open("testfile", "r")  
   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")  

Python List
 

  1. Function
  1. Description
  1. list.append()
  1. Add an item at the end of a list
  1. list.extend()
  1. Add multiple items at the end of a list
  1. list.insert()
  1. Insert an item at a defined index
  1. list.remove()
  1. Remove an item from a list
  1. del list[index]
  1. Delete an item from a list
  1. list.clear()
  1. Empty all the list
  1. list.pop()
  1. Remove an item at a defined index
  1. list.index()
  1. Return the index of the first matched item
  1. list.sort()
  1. Sort the items of a list in ascending or descending order
  1. list.reverse()
  1. Reverse the items of a list
  1. len(list)
  1. Return the total length of the list
  1. max(list)
  1. Return the item with the maximum value in the list
  1. min(list)
  1. Return the item with the minimum value in the list
  1. list(seq)
  1. Converts a tuple, string, set, or dictionary into a list


Python Dictionary
 

  1. Function
  1. Description
  1. dict.clear()
  1. removes all elements of dictionary dict
  1. dict.copy()
  1. returns a shallow copy of dictionary dict
  1. dict.items()
  1. returns a list of dict's (key, value) tuple pairs
  1. dict.setdefault(key, default=None)
  1. similar to get(), but will set dict[key] = default
  1. dict.update(dict2)
  1. adds dictionary dict2's key-values pairs to dict
  1. dict.keys()
  1. returns list of dictionary dict's keys
  1. dict.values()
  1. returns list of dictionary dict's values


Python Tuples
 

  1. Function
  1. Description
  1. tuple(seq)
  1. converts a list into a tuple
  1. min(tuple)
  1. returns an item from the tuple with a minimum value
  1. max(tuple)
  1. returns item from the tuple with maximum value
  1. len(tuple)
  1. gives the total length of the tuple
  1. cmp(tuple1,tuple2)
  1. compares elements of both tuples


Python Class

A class is a code template for creating objects. Objects have member variables and have behavior associated with them. In Python, a class is created by the keyword class. An object is created using the constructor of the class. This object will then be called the instance of a class. In Python, we create instances in the following manner.

  1. Declaring a Class.
    class name:
    statements 
  2. Using a Class.
    class Point:
        x = 0
        y = 0
    # main
    p1 = Point()
    p1.x = 2
    p1.y = -5
    
    from Point import *
    # main
    p1 = Point()
    p1.x = 7
    p1.y = -3
    # Python objects are dynamic (can add fields any time!)
    p1.name = "Tyler Durden"
    
  3. Objects Methods.
    def name (self, parameter, ....., parameter):
    statements 
  4. In the above code, self is essential, as, without the presence of self, python will not allow us to use any of the class member functions. It is similar to "this" used in Java. The only difference is that using "this" in Java is not compulsory.
    from math import *
    class Point:
        x = 0
        y = 0
        def set_location(self, x, y):
            self.x = x
            self.y = y
        def distance_from_origin(self):
            return sqrt(self.x * self.x + self.y * self.y)
        def distance(self, other):
            dx = self.x - other.x
            dy = self.y - other.y
            return sqrt(dx * dx + dy * dy)
    
  5. In the above code, we have created 3 methods namely set_location(), distance_from_origin(), and distance().

Calling methods

A client can call the methods of an object in two ways.

  1. object.method( parameter).
  2. Class.method( object, parameters).
    p = Point(3, -4)  
    p.translate (1, 5)   
    Point.translate (p, 1, 5)  

Python Class Constructors

a constructor is a special method with the name __init__

def __init__ (self, parameter, ....., parameter):
               statements 
class Point:  
       def __init__( self, x, y):  
               self.x = y  
               self.y = y  

toString and __str__

It is equivalent to Java's toString which converts objects to a string. It is automatically involved when str or print is called.

def __str__( self):
          return string
from math import *  
class Point:  
    def __init__(self, x, y):  
        self.x = x  
        self.y = y  
    def distance_from_origin(self):  
        return sqrt(self.x * self.x + self.y * self.y)  
    def distance(self, other):  
        dx = self.x - other.x  
        dy = self.y - other.y  
        return sqrt(dx * dx + dy * dy)  
    def translate(self, dx, dy):  
        self.x += dx  
        self.y += dy  
    def __str__(self):  
        return "(" + str(self.x) + ", " + str(self.y) + ")"  
  1. Operator
  1. Class Methods
  1. -
  1. __sub__(self, other)
  1. +
  1. __pos__(self, other)
  1. *
  1. __mul__(self, other)
  1. /
  1. __truediv__(self, other)
  1. ==
  1. __eq__(self, other)
  1. !=
  1. __ne__(self, other)
  1. <
  1. __lt__(self, other)
  1. >
  1. __gt__(self, other)
  1. <=
  1. __le__(self, other)
  1. >=
  1. __ge__(self, other)


Python operator overloading in Python Classes

Conclusion

In the above article, we brushed up on our Python basics, under which we studied features of Python, shortcomings of Python, installing Python, the difference between Python 2 and Python 3, Python Character Set, Python Tokens, Skeleton of a Python program, Python Variables, Python Data Types, Python Operators, Python Operator Overloading Python Control Statements, Python Control Loops, Python Jump Statements, Python Errors and Exceptions, Python List, List Dictionary, Python Tuples, and Python Classes.

In the next part of this series, we will learn about various packages and tools we will be requiring throughout our journey.

Congratulations!!! you have climbed your first step in becoming a successful ML engineer.

Next Article in this series >> Libraries Needed for Machine Learning


Similar Articles