Python Module 1 23MBA
Python Module 1 23MBA
MODULE 1
Python - History
1980s: Guido van Rossum, a Dutch programmer, starts working on Python as a hobby project
during Christmas.
1991: Python's first version, Python 0.9.0, is released, featuring exception handling, functions,
and modules.
1994: Python 1.0 is released, with features like lambda, map, filter, and reduce.
2000: Python 2.0 is released, introducing list comprehensions and garbage collection.
2008: Python 3.0 (also known as "Python 3000" and "Py3k") is released, with significant changes
to the language to improve its consistency and eliminate redundancy.
2010: The release of Python 2.7, which would be the last major version in the Python 2.x series,
marking the start of the transition to Python 3.
2018: Python 3.7 is released, featuring various improvements and optimizations.
2020: Python 2 reaches its end-of-life, and all development efforts focus on Python 3.
2021: Python 3.9 is released, introducing features like the walrus operator (:=) and performance
enhancements.
2022: Python 3.10 is released, bringing features like pattern matching and improved error
messages.
2023: Python 3.11 released
2024: Python 3.12 released
Python continues to evolve with regular updates and releases, maintaining its status as one of the
most popular programming languages worldwide.
Python - Characteristics
Readability: Python emphasizes code readability and simplicity, making it easier to write and
understand code, even for beginners.
Versatility: Python is a versatile language, suitable for various domains such as web
development, data science, machine learning, artificial intelligence, automation, and more.
Interpreted: Python is an interpreted language, meaning that code is executed line by line,
allowing for quick prototyping and development.
Dynamic typing: Python uses dynamic typing, where variable types are determined at runtime,
providing flexibility but requiring careful attention to type compatibility.
Large standard library: Python comes with a comprehensive standard library, providing
modules and packages for tasks ranging from file I/O to networking to web development, reducing
the need for external dependencies.
High-level language: Python abstracts away low-level details, allowing developers to focus on
problem-solving rather than system-specific details.
Community support: Python has a large and active community of developers, contributing to a
wealth of resources, libraries, frameworks, and online forums for support and collaboration.
Object-oriented: Python supports object-oriented programming paradigms, allowing for the
creation and manipulation of objects with attributes and methods, facilitating code organization
and reuse.
Cross-platform: Python is available on various operating systems, including Windows, macOS,
and Linux, making it highly portable and accessible across different environments.
Integration: Python can easily integrate with other languages like C/C++, allowing for
performance-critical tasks to be optimized while still leveraging Python's high-level features.
These characteristics contribute to Python's popularity and widespread adoption across different
industries and applications.
Python – Applications
Web Development: Python is widely used for web development, with
frameworks like Django and Flask facilitating the creation of dynamic and
scalable web applications.
Data Science and Machine Learning: Python is a popular choice for
data analysis, machine learning, and artificial intelligence tasks. Libraries
like NumPy, Pandas, scikit-learn, TensorFlow, and PyTorch provide
powerful tools for data manipulation, analysis, and building machine
learning models.
Scientific Computing: Python is extensively used in scientific
computing and computational science for tasks such as simulations,
modeling, and visualization. Libraries like SciPy and Matplotlib are
commonly employed for these purposes.
Automation and Scripting: Python's simplicity and versatility make it
well-suited for automation tasks, scripting, and process automation. It's
commonly used for tasks like file manipulation, data processing, and
system administration.
Desktop GUI Applications: Python can be used to develop desktop GUI
applications using frameworks like Tkinter, PyQt, and PyGTK, allowing
developers to create cross-platform desktop applications with graphical
Game Development: Python is used in game development, both for creating
games from scratch and for scripting within existing game engines like Unity and
Blender. Libraries like Pygame provide tools for game development in Python.
Web Scraping: Python's ease of use and rich ecosystem of libraries make it a
popular choice for web scraping and data extraction tasks. Libraries like
BeautifulSoup and Scrapy are commonly used for extracting data from websites.
Networking: Python is used for networking tasks, such as building network
servers, clients, and network automation scripts. Libraries like Twisted and
asyncio provide tools for asynchronous networking programming.
Education: Python's readability and simplicity make it an excellent choice for
teaching programming concepts to beginners. Many educational institutions use
Python as an introductory programming language.
Financial and Quantitative Analysis: Python is widely used in the finance
industry for tasks such as financial modeling, algorithmic trading, and
quantitative analysis. Libraries like pandas and NumPy are commonly used for
analyzing financial data.
These are just a few examples of the diverse range of applications for Python. Its
versatility, ease of use, and large ecosystem of libraries and frameworks make it
a popular choice for a wide variety of projects and industries.
Python installation
Here are the general steps to install Python on a Windows system:
Choose the latest version of Python for Windows, typically displayed prominently on the page.
Click on the download link for the Windows installer (usually labeled as "Download Python X.X.X").
Once the installer is downloaded, locate the downloaded file (typically in your Downloads folder).
Double-click on the installer file to run it. The file name usually starts with "python-" followed by the version number.
In the Python installer, make sure to check the box that says "Add Python X.X to PATH". This option ensures that Python is added to the system
PATH, allowing you to run Python from the command line easily.
You can also customize the installation by choosing optional features or changing the installation directory if needed. For most users, the default
settings are sufficient.
Install Python:
The installer will copy Python files to your system and set up the environment. This process may take a few minutes.
Verify Installation:
Once the installation is complete, you can verify that Python is installed correctly by opening a command prompt (search for "cmd" in the Start
menu).
In the command prompt, type python --version and press Enter. This command should display the installed Python version. Alternatively, you can
type python and press Enter to start the Python interpreter, where you can execute Python code directly.
That's it! Python should now be successfully installed on your Windows system. You can start writing and running Python code right away.
Anaconda
Anaconda is an open-source distribution of Python and other programming languages commonly used for
data science and machine learning tasks. It includes a wide range of pre-installed libraries and tools that
are essential for data analysis, scientific computing, and machine learning tasks. Anaconda simplifies the
process of setting up and managing environments for data science projects by providing a convenient
package management system called Conda.
Here's how Anaconda is related to Python:
Python Distribution: Anaconda includes Python as its primary programming language. It comes bundled
with the Python interpreter, standard library, and commonly used third-party packages.
Pre-installed Libraries: Anaconda comes with a curated selection of data science libraries pre-installed,
including NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, and many others. These libraries are
commonly used for tasks such as data manipulation, visualization, statistical analysis, and machine
learning.
Conda Package Manager: Anaconda includes Conda, a powerful package and environment management
system. Conda allows users to easily install, update, and manage packages and dependencies for their
Python projects. It also enables the creation and management of isolated environments, which can have
their own set of packages and Python versions, making it easy to manage dependencies and avoid
conflicts between projects.
Cross-platform: Anaconda is available for Windows, macOS, and Linux, making it a versatile choice for
data science and machine learning tasks across different operating systems.
Integrated Development Environment (IDE): Anaconda includes an integrated development
environment called Anaconda Navigator, which provides a graphical interface for managing environments,
installing packages, and launching applications such as Jupyter Notebook, JupyterLab, and Spyder.
Overall, Anaconda provides a convenient and comprehensive platform for data scientists, researchers, and
developers to work with Python and other programming languages for data-intensive tasks. It simplifies
the setup and management of environments and comes with a rich ecosystem of libraries and tools
tailored for data science and machine learning workflows.
Anaconda installation
Here are the steps to install Anaconda on a Windows system:
Download Anaconda Installer:
Go to the Anaconda website at https://www.anaconda.com/products/distribution
Navigate to the download section and choose the appropriate version of Anaconda for your operating system
(Windows).
Select the Python version (Python 3.x is recommended) and download the installer corresponding to your system
architecture (32-bit or 64-bit).
Run Anaconda Installer:
Once the installer is downloaded, locate the downloaded file (typically in your Downloads folder).
Double-click on the installer file to run it. The file name usually starts with "Anaconda3-" followed by the version
number.
Follow Installation Wizard:
The Anaconda installer will launch and display the installation wizard.
Click "Next" to proceed with the installation.
Read and Accept License Agreement:
Read the Anaconda Individual Edition License Agreement.
If you agree to the terms, select "I Agree" and click "Next" to continue.
Choose Installation Type:
Select the installation type. The default option, "Just Me (recommended)", installs Anaconda for your user
account only. You can choose "All Users" if you want to install Anaconda system-wide for all users on the
computer.
Click "Next" to proceed.
Choose Installation Location:
Choose the installation location where Anaconda will be installed. The default location is usually
in your user directory (e.g., C:\Users\YourUsername\Anaconda3).
You can change the installation location if needed.
Click "Next" to continue.
Select Start Menu Folder:
Choose the Start Menu folder where shortcuts for Anaconda will be created.
Click "Install" to begin the installation process.
Wait for Installation to Complete:
The installer will copy files and install Anaconda on your system. This process may take a few
minutes.
Completing the Installation:
Once the installation is complete, click "Next" and then "Finish" to exit the installer.
Verify Installation:
After installation, you can verify that Anaconda is installed correctly by searching for "Anaconda
Navigator" in the Start menu.
Launch Anaconda Navigator, and you should see the graphical interface where you can manage
environments, install packages, and launch applications like Jupyter Notebook and Spyder.
That's it! Anaconda should now be successfully installed on your Windows system, and
you can start using it for data science, machine learning, and other tasks.
Translators: (Interpreters and compilers)
Python is a high-level language intended to be relatively
straightforward for humans to read and write and for computers
to read and process like, Java, C++, PHP, Ruby, Basic, Perl,
JavaScript, and many more.
However, The actual hardware inside the Central Processing Unit
(CPU) does not understand any of these high-level languages.
The CPU understands a language we call machine language.
Machine language is very simple and frankly very tiresome to
write because it is represented all in zeros and ones:
001010001110100100101010000001111
11100110000011101010010101101101
However it is quite tricky and complex to program.
So programmers build translators to convert highend languages
to machine language and vice versa.
2 types of translators
These programming language translators fall into two general
categories: (1) interpreters and (2) compilers.
1. Intepreters:
An interpreter reads the source code of the program as written by the
programmer, parses the source code, and interprets the instructions.
Python is an interpreter and when we are running Python interactively,
we can type a line of Python (a sentence) and Python processes it
immediately and is ready for us to type another line of Python.
>>> x = 6
>>> print(x)
6
>>> y = x * 7
>>> print(y)
42
>>>
2. Compiler:
A compiler needs to be handed the entire program in a file, and then it runs a
process to translate the high-level source code into machine language and then the
compiler puts the resulting machine language into a file for later execution.
If you have a Windows system, often these executable machine language programs
have a suffix of “.exe” or “.dll” which stand for “executable” and “dynamic link
library” respectively. In Linux and Macintosh, there is no suffix that uniquely
marks a file as executable.
If you were to open an executable file in a text editor, it would look completely
crazy and be unreadable:
^?ELF^A^A^A^@^@^@^@^@^@^@^@^@^B^@^C^@^A^@^@^@\xa0\x82
^D^H4^@^@^@\x90^]^@^@^@^@^@^@4^@ ^@^G^@(^@$^@!^@^F^@
^@^@4^@^@^@4\x80^D^H4\x80^D^H\xe0^@^@^@\xe0^@^@^@^E
^@^@^@^D^@^@^@^C^@^@^@^T^A^@^@^T\x81^D^H^T\x81^D^H^S
^@^@^@^S^@^@^@^D^@^@^@^A^@^@^@^A\^D^HQVhT\x83^D^H\xe8
Modules, packages and Libraries
In Python, both module packages and libraries serve
as means to organize and distribute code, but they
differ in their scope and usage.
Module: A module in Python is a single file containing
Python code that defines functions, classes, and
variables. It allows you to organize your code logically
and reuse it across different Python scripts. Modules
are typically used for a specific purpose or
functionality.
Example: Suppose you have a file named
math_operations.py containing functions for
mathematical operations such as addition,
subtraction, multiplication, and division. This file can
be considered a module.
In the context of Python, the terms "package" and "library" are often used interchangeably
but they have slightly different meanings:
Library:
A library in Python refers to a collection of modules that contain reusable code and functions for
specific tasks or domains.
Libraries typically consist of multiple modules that are related to each other and serve a common
purpose.
Examples of Python libraries include NumPy, Pandas, Matplotlib, Requests, and BeautifulSoup.
Package:
A package in Python is a directory that contains one or more modules and an optional __init__.py
file.
Packages allow you to organize related modules into a hierarchical directory structure.
The __init__.py file can be empty or contain initialization code that is executed when the package is
imported.
Packages provide a way to structure and namespace your code, making it easier to manage and
import.
Examples of Python packages include NumPy, Pandas, Matplotlib, Django, Flask, and TensorFlow.
In summary, a library is a collection of modules, while a package is a directory containing
modules and potentially other sub-packages.
However, in everyday usage, the terms "library" and "package" are often used
interchangeably to refer to collections of reusable code in Python.
Part 2
Python -
Values & data types, Variables,
Expressions, statements &
scripts,
Operators,
Functions
Values and value types (data types)
A value is one of the basic unit a program works with,
like a letter or a number. Eg: 1, 2, “Hello, World!”, etc
Values types/data types: There are several types of
values like Integer, float, and string.
strings belong to the type str and integers
belong to the type int. Numbers with a
decimal point belong to a type called float,
because these numbers are represented in a
format called floating point. [We will learn later
that there are types like bool, list, tuple,
dictionary, no type etc]
2 is an integer, 2.00 is a float and “Hello, World!” is a
string, so called because it contains a “string” of
To check the type of a value, type, type; the interpreter will tell
you.
>>> type('Hello, World!')
<class 'str'>
>>> type(17)
<class 'int'>
>>> type(3.2)
<class 'float'>
What about values like “17” and “3.2”? They look like numbers, but they
are in quotation marks like strings.
>>> type('17')
<class 'str'>
>>> type('3.2')
<class 'str'>
They’re strings.
Variables
A variable is a name that refers to a value.
An assignment statement creates new variables and gives them values:
>>> message = ‘There is no class tomorrow'
>>> n = 17
>>> pi = 3.1415926535897931
This example makes three assignments. The first assigns a string to a new variable named message; the second
assigns the integer 17 to n; the third assigns the (approximate) value of π to pi.
To display the value of a variable, you can use a print statement:
>>> print(n)
17
>>> print(pi)
3.141592653589793
The type of a variable is the type of the value it refers to (and not of the variable itself)
>>> type(message)
<class 'str'>
>>> type(n)
<class 'int'>
>>> type(pi)
<class 'float'>
Variable names
Programmers generally choose names for their variables that are
- Meaningful and represent what the variable is used for.
- Variable names can be arbitrarily long.
- They can contain both letters and numbers,
- But they cannot start with a number
- They cannot have space in between and
- They are case sensitive
- Cannot use key words
- It is legal to use uppercase letters, but it is a good idea to begin variable
names with a lowercase letter (you’ll see why later).
- The underscore character ( _ ) can appear in a name. It is often used in
names with multiple words, - such as my_name or mary_had_a_little_lamb
- Variable names can start with an underscore character, but we generally
avoid doing this unless we are writing library code for others to us
Illegal names
If you give a variable an illegal name, you get a syntax error:
examples,
>>> 76trombones = 'big parade' SyntaxError: invalid
syntax
>>> more@ = 1000000 SyntaxError: invalid syntax
>>> class = 'Advanced Theoretical Zymurgy' SyntaxError:
invalid syntax
76trombones is illegal because it begins with a number.
more@ is illegal because it contains an illegal character @,
and class is a key word in python
Case sensitivity –they are case sensitive
Space – space matters
It turns out that class is one of Python’s keywords. The interpreter
uses keywords to recognize the structure of the program, and they
cannot be used as variable names.
Python reserves 35 keywords:
This program produces the following list of 10 random numbers between 0.0 and up to but not including 1.0.
0.11132867921152356
0.5950949227890241
0.04820265884996877
0.841003109276478
0.997914947094958
0.04842330803368111
0.7416295948208405
0.510535245390327
0.27447040171978143
0.028511805472785867
Composition of function/composite function
Composite function is where any kind of expression
(including arithmetic operators) or another function is used
as an argument to a function. Example:
X=math.sin(angle+math.pi/4)
Here we have used an expression (angle+math.pi)/4 as an
argument to the function math.sin.
First the inner expression is calculated and the resultant
value is used as an argument for the function math.sin
Similarly we can take a function as an argument for
another function Example:
X=math.exp(math.log(10.0))
Here the value of function math.log(10.0) is calculated first
and used as an argument for the function math.exp
Creating new functions - user defined functions
A function definition specifies the name of a new function and the sequence of
statements that execute when the function is called. Example:
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print('I sleep all night and I work all day.')
def is a keyword that indicates that this is a function definition. The name of the
function is print lyrics.
[The rules for function names are the same as for variable names: letters,
numbers and some punctuation marks are legal, but the first character can’t be a
number. You can’t use a keyword as the name of a function, and you should avoid
having a variable and a function with the same name]
The empty parentheses after the name indicate that this function
doesn’t take any arguments. Later we will build functions that take
arguments as their inputs.
The first line of the function definition is called the header; the rest
is called the body. The header has to end with a colon and the body has
to be indented. By convention, the indentation is always four spaces.
The body can contain any number of statements.
If you type a function definition in interactive mode, the interpreter prints
ellipses (. . . ) to let you know that the definition isn’t complete:
>>> def print_lyrics():
... print("I'm a lumberjack, and I'm okay.")
... print('I sleep all night and I work all day.')
…
To end the function, you have to enter an empty line (this is not necessary in
a script). Defining a function creates a variable with the same name
The value of the variable print_lyrics is called a ‘function object’ , which is of
type “function”.
The syntax for calling the new function is the same as for built-in functions:
print(type(print_lyrics))
<class 'function'>
Calling the function:
>>> print_lyrics()
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
Recursion or recursive function
If a function calls itself it is called recursion or recursive
function. Usually a function calls another function but in this
case it calls itself.
Example:
Def countdown(n):
if n <= 0:
print(Blast off!)
else:
print(n)
countdown(n-1)
Please note that this is very similar to iteration which uses while
statement and updating variables. This one uses If, else
statement and repeats a function itself