This page looks best with JavaScript enabled

Getting started with python programming

 ·   ·  β˜• 6 min read

    History

    Python is a general purpose high level, interpreted language.
    Initiallly created by Guido van Rossum in 1985. Python 3 was released in 2008.

    At a glance

    • Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell and other scripting languages.

    • Python is copyrighted. Like Perl, Python source code is now available under the GNU General Public License (GPL).

    • Python is now maintained by a core development team at the institute, although Guido van Rossum still holds a vital role in directing its progress.

    • Python 1.0 was released in November 1994. In 2000, Python 2.0 was released. Python 2.7.11 is the latest edition of Python 2.

    • Meanwhile, Python 3.0 was released in 2008. Python 3 is not backward compatible with Python 2. The emphasis in Python 3 had been on the removal of duplicate programming constructs and modules so that “There should be one – and preferably only one – obvious way to do it.” Python 3.5.1 is the latest version of Python 3.

    Python Characteristics

    • High level,
    • Interpreted: Processed at runtime.
    • Interactive: Run python command line by line in a command prompt
    • OOP supported: Supports functional (Procedural), structured and OOP methods for programming
    • Automatic garbage collection
    • Easily integrated with other language
    • Dynamic data type and dynamic type checking
    • Scripting/Compiled: Can be used for scripting and compiled to byte code.
    • Easy to read
    • Easy to learn
    • Easy to maintain
    • Hugo standard library
    • Portable
    • Scalable - provides better structure and support for large projects

    Applications

    • Scripting
    • GUI
    • Databases
    • Web application
    • Machine Learning
    • Computer vision
    • Automation
    • And the list goes on…

    Python 2 vs 3

    The print method is replaced by print() method.

    print "Hello World" #is acceptable in Python 2
    print ("Hello World") # in Python 3, print must be followed by ()
    

    To get rid of newline

    print x,           # Trailing comma suppresses newline in Python 2
    print(x, end="")  # Removes newline
    

    The future module

    Python 3.x introduced some Python 2-incompatible keywords and features that can be imported via the in-built future module in Python 2. It is recommended to use future imports, if you are planning Python 3.x support for your code.

    For example, if we want Python 3.x’s integer division behavior in Python 2, add the following import statement.

    from __future__ import division
    

    Taking input

    In python2 input() and raw_input() are used to take input. raw_input() is deprecated in python3.

    #In Python 2
    
    >>> x = input('something:') 
    something:10 #entered data is treated as number
    >>> x
    10
    
    >>> x = input('something:')
    something:'10' #entered data is treated as string
    >>> x
    '10'
    
    >>> x = raw_input("something:")
    something:10 #entered data is treated as string even without ''
    >>> x
    '10'
    
    >>> x = raw_input("something:")
    something:'10' #entered data treated as string including ''
    >>> x
    "'10'"
    
    #In Python 3
    
    >>> x = input("something:")
    something:10
    >>> x
    '10'
    
    >>> x = input("something:")
    something:'10' #entered data treated as string with or without ''
    >>> x
    "'10'"
    

    Integer Division

    In Python 2, the result of division of two integers is rounded to the nearest integer. As a result, 3/2 will show 1. In order to obtain a floating-point division, numerator or denominator must be explicitly used as float. Hence, either 3.0/2 or 3/2.0 or 3.0/2.0 will result in 1.5

    Python 3 evaluates 3 / 2 as 1.5 by default, which is more intuitive for new programmers.

    Unicode Representation

    Python 2 requires you to mark a string with a u if you want to store it as Unicode.

    Python 3 stores strings as Unicode, by default. We have Unicode (utf-8) strings, and 2 byte classes: byte and byte arrays.

    xrange() Function Removed

    In Python 2 range() returns a list, and xrange() returns an object that will only generate the items in the range when needed, saving memory.

    In Python 3, the range() function is removed, and xrange() has been renamed as range(). In addition, the range() object supports slicing in Python 3.2 and later.

    raise exception

    Python 2 accepts both notations, the ‘old’ and the ‘new’ syntax; Python 3 raises a SyntaxError if we do not enclose the exception argument in parenthesis.

    
    raise IOError, "file error" #This is accepted in Python 2 
    raise IOError("file error") #This is also accepted in Python 2 
    raise IOError, "file error" #syntax error is raised in Python 3 
    raise IOError("file error") #this is the recommended syntax in Python 3
    
    
    

    Arguments in Exceptions

    In Python 3, arguments to exception should be declared with ‘as’ keyword.

    except Myerror, err: # In Python2 
    except Myerror as err: #In Python 3
    

    next() Function and .next() Method

    In Python 2, next() as a method of generator object, is allowed. In Python 2, the next() function, to iterate over generator object, is also accepted. In Python 3, however, next(0 as a generator method is discontinued and raises AttributeError.

    gen = (letter for letter in 'Hello World') # creates generator object
    next(my_generator) #allowed in Python 2 and Python 3
    my_generator.next() #allowed in Python 2. raises AttributeError in Python 3
    

    Convert Python 2 code to Python 3

    Here is a sample Python 2 code (area.py):

    def area(x,y = 3.14): 
       a = y*x*x
       print a
       return a
    
    a = area(10)
    print "area",a
    

    To convert into Python 3 version:

    2to3 -w area.py
    

    Converted code :

    def area(x,y = 3.14): # formal parameters
       a = y*x*x
       print (a)
       return a
    
    a = area(10)
    print("area",a)
    

    Install on windows

    We can download binary from https://www.python.org

    Install on linux

    sudo apt-get install python3-minimal

    Install on linux from source

    wget https://www.python.org/ftp/python/3.5.1/Python-3.8.1.tgz
    tar xvfz Python-3.8.1.tgz
    cd Python-3.8.1
    ./configure --prefix = /opt/python3.8.1
    make  
    sudo make install
    

    Setting up PATH

    Programs and other executable files can be in many directories. Hence, the operating systems provide a search path that lists the directories that it searches for executables.

    The important features are βˆ’

    • The path is stored in an environment variable, which is a named string maintained by the operating system. This variable contains information available to the command shell and other programs.

    • The path variable is named as PATH in Unix or Path in Windows (Unix is case-sensitive; Windows is not).

    • In Mac OS, the installer handles the path details. To invoke the Python interpreter from any particular directory, you must add the Python directory to your path.

    Setting Path at Unix/Linux

    To add the Python directory to the path for a particular session in Unix βˆ’

    • In the csh shell βˆ’ type setenv PATH “$PATH:/usr/local/bin/python3” and press Enter.

    • In the bash shell (Linux) βˆ’ type export PYTHONPATH=/usr/local/bin/python3.8 and press Enter.

    • In the sh or ksh shell βˆ’ type PATH = “$PATH:/usr/local/bin/python3” and press Enter.

    Note βˆ’ /usr/local/bin/python3 is the path of the Python directory.

    Setting Path at Windows

    To add the Python directory to the path for a particular session in Windows βˆ’

    • At the command prompt βˆ’ type path %path%;C:\Programs\python3 and press Enter.

    Ohidur Rahman Bappy
    WRITTEN BY
    Ohidur Rahman Bappy
    πŸ“šLearner 🐍 Developer