Introduction to python 3

Introduction to python 3

Python is a high-level, general-purpose, and very popular programming language. Python programming language (latest Python 3) is being used in web development and machine Learning applications, along with all cutting-edge technology in the Software Industry.

Python language is being used by almost all tech-giant companies like – Google, Amazon, Facebook, Instagram, Dropbox, Uber… etc.

The biggest strength of Python is a huge collection of standard libraries which can be used for the following:

  • Machine Learning

  • GUI Applications (like Kivy, Tkinter, PyQt etc. )

  • Web frameworks like Django (used by YouTube, Instagram, and Dropbox)

  • Image processing (like OpenCV, Pillow)

  • Web scraping (like Scrapy, BeautifulSoup, Selenium)

  • Test frameworks

  • Multimedia

  • Scientific computing

Text processing and many more.

The nature of the language

Python is one of the most popular general-purpose programming languages in modern times.

The term “general purpose” simply means that Python can be used for a variety of applications and does not focus on any one aspect of programming.

A High-Level Language

Python falls under the category of high-level, interpreted languages. A high-level language cannot be understood directly by our machine. There is a certain degree of abstraction in its syntax. Machines are generally designed to read machine code, but high-level syntax cannot be directly converted to machine code.

As a result, it must first be converted to bytecode which is then converted to machine code before the program can be executed.

Python is an interpreted language because, during execution, each line is interpreted to the machine language on the go.

However, if we take the example of C++, the code needs to be compiled into an executable first, and then it can be executed. In Python, we can skip this compilation step (Python does it for us behind the scenes) and directly run the code.

Readability

One of the biggest reasons for Python’s rapid growth is the simplicity of its syntax. The language reads almost like plain English, making it easy to write complex programs.

Since it doesn’t have much of a learning curve, Python is a very good entry point into the world of programming for beginners.

Applications

Apart from the ease of learning, Python is a very efficient language which is used in almost every sphere of modern computing.

This makes a strong case for learning Python, even for non-programmers.

Some of Python’s main applications are highlighted below:

Python Application Areas in the Real World

We are living in a digital world that is completely driven by chunks of code. Every industry depends on software for its proper functioning be it healthcare, military, banking, research, and the list goes on. We have a huge list of programming languages that facilitate the software development process. One of these is Python which has emerged as the most lucrative and exciting programming language. As per a survey it is observed that Python is the main coding language for more than 80% of developers. The main reason behind this is its extensive libraries and frameworks that fuel up the process.

Python has been at the forefront of Machine learning, data science, and artificial intelligence innovation. Further, it provides ease in building a plethora of applications, web development processes, and a lot more. In this blog, we will discuss the top 10 Python applications in the real world in a detailed manner. So let’s get started:

1. Web Development

It is one of the most astonishing/amazing applications of Python because Python comes up with a wide range of frameworks like Django, Flask, Bottle, and a lot more making it very easy to develop and deploy simple as well as complex web applications. Furthermore, Python has inbuilt libraries and tools which make the web development process completely effortless. The use of Python for web development also offers:

  • Amazing visualization

  • Convenience in development

  • Enhanced security

  • Fast development process

2. Machine Learning and Artificial Intelligence

Machine Learning and Artificial Intelligence are the hottest subjects right now. Python along with its inbuilt libraries and tools facilitate the development of AI and ML algorithms. Further, it offers simple, concise, and readable code which makes it easier for developers to write complex algorithms and provide a versatile flow. Some of the inbuilt libraries and tools that enhance AI and ML processes are:

  • Numpy for complex data analysis

  • Keras for Machine learning

  • SciPy for technical computing

  • Seaborn for data visualization

3. Data Science

Data science involves data collection, data sorting, data analysis, and data visualization. Python provides amazing functionality to tackle statistics and complex mathematical calculations. The presence of in-built libraries provides convenience to data science professionals. Some of the popular libraries that provide ease in the data science process are TensorFlow, Pandas, and Socket Learning. These libraries provide an ecosystem for fine-tuning data models, data preprocessing, and performing complex data analysis.

4. Game Development

With the rapidly growing gaming industry, Python has proved to be an exceptional option for game development. Popular games like Pirates of the Caribbean, Bridge Commander, and Battlefield 2 use Python programming for a wide range of functionalities and add-ons. The presence of popular 2D and 3D gaming libraries like pygame, panda3D, and Cocos2D makes the game development process completely effortless.

5. Audio and Visual Applications

Audio and video applications are undoubtedly the most amazing feature of Python. Python is equipped with a lot of tools and libraries to accomplish your task flawlessly. Applications that are coded in Python include popular ones like Netflix, Spotify, and YouTube. This can be handled by libraries like

  • Dejavu

  • Pyo

  • Mingus

  • SciPy

  • OpenCV

6. Software Development

Python is just the perfect option for software development. Popular applications like Google, Netflix, and Reddit all use Python. This language offers amazing features like:

  • Platform independence

  • Inbuilt libraries and frameworks to provide ease of development.

  • Enhanced code reusability and readability

  • High compatibility

Apart from these Python offers enhanced features to work with rapidly growing technologies like Machine learning and Artificial intelligence. All these embedded features make it a popular choice for software development.

7. CAD Applications

CAD refers to computer-aided design; it is the process of creating 3D and 2D models digitally. This application has replaced manual drift and is used by architects, product designers, and construction managers to design products with extremely high consistency. Python is embedded with amazing applications like Blender, FreeCAD, Open Cascade, and a lot more to efficiently design products. These provide enhanced features like technical drawing, dynamic system development, recordings, file export, and import.

8. Business Applications

Python offers excellent security and scalability features that make it perfect for delivering high-performance business applications. It has inbuilt libraries and tools like:

  • Odoo is business management software that provides you with an automated solution for your business process.

  • Tryton is an easy-to-use open-source business software. It has fully integrated features like financial accounting, sales, CRM, purchasing, shipping, and the list goes on.

All these distinguishing features make it fit for creating business applications.

9. Desktop GUI

Python is an interactive programming language that helps developers to create GUIs easily and efficiently. It has a huge list of inbuilt tools like PyQT, kivy, wxWidgets, and many other libraries like them to build a fully functional GUI in an extremely secure and efficient manner.

10. Web Scraping Application

Web scraping is an automated process used to extract information from websites in an easier and faster way. The information is used by researchers, organizations, and analysts for a wide variety of tasks. Python has a wide range of features that make it suitable for web scraping some of them are:

  • A concise syntax that enhances readability and saves your time.

  • A wide range of libraries and tools like pandas, matplotlib, and Selenium makes the web scraping process easy and efficient.

  • Easy to use and understand

Some other real-world applications of Python are:

  • Robotics and automation by the use of inbuilt libraries and tools like PyDy, Dart, PyRobot, and Pyro.

  • Image processing: some of the amazing libraries and tools for image processing are Blender, OpenCV, Houdini, and PIL.

  • Scientific applications are facilitated by popular libraries like Pandas, Matplotlib, SciPy, and many more

Programming Paradigms in Python

Paradigm can also be termed as a method to solve some problems or do some tasks. A programming paradigm is an approach to solving a problem using some programming language or also we can say it is a method to solve a problem using tools and techniques that are available to us following some approach.

There are lots of programming languages that are known but all of them need to follow some strategy when they are implemented and this methodology/strategy is paradigms. Apart from a variety of programming languages, there are lots of paradigms to fulfil every demand.

Python supports three types of Programming paradigms

  1. Procedural programming paradigms

  2. Object Oriented programming paradigms

  3. Functional programming paradigms

    1. Procedural programming paradigms

In Procedure programming paradigms, a series of computational steps are divided into modules which means that the code is grouped into functions and the code is serially executed step by step basically, it combines the serial code to instruct a computer with each step to perform a certain task. This paradigm helps in the modularity of code and modularization is usually done by the functional implementation. This programming paradigm helps in an easy organization of related items without difficulty and so each file acts as a container.

Advantages:

  • General-purpose programming

  • Code reusability

  • Portable source code

Disadvantages:

  • Data protection

  • Not suitable for real-world objects

  • Harder to write

Example:

# Procedural way of finding sum
# of a list

mylist = [10, 20, 30, 40]

# modularization is done by
# functional approach
def sum_the_list(mylist):
    res = 0
    for val in mylist:
        res += val
    return res

print(sum_the_list(mylist))

Output:

100

2. Object Oriented programming paradigms

In the object-oriented programming paradigm, objects are the key element of paradigms. Objects can simply be defined as the instance of a class that contains both data members and the method functions. Moreover, the object-oriented style relates data members and methods functions that support encapsulation and with the help of the concept of inheritance, the code can be easily reusable but the major disadvantage of the object-oriented programming paradigm is that if the code is not written properly then the program becomes a monster.

Advantages

  • Relation with Real-world entities

  • Code reusability

  • Abstraction or data hiding

Disadvantages

  • Data protection

  • Not suitable for all types of problems

  • Slow Speed

Example:

# class Emp has been defined here
class Emp:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def info(self):
        print("Hello, % s. You are % s old." % (self.name, self.age))

# Objects of class Emp has been 
# made here        
Emps = [Emp("John", 43),
    Emp("Hilbert", 16),
    Emp("Alice", 30)]

# Objects of class Emp has been
# used here
for emp in Emps:
    emp.info()

Output:

Hello, John. You are 43 old.
Hello, Hilbert. You are 16 old.
Hello, Alice. You are 30 old.

3. Functional programming paradigms

Functional programming paradigms a paradigms in which everything is bound in pure mathematical functions style. It is known as the declarative paradigm because it uses declarations overstatements. It uses the mathematical function and treats every statement as a functional expression as an expression is executed to produce a value. Lambda functions or Recursion are basic approaches used for its implementation. The paradigms mainly focus on “what to solve” rather than “how to solve”. The ability to treat functions as values and pass them as an argument makes the code more readable and understandable.

Advantages

  • Simple to understand

  • Making debugging and testing easier

  • Enhances the comprehension and readability of the code

Disadvantages

  • Low performance

  • Writing programs is a daunting task

  • Low readability of the code

Example:

# Functional way of finding sum of a list 
import functools


mylist = [11, 22, 33, 44]

# Recursive Functional approach
def sum_the_list(mylist):

    if len(mylist) == 1:
        return mylist[0]
    else:
        return mylist[0] + sum_the_list(mylist[1:])

# lambda function is used
print(functools.reduce(lambda x, y: x + y, mylist))

Output:

110

Features of Python

Let's highlight some of the important features of Python that make it widely popular. Apart from these 10 features, there are several other interesting features which make Python most of the developer's first choice.

Python Important Features

The following section will explain these features in more detail:

1. Python is Easy to Learn

This is one of the most important reasons for the popularity of Python. Python has a limited set of keywords. Its features such as simple syntax, usage of indentation to avoid clutter of curly brackets and dynamic typing that doesn’t necessitate prior declaration of variables help a beginner to learn Python quickly and easily.

2. Python is an Interpreter Based

Instructions in any programming language must be translated into machine code for the processor to execute them. Programming languages are either compiler-based or interpreter-based.

In the case of a compiler, a machine language version of the entire source program is generated. The conversion fails even if there is a single erroneous statement. Hence, the development process is tedious for beginners. The C family languages (including C, C++, Java, C Sharp etc.) are compiler-based.

Python is an interpreter-based language. The interpreter takes one instruction from the source code at a time, translates it into machine code and executes it. Instructions before the first occurrence of error are executed. With this feature, it is easier to debug the program and thus proves useful for the beginner-level programmer to gain confidence gradually. Python therefore is a beginner-friendly language.

  • how Python interpreter works in interactive and scripted mode. Python code is executed by one statement at a time method. Python interpreter has two components. The translator checks the statement for syntax. If found correct, it generates an intermediate byte code. There is a Python virtual machine which then converts the byte code into native binary and executes it. The following diagram illustrates the mechanism:

    Python Interpreter

    Python interpreter has an interactive mode and a scripted mode.

    Python Interpreter - Interactive Mode

    When launched from a command line terminal without any additional options, a Python prompt >>> appears and the Python interpreter works on the principle of REPL (Read, Evaluate, Print, Loop). Each command entered in front of the Python prompt is read, translated and executed. A typical interactive session is as follows.

      >>> price = 100
      >>> qty = 5
      >>> ttl = price*qty
      >>> ttl
      500
      >>> print ("Total = ", ttl)
      Total = 500
    

    To close the interactive session, enter the end-of-line character (ctrl+D for Linux and ctrl+Z for Windows). You may also type quit() in front of the Python prompt and press Enter to return to the OS prompt.

    The interactive shell available with standard Python distribution is not equipped with features like line editing, history search, auto-completion etc. You can use other advanced interactive interpreters software such as IPython and BPython.

    Python Interpreter - Scripting Mode

    Instead of entering and obtaining the result of one instruction at a time as in the interactive environment, it is possible to save a set of instructions in a text file, make sure that it has a .py extension, and use the name as the command line parameter for Python command.

    Save the following lines as prog.py, with the use of any text editor such as Vim on Linux or Notepad on Windows.

      print ("My first program")
      price = 100
      qty = 5
      ttl = price*qty
      print ("Total = ", ttl)
    

    When we execute the above program, it will produce the following result:

      C:\Users\Acer>python prog.py
      My first program
      Total = 500
    

    Note that even though Python executes the entire script in one go, internally it is still executed in a line-by-line fashion.

    In the case of any compiler-based language such as Java, the source code is not converted into byte code unless the entire code is error-free. In Python, on the other hand, statements are executed until the first occurrence of error is encountered.

    Let us introduce an error purposefully in the above code.

      print ("My first program")
      price = 100
      qty = 5
      ttl = prive*qty #Error in this statement
      print ("Total = ", ttl)
    

    Note the misspelt variable Prive instead of price. Try to execute the script again as before −

      C:\Users\Acer>python prog.py
      My first program
      Traceback (most recent call last):
        File "C:\Python311\prog.py", line 4, in <module>
         ttl = prive*qty
         ^^^^^
      NameError: name 'prive' is not defined. Did you mean: 'price'?
    

    Note that the statements before the erroneous statement are executed and then the error message appears. Thus it is now clear that Python script is executed in an interpreted manner.

    Python Interpreter - Using Shebang #!

    In addition to executing the Python script as above, the script itself can be self-executable in Linux, like a shell script. You have to add a shebang line on top of the script. The shebang indicates which executable is used to interpret Python statements in the script. The very first line of the script starts with #! and by the path to the Python executable.

    Modify the prog.py script as follows −

      #! /usr/bin/python3.11
      print ("My first program")
      price = 100
      qty = 5
      ttl = price*qty
      print ("Total = ", ttl)
    

    To mark the script as self-executable, use the chmod command

      $ chmod +x prog.py
    

    You can now execute the script directly, without using it as a command-line argument.

      $ ./hello.py
    

    Interactive Python - IPython

    IPython (stands for Interactive Python) is an enhanced and powerful interactive environment for Python with many functionalities compared to the standard Python shell. IPython was originally developed by Fernando Perez in 2001.

    IPython has the following important features −

    • IPython's object introspection ability to check the properties of an object during runtime.

    • Its syntax highlighting proves to be useful in identifying the language elements such as keywords, variables etc.

    • The history of interactions is internally stored and can be reproduced.

    • Tab completion of keywords, variables and function names is one of the most important features.

    • IPython's Magic command system is useful for controlling the Python environment and performing OS tasks.

    • It is the main kernel for Jupyter Notebook and other front-end tools of Project Jupyter.

Install IPython with the PIP installer utility.

    pip3 install ipython

Launch IPython from the command line

    C:\Users\Acer>ipython
    Python 3.11.2 (tags/v3.11.2:878ead1, Feb 7 2023, 16:38:35) [MSC v.1934
    64 bit (AMD64)] on win32
    Type 'copyright', 'credits' or 'license' for more information
    IPython 8.4.0 -- An enhanced Interactive Python. Type '?' for help.
    In [1]:

Instead of the regular >>> prompt as in standard interpreter, you will notice two major IPython prompts as explained below −

  • In[1] appears before any input expression.

  • Out[1]appears before the Output appears.

    In [1]: price = 100
    In [2]: quantity = 5
    In [3]: ttl = price*quantity
    In [4]: ttl
    Out[4]: 500
    In [5]:

Tab completion is one of the most useful enhancements provided by IPython. IPython pops up an appropriate list of methods as you press tab key after the dot in front of the object.

IPython provides information (introspection) of any object by putting ? in front of it. It includes docstring, function definitions and constructor details of the class. For example to explore the string object var defined above, in the input prompt enter var?.

    In [5]: var = "Hello World"
    In [6]: var?
    Type: str
    String form: Hello World
    Length: 11
    Docstring:
    str(object='') -> str
    str(bytes_or_buffer[, encoding[, errors]]) -> str
    Create a new string object from the given object. If encoding or
    errors is specified, then the object must expose a data buffer
    that will be decoded using the given encoding and error handler.
    Otherwise, returns the result of object.__str__() (if defined)
    or repr(object).
    encoding defaults to sys.getdefaultencoding().
    errors defaults to 'strict'.

IPython's magic functions are extremely powerful. Line magics lets you run DOS commands inside IPython. Let us run the dir command from within the IPython console

    In [8]: !dir *.exe
     Volume in drive F has no label.
     Volume Serial Number is E20D-C4B9

     Directory of F:\Python311

    07-02-2023 16:55            103,192 python.exe
    07-02-2023 16:55            101,656 pythonw.exe
                    2 File(s)    204,848 bytes
                    0 Dir(s)  105,260,306,432 bytes free

Jupyter Notebook is a web-based interface to programming environments of Python, Julia, R and many others. For Python, it uses IPython as its main kernel.

3. Python is Interactive

Standard Python distribution comes with an interactive shell that works on the principle of REPL (Read – Evaluate – Print – Loop). The shell presents a Python prompt >>>. You can type any valid Python expression and press Enter. Python interpreter immediately returns the response and the prompt comes back to read the next expression.

    >>> 2*3+1
    7
    >>> print ("Hello World")
    Hello World

The interactive mode is especially useful for getting familiar with a library and testing out its functionality. You can try out small code snippets in interactive mode before writing a program.

4.Python is MultiParadigm

Python is a completely object-oriented language. Everything in a Python program is an object. However, Python conveniently encapsulates its object orientation to be used as an imperative or procedural language – such as C. Python also provides certain functionality that resembles functional programming. Moreover, certain third-party tools have been developed to support other programming paradigms such as aspect-oriented and logic programming.

5. Python’s Standard Library

Even though it has very few keywords (only Thirty-Five), Python software is distributed with a standard library made of a large number of modules and packages. Thus Python has out-of-the-box support for programming needs such as serialization, data compression, internet data handling, and many more. Python is known for its batteries-included approach.

6. Python is Open Source and Cross-Platform

Python’s standard distribution can be downloaded from python.org/downloads without any restrictions. You can download pre-compiled binaries for various operating system platforms. In addition, the source code is also freely available, which is why it comes under the open-source category.

Python software (along with the documentation) is distributed under the Python Software Foundation License. It is a BSD-style permissive software license and compatible with GNU GPL (General Public License).

Python is a cross-platform language. Pre-compiled binaries are available for use on various operating system platforms such as Windows, Linux, Mac OS, and Android OS. The reference implementation of Python is called CPython and is written in C. You can download the source code and compile it for your OS platform.

A Python program is first compiled to an intermediate platform independent byte code. The virtual machine inside the interpreter then executes the byte code. This behaviour makes Python a cross-platform language, and thus a Python program can be easily ported from one OS platform to another.

7. Python for GUI Applications

Python’s standard distribution has an excellent graphics library called TKinter. It is a Python port for the vastly popular GUI toolkit called TCL/Tk. You can build attractive user-friendly GUI applications in Python. GUI toolkits are generally written in C/C++. Many of them have been ported to Python. Examples are PyQt, WxWidgets, PySimpleGUI etc.

8. Python’s Database Connectivity

Almost any type of database can be used as a backend with the Python application. DB-API is a set of specifications for database driver software to let Python communicate with a relational database. With many third-party libraries, Python can also work with NoSQL databases such as MongoDB.

9. Python is Extensible

The term extensibility implies the ability to add new features or modify existing features. As stated earlier, CPython (which is Python’s reference implementation) is written in C. Hence one can easily write modules/libraries in C and incorporate them in the standard library. There are other implementations of Python such as Jython (written in Java) and IPython (written in C#). Hence, it is possible to write and merge new functionality in these implementations with Java and C# respectively.

10. Python’s Active Developer Community

As a result of Python’s popularity and open-source nature, a large number of Python developers often interact with online forums and conferences. Python Software Foundation also has a significant member base, involved in the organization’s mission to "promote, protect, and advance the Python programming language”

Python also enjoys significant institutional support. Major IT companies Google, Microsoft, and Meta contribute immensely by preparing documentation and other resources.