1. Introduction to Python Programming
1. Introduction to Python Programming
Python is easy to learn yet powerful and versatile scripting language, which makes it attractive for
Application Development.
Python's syntax and dynamic typing with its interpreted nature make it an ideal language for
scripting and rapid application development.
Python is not intended to work in a particular area, such as web programming. That is why it is
known as multipurpose programming language because it can be used with web, enterprise, 3D
CAD, etc.
We don't need to use data types to declare variable because it is dynamically typed so we can write
a=10 to assign an integer value in an integer variable.
Python makes the development and debugging fast because there is no compilation step included in
Python development, and edit-test-debug cycle is very fast.
Python Features
Python provides many useful features which make it popular and valuable from the other
programming languages. It supports object-oriented programming; procedural programming
approaches and provides dynamic memory allocation. We have listed below a few essential
features.
Python is easy to learn as compared to other programming languages. Its syntax is straight forward
and much the same as the English language. There is no use of the semicolon or curly-bracket, the
indentation defines the code block. It is the recommended programming language for beginners.
2. Expressive Language
Python can perform complex tasks using a few lines of code. A simple example, the hello world
program you simply type print("Hello World"). It will take only one line to execute, while Java or
C takes multiple lines.
INTRODUCTION TO PYTHON PROGRAMMING
3. Interpreted Language
Python is an interpreted language; it means the Python program is executed one line at a time. The
advantage of being interpreted language, it makes debugging easy and portable.
4. Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, UNIX, and Macintosh, etc.
So, we can say that Python is a portable language. It enables programmers to develop the software
for several competing platforms by writing a program only once.
Python is freely available for everyone. It is freely available on its official website
www.python.org. It has a large community across the world that is dedicatedly working towards
make new python modules and functions. Anyone can contribute to the Python community. The
open-source means, "Anyone can download its source code without paying any penny."
6. Object-Oriented Language
Python supports object-oriented language and concepts of classes and objects come into existence.
It supports inheritance, polymorphism, and encapsulation, etc. The object-oriented procedure helps
to programmer to write reusable code and develop applications in less code.
7. Extensible
It implies that other languages such as C/C++ can be used to compile the code and thus it can be
used further in our Python code. It converts the program into byte code, and any platform can use
that byte code.
It provides a vast range of libraries for the various fields such as machine learning, web developer,
and also for the scripting. There are various machine learning libraries, such as Tensor flow,
Pandas, Numpy, Keras, and Pytorch, etc. Django, flask, pyramids are the popular framework for
Python web development.
Graphical User Interface is used for the developing Desktop application. PyQT5, Tkinter, Kivy are
the libraries which are used for developing the web application.
10. Integrated
INTRODUCTION TO PYTHON PROGRAMMING
It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs code line by line
like C,C++ Java. It makes easy to debug the code.
11. Embeddable
The code of the other programming language can use in the Python source code. We can use Python
source code in another programming language as well. It can embed other language into our code.
In Python, we don't need to specify the data-type of the variable. When we assign some value to the
variable, it automatically allocates the memory to the variable at run time. Suppose we are assigned
integer value 15 to x, then we don't need to write int x = 15. Just write x = 15.
Python Applications
Python is known for its general-purpose nature that makes it applicable in almost every domain of
software development. Python makes its presence in every emerging field. It is the fastest-growing
programming language and can develop any application.
1. Web Applications
We can use Python to develop web applications. It provides libraries to handle internet protocols
such as HTML and XML, JSON, Email processing, request, beautifulSoup, Feedparser, etc. One of
Python web-framework named Django is used on Instagram. Python provides many useful
frameworks, and these are given below:
The GUI stands for the Graphical User Interface, which provides a smooth interaction to any
application. Python provides a Tk GUI library to develop a user interface. Some popular GUI
libraries are given below.
o Tkinter or Tk
o wxWidgetM
o PyQt or Pyside
3. Console-based Application
Console-based applications run from the command-line or shell. These applications are computer
program which are used commands to execute. This kind of application was more popular in the old
generation of computers. Python can develop this kind of application very effectively. It is famous
for having REPL, which means the Read-Eval-Print Loop that makes it the most suitable language
for the command-line applications.
Python provides many free library or module which helps to build the command-line apps. The
necessary IO libraries are used to read and write. It helps to parse argument and create console help
text out-of-the-box. There are also advance libraries that can develop independent console apps.
4. Software Development
Python is useful for the software development process. It works as a support language and can be
used to build control and management, testing, etc.
o Buildbot and Apache Gumps are used for automated continuous compilation and testing.
This is the era of Artificial intelligence where the machine can perform the task the same as the
human. Python language is the most suitable language for Artificial intelligence or machine
learning. It consists of many scientific and mathematical libraries, which makes easy to solve
complex calculations.
Implementing machine learning algorithms require complex mathematical calculation. Python has
many libraries for scientific and numeric such as Numpy, Pandas, Scipy, Scikit- learn, etc. If you
have some basic knowledge of Python, you need to import libraries on the top of the code. Few
popular frameworks of machine libraries are given below.
o SciPy
o Scikit-learn
o NumPy
o Pandas
o Matplotlib
6. Business Applications
Business Applications differ from standard applications. E-commerce and ERP are an example of a
business application. This kind of application requires extensively, scalability and readability, and
Python provides all these features.
Oddo is an example of the all-in-one Python-based application which offers a range of business
applications. Python provides a Tryton platform which is used to develop the business application.
Python is flexible to perform multiple tasks and can be used to create multimedia applications.
Some multimedia applications which are made by using Python are TimPlayer, cplay, etc. The few
multimedia libraries are given below.
o Gstreamer
o Pyglet
INTRODUCTION TO PYTHON PROGRAMMING
o QTPhonon
8. 3D CAD Applications
The CAD (Computer-aided design) is used to design engineering related architecture. It is used to
develop the 3D representation of a part of a system. Python can create a 3D CAD application by
using the following functionalities.
o Fandango(Popular)
o CAMVOX
o HeeksCNC
o AnyCAD
o RCAM
9. Enterprise Applications
Python can be used to create applications that can be used within an Enterprise or an Organization.
Some real-time applications are OpenERP, Tryton, Picalo, etc.
Python contains many libraries that are used to work with the image. The image can be manipulated
according to our requirements. Some libraries of image processing are given below.
o OpenCV
o Pillow
o SimpleITK
Unlike the other programming languages, Python provides the facility to execute the code using few
lines. For example - Suppose we want to print the "Hello World" program in Java; it will take
three lines to print it.
Java Program
Python Program
print("HelloWorld")
Both programs will print the same result, but it takes only one statement without using a semicolon
or curly braces in Python.
def func():
statement 1
statement 2
……………
……………
statement N
In the above example, the statements that are same level to right belong to the function. Generally,
we can use four whitespaces to define indentation.
o In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to
alt.sources.
o In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce.
o Python 2.0 added new features such as list comprehensions, garbage collection systems.
o On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to
rectify the fundamental flaw of the language.
o ABC programming language is said to be the predecessor of Python language, which was
capable of Exception Handling and interfacing with the Amoeba Operating System.
o The following programming languages influence Python:
o ABC language.
o Modula-3
There is a fact behind choosing the name Python. Guido van Rossum was reading the script of a
popular BBC comedy series "Monty Python's Flying Circus". It was late on-air 1970s.
Van Rossum wanted to select a name which unique, sort, and little-bit mysterious. So, he decided to
select naming Python after the "Monty Python's Flying Circus" for their newly created
programming language.
The comedy series was creative and well random. It talks about everything. Thus, it is slow and
unpredictable, which made it very interesting.
Python is also versatile and widely used in every technical field, such as Machine Learning,
Artificial Intelligence, Web Development, Mobile Application, Desktop Application, Scientific
Calculation, etc.
Python programming language is being updated regularly with new features and
supports. There are lots of update in Python versions, started from 1994 to current
release.
Installation of Python
Python is a widely used high-level programming language. To write and execute code in python, we
first need to install Python on our system.
Python has various versions available with differences between the syntax and working of different
versions of the language. We need to choose the version which we want to use or need. There are
different versions of Python 2 and Python 3 available.
On the web browser, in the official site of python(www.python.org), move to the Download for
Windows section.
All the available versions of Python will be listed. Select the version required by you and click on
Download. Let suppose, we chose the Python 3.9.1 version.
On clicking download, various available executable installers shall be visible with different
operating system specifications. Choose the installer which suits your system operating system and
download the installer. Let suppose, we select the Windows installer(64 bits).
Run the installer. Make sure to select both the checkboxes at the bottom and then click Install New.
The installation process will take few minutes to complete and once the installation is successful,
the following screen is displayed.
INTRODUCTION TO PYTHON PROGRAMMING
To ensure if Python is successfully installed on your system. Follow the given steps−
The version of the python which you have installed will be displayed if the python is
successfully installed on your windows.
Pip is a powerful package management system for Python software packages. Thus, make sure that
you have it installed.
Python IDE’s
Python has several Integrated Development Environments (IDEs) that provide a comprehensive set
of tools and features to support software development in Python. Here are some popular Python
IDEs:
1. PyCharm: Developed by JetBrains, PyCharm is a powerful and feature-rich IDE that offers a
wide range of tools for Python development.
2. Visual Studio Code (VSCode): A lightweight and versatile code editor, VS Code has gained
popularity due to its extensibility and support for multiple programming languages, including
Python.
3. Spyder: Designed for scientific computing and data analysis, Spyder provides a user- friendly
IDE with features tailored for scientific Python development.
5. IDLE: As Python's default IDE, IDLE comes bundled with the Python installation. It offers a
simple and lightweight development environment suitable for beginners.
6. Anaconda: Anaconda is a Python distribution that includes its own integrated development
environment called Anaconda Navigator. It provides a convenient way to manage Python packages
and environments for data science and scientific computing.
7. Wing IDE: WingIDE is a commercial Python IDE known for its powerful debugger and code
intelligence features. It supports web development frameworks like Django and Flask.
8. Eric IDE: Eric IDE is an open-source IDE written in Python. It offers a range of features
including code navigation, refactoring, debugging, and support for various frameworks.
INTRODUCTION TO PYTHON PROGRAMMING
9. Sublime Text: Although not exclusively for Python, Sublime Text is a popular code editor with
a large user base. It provides a smooth editing experience and supports Python through plugins.
10. Atom: Atom is another highly customizable and extensible code editor that supports Python
development. It offers a wide range of plugins and packages to enhance the development
experience.
These are just some of the popular Python IDEs available, and the best choice for you will depend
on your specific needs and preferences.
Identifiers in Python
Identifier is a user-defined name given to a variable, function, class, module, etc. The
identifier is a combination of character digits and an underscore. They are case-sensitive i.e., ‘num’
and ‘Num’ and ‘NUM’ are three different identifiers in python. It is a good programming practice
to give meaningful names to identifiers to make the code understandable.
We can also use the Python string isidentifier( ) method to check whether a string is a valid
identifier or not.
Rules for Naming Python Identifiers
It cannot be a reserved python keyword.
It should not contain whitespace.
Invalid Identifiers
!var1
1var
1_var
var#1
var1
Variables in Python
Python Variable is containers that store values. Python is not “statically typed”. We do not
need to declare variables before using them or declare their type. A variable is created the moment
we first assign a value to it. A Python variable is a name given to a memory location. It is the basic
unit of storage in a program.
Note:
The value stored in a variable can be changed during program execution.
A variable in Python is only a name given to a memory location; all the operations done
on the variable effects that memory location.
Rules for Python variables
A Python variable name must start with a letter or the underscore character.
A Python variable name cannot start with a number.
A Python variable name can only contain alpha-numeric characters and underscores (A-
z, 0-9, and _).
Variable in Python names are case-sensitive (name, Name, and NAME are three
different variables).
The reserved words (keywords) in Python cannot be used to name the variable in
Python.
Python provides various standard data types that define the storage method on each of them. The
data types defined in Python are given below.
1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary
b=5.0
print("\n Type of b:",type(b))
c=2+4j
print("\n Type of c:",type(c))
Output:
Type of a:<class 'int'>
Python String
Python List
Python Tuple
String Data Type
Strings in Python are arrays of bytes representing Unicode characters. A string is a
collection of one or more characters put in a single quote, double-quote, or triple-quote. In python
there is no character data type, a character is a string of length one. It is represented by str class.
Note: Strings in Python can be created using single quotes or double quotes or even triple quotes.
Data type with one of the two built-in values, True or False. Boolean objects that are equal to True
are truthy (true), and those equal to False are falsy (false). But non-Boolean objects can be
evaluated in a Boolean context as well and determined to be true or false. It is denoted by the class
bool.
Note – True and False with capital ‘T’ and ‘F’ are valid Booleans otherwise python will throw an
error.
Example:
#Python program to demonstrate Boolean type
print(type(True))
print(type(False))
print(type(true))
Output:
INTRODUCTION TO PYTHON PROGRAMMING
Set Data Type in Python
In Python, a Set is an unordered collection of data types that is iterable, mutable and has no
duplicate elements. The order of elements in a set is undefined though it may consist of various
elements.
Create a Set in Python
Sets can be created by using the built-in set() function with an iterable object or a sequence by
placing the sequence inside curly braces, separated by a ‘comma’. The type of elements in a set
need not be the same, various mixed-up data type values can also be passed to the set.
Python Operators
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x**y
= x=5 x=5
+= x+=3 x=x +3
-= x-=3 x=x – 3
*= x*=3 x=x * 3
/= x/=3 x=x /3
%= x%=3 x=x% 3
|= x|=3 x=x |3
^= x^=3 x=x ^3
== Equal x==y
and Returns True if both statements are true x<5 and x<10
not Reverse the result, returns False if the result Not (x<5 and x<10)
is true
Python Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location:
Is not Returns True if both variables are not the same X is not y
object
<< Zero fill Shift left by pushing zeros in from the right x<<2
left shift and let the leftmost bits fall off
>> Signed Shift right by pushing copies of the left most bit x>>2
right shift in from the left, and let the rightmost bits fall
off
Operator Precedence
Example
A parenthesis has the highest precedence, meaning that expressions inside parenthesis
must be evaluated first:
Example
Multiplication * has higher precedence than addition +, and therefore multiplications are
evaluated before additions:
print(100 + 5 *3)
The precedence order is described in the table below, starting with the highest precedence at the
top:
Operator Description
() Parentheses
INTRODUCTION TO PYTHON PROGRAMMING
** Exponentiation
^ Bitwise XOR
| Bitwise OR
== != > >= < <= is is not in not Comparisons, identity, and membership
in operators
and AND
or OR
If two operators have the same precedence, the expression is evaluated from left to right.
Example
Addition+ and subtraction- has the same precedence, and therefore we evaluate the
expression from left to right:
print(5 + 4 – 7 + 3)
INTRODUCTION TO PYTHON PROGRAMMING
Python Indentation
Python indentation refers to adding white space before a statement to a particular block of
code. In another word, all the statements with the same space to the right belong to the same
code block.
Where in other programming languages the indentation in code is for readability only, the
indentation in Python is very important.
Example - 1
If 5>2:
print("Five is greater than two!")
Output:
Example - 2
Syntax Error:
If 5>2:
print("Five is greater than two!")
INTRODUCTION TO PYTHON PROGRAMMING
Output:
Python Comments
Comments in Python are the lines in the code that are ignored by the interpreter during the
execution of the program. Comments enhance the readability of the code and help the
programmers to understand the code very carefully.
Multiline Comments
Comments in Python
In the example, it can be seen that comments are ignored by the interpreter during the execution of
the program.
#sample comment
name="PESIAMS"
print(name)
Output:
PESIAMS
INTRODUCTION TO PYTHON PROGRAMMING
Types of Comments in Python
Python single-line comment starts with the hashtag symbol (#) with no white spaces and lasts
till the end of the line. If the comment exceeds one line, then put a hashtag on the
Next line and continue the comment. Python’s single-line comments are proved useful for
supplying short explanations for variables, function declarations, and expressions. See the
following code snippet demonstrating single line comment:
Example:
print("PESIAMS")
Output
PESIAMS
Python does not provide the option for multiline comments. However, there are different ways
through which we can write multiline comments.
We can multiple hashtags (#) to write multiline comments in Python. Each and every line will
be considered as a single-line comment.
Python3
# Python program to demonstrate
# multiline comments
print("Multiline comments")
Output:
Multiline comment
INTRODUCTION TO PYTHON PROGRAMMING
Built-in Function
Sometimes a developer might want to take user input at some point in the program. To do this
Python provides an input( ) function.
Syntax:
input('prompt')
Where prompt is an optional string that is displayed on the string at the time of taking input.
# Output
print("Hello,"+name)
print(type(name))
Output:
Hello, GFG
<Class 'str'>
Note: Python takes all the input as a string input by default. To convert it to any other data
type we have to convert the input explicitly. For example, to convert the input to int or float
we have to use the int( ) and float( ) method respectively.
INTRODUCTION TO PYTHON PROGRAMMING
add= num+ 1
# Output
print(add)
Output:
Enter a number: 25
26
We can take multiple inputs of the same data type at a time in python, using map( ) method
in python.
print(a, b, c)
Output:
How take inputs for the Sequence Data Types like List, Set, Tuple, etc.
In the case of List and Set the input can be taken from the user in two ways.
Take the elements of the List/Set one by one and use the append() method in the case of List,
and add() method in the case of a Set, to add the elements to the List / Set.
List = list()
Set = set()
List.append(int(input()))
Set.add(int(input()))
print(List)
print(Set)
Output:
9013
291
[9, 0, 1, 3]
{9, 2, 1}
print(List)
print(Set)
Output:
[3, 4, 8, 9, 0, 11]
We know that tuples are immutable; there are no methods available to add elements to tuples.
To add a new element to a tuple, first type cast the tuple to the list, later appends the element
to the list, and again type cast list back to a tuple.
INTRODUCTION TO PYTHON PROGRAMMING
T = (2,3,4,5,6)
print(T)
L=list(T)
T = tuple(L)
print(T)
Output:
(2,3, 4, 5, 6)
(2, 3, 4, 5, 6, 35)
Python provides the print() function to display output to the standard output devices.
Parameters:
value(s): Any value, and as many as you like. Will be converted to string before printed
sep=’separator’: (Optional) Specify how to separate the objects, if there is more than
one.Default :’ ‘
end=’end’: (Optional) Specify what to print at the end.Default :‘\n’
INTRODUCTION TO PYTHON PROGRAMMING
print() method
print("GFG")
print('G','F','G')
Output:
GFG
GFG
In the above example, we can see that in the case of the 2nd print statement there is a space
between every letter and the print statement always add a new line character at the end of the
string. This is because after every character the Sep parameter is printed and at the end of the
string the end parameter is printed. Let’s try to change this sep and end parameter.
Example: Python Print output with custom sep and end parameter
print("GFG", end="@")
Output:
GFG@G#F#G
Formatting Output
Formatting output in Python can be done in many ways. Let’s discuss them below
We can use formatted string literals, by starting a string with f or F before opening
quotation marks or triple quotation marks. In this string, we can write Python expressions
between { and } that can refer to a variable or any literal value.
#Declaring a variable
name = "Gfg"
# Output
Output:
2. Using format()
We can also use format() function to format our output to make it look presentable. The curly
braces { } work as placeholders. We can specify the order in which variables occur in the
output.
#Initializing variables
a=20
b=10
sum = a + b
INTRODUCTION TO PYTHON PROGRAMMING
# subtraction
sub = a- b
# Output
value_b = b,
sub_value
=sub))
Output:
3. Using % Operator
We can use ‘%’ operator. % values are replaced with zero or more value of elements. The
formatting using % is similar to that of ‘printf’ in the C programming language.
%d – integer
%f – float
%s – string
%x – hexadecimal
%o – octal
INTRODUCTION TO PYTHON PROGRAMMING
Example:
num=int(input("Enter a value:"))
add = num + 5
# Output
Output:
Enter a value: 50
The sum is 55
Python defines type conversion functions to directly convert one data type to another which is
useful in day-to-day and competitive programming. This article is aimed at providing
information about certain conversion functions.
In Implicit type conversion of data types in Python; the Python interpreter automatically
converts one data type to another without any user involvement. To get a clearer view of the
topic see the below examples.
INTRODUCTION TO PYTHON PROGRAMMING
Example:
x =10
print("x is of type:", type(x))
y = 10.6
print("y is of type:", type(y))
z=x+y
print(z)
print("z is of type:", type(z))
Output:
X is of type: <class 'int'>
Y is of type: <class 'float'>
20.6
Z is of type: <class 'float'>
As we can see the data type of ‘z’ got automatically changed to the “float” type while one
variable x is of integer type while the other variable y is of float type. The reason for the float
value not being converted into an integer instead is due to type promotion that allows
performing operations by converting data into a wider-sized data type without any loss of
information. This is a simple case of implicit type conversion in python.
In Explicit Type Conversion in Python, the data type is manually changed by the user as
per their requirement. With explicit type conversion, there is a risk of data loss since we are
forcing an expression to be changed in some specific data type. Various forms of
INTRODUCTION TO PYTHON PROGRAMMING
1. int(a, base): This function converts any data type to integer. ‘Base’ specifies the base in
which string is if the data type is a string.
2. float(): This function is used to convert any data type to a floating-point number.
#initializing string
s = "10010"
Output:
After converting to integer base 2: 18
After converting to float: 10010.0
3. ord(): This function is used to convert a character to integer.
4. hex():This function is to convert integer to hexadecimal string.
5. oct():This function is to convert integer to octal string.
#initializing integer
s = '4'
#initializing string
s = 'geeks'
Output:
After converting string to tuple: ('g', 'e', 'e', 'k', 's')
After converting string to set: {'k', 'e', 's', 'g'}
After converting string to list: ['g', 'e', 'e', 'k', 's']
9. dict() : This function is used to convert a tuple of order (key, value) into a
dictionary.
10. str(): Used to convert integer into a string.
11. complex(real, imag): This function converts real numbers to
complex(real, imag) number.
#initializing integers
a=1
b=2
#initializing tuple
tup=(('a', 1), ('f', 2), ('g', 3))
Output:
After converting integer to complex number: (1+2j)
After converting integer to string: 1
After converting tuple to dictionary: {'a':1,'f':2,'g':3}
12. chr(number): This function converts number to its corresponding ASCII
character.
INTRODUCTION TO PYTHON PROGRAMMING
print(a)
print(b)
Output:
L
M
Python Libraries
In the programming world, a library is a collection of pre compiled codes that can be used
later on in a program for some specific well-defined operations. Other than pre- compiled codes,
a library may contain documentation, configuration data, message templates, classes, and values,
etc.
A Python library is a collection of related modules. It contains bundles of code that can be
used repeatedly in different programs. It makes Python Programming simpler and convenient for
the programmer. As we don’t need to write the same code again and again for different
programs. Python libraries play a very vital role in fields of Machine Learning, Data Science,
Data Visualization, etc.
The Python Standard Library contains the exact syntax, semantics, and tokens of Python. It
contains built-in modules that provide access to basic system functionality like I/O and some
other core modules. Most of the Python Libraries are written in the C programming language.
The Python standard library consists of more than 200 core modules. All these work together to
make Python a high-level programming language. Python Standard Library plays a very
important role. Without it, the programmers can’t have access to the functionalities of Python.
But other than this, there are several other libraries in Python
INTRODUCTION TO PYTHON PROGRAMMING
That makes a programmer’s life easier. Let’s have a look at some of the commonly used
libraries:
1. TensorFlow: This library was developed by Google in collaboration with the Brain
Team. It is an open-source library used for high-level computations. It is also used in
machine learning and deep learning algorithms. It contains a large number of tensor
operations. Researchers also use this Python library to solve complex computations in
Mathematics and Physics.
2. Matplotlib: This library is responsible for plotting numerical data. And that’s why it is
used in data analysis. It is also an open-source library and plots high-defined figures like
pie charts, histograms, scatter plots, graphs, etc.
3. Pandas: Pandas are an important library for data scientists. It is an open-source machine
learning library that provides flexible high-level data structures and a variety of analysis
tools. It eases data analysis, data manipulation, and cleaning of data. Pandas support
operations like Sorting, Re-indexing, Iteration, Concatenation, Conversion of data,
Visualizations, Aggregations, etc.
4. Numpy: The name “Numpy” stands for “Numerical Python”. It is the commonly used
library. It is a popular machine learning library that supports large matrices and multi-
dimensional data. It consists of in-built mathematical functions for easy computations.
Even libraries like TensorFlow use Numpy internally to perform several operations on
tensors. Array Interface is one of the key features of this library.
5. SciPy: The name “SciPy” stands for “Scientific Python”. It is an open-source library used
for high-level scientific computations. This library is built over an extension of Numpy. It
works with Numpy to handle complex computations. While Numpy allows sorting and
indexing of array data, the numerical data code is stored in SciPy. It is also widely used
by application developers and engineers.
INTRODUCTION TO PYTHON PROGRAMMING
6. Scrapy: It is an open-source library that is used for extracting data from websites. It
provides very fast web crawling and high-level screen scraping. It can also be used for
data mining and automated testing of data.
8. PyGame: This library provides an easy interface to the Standard Direct media Library
(SDL) platform-independent graphics, audio, and input libraries. It is used for developing
video games using computer graphics and audio libraries along with Python
programming language.
9. PyTorch: PyTorch is the largest machine learning library that optimizes tensor
computations. It has rich APIs to perform tensor computations with strong GPU
acceleration. It also helps to solve application issues related to neural networks.
10. PyBrain: The name “PyBrain” stands for Python Based Reinforcement Learning,
Artificial Intelligence, and Neural Networks library. It is an open-source library built for
beginners in the field of Machine Learning. It provides fast and easy-to-use algorithms
for machine learning tasks. It is so flexible and easily understandable and that’s why is
really helpful for developers that are new in research fields.
There are many more libraries in Python. We can use a suitable library for our purposes. Hence,
Python libraries play a very crucial role and are very helpful to the developers.
As we write large-size programs in Python, we want to maintain the code’s modularity. For the
easy maintenance of the code, we split the code into different parts and we can use that code later
ever we need it. In Python, modules play that part. Instead of using the same code in different
programs and making the code complex, we define mostly used functions in modules and we can
just simply import the min a program wherever there is a
INTRODUCTION TO PYTHON PROGRAMMING
requirement. We don’t need to write that code but still, we can use its functionality by importing
its module. Multiple interrelated modules are stored in a library. And whenever we need to use a
module, we import it from its library. In Python, it’s a very simple job to do due to its easy
syntax. We just need to use import.
import math
A=16
print(math.sqrt(A))
Output:
4.0
Here in the above code, we imported the math library and used one of its methods i.e. sqrt
(square root) without writing the actual code to calculate the square root of a number. That’s how
a library makes the programmers’ job easier. But here we needed only the sqrt method of math
library, but we imported the whole library. Instead of this, we can also import specific items from
a library module.
As in the above code, we imported a complete library to use one of its methods. But we could
have just imported “sqrt” from the math library. Python allows us to import specific items from a
library.
A=16
B =3.14
print(sqrt(A))
print(sin(B))
Output:
4.0
0.0015926529164868282
In the above code, we can see that we imported only “sqrt” and “sin” methods from the math
library.
INTRODUCTION TO PYTHON PROGRAMMING
Python String
Python string is the collection of the characters surrounded by single quotes, double quotes,
or triple quotes. The computer does not understand the characters; internally, it stores
manipulated character as the combination of the 0's and 1's.
Each character is encoded in the ASCII or Unicode character. So, we can say that Python strings
are also called the collection of Unicode characters.
In Python, strings can be created by enclosing the character or the sequence of characters in the
quotes. Python allows us to use single quotes, double quotes, or triple quotes to create the string.
Syntax:
Here, if we check the type of the variable str using a Python script
In Python, strings are treated as the sequence of characters, which means that Python doesn't
support the character data-type; instead, a single character written as 'p' is treated as the string of
length 1.
We can create a string by enclosing the characters in single-quotes or double- quotes. Python also
provides triple-quotes to represent the string, but it is generally used for multiline string or doc
strings.
print(str1)
str2="Hello Python"
print(str2)
the multiline or
doc string'''
print(str3)
Output:
Hello Python
Hello Python
doc string
Like other languages, the indexing of the Python strings starts from 0. For example, the string
"HELLO" is indexed as given in the below figure.
INTRODUCTION TO PYTHON PROGRAMMING
str = "HELLO"
print(str[0])
print(str[1])
print(str[2])
print(str[3])
print(str[4])
#It returns the Index Error because 6th index doesn't exist
print(str[6])
Output:
As shown in Python, the slice operator [ ] is used to access the individual characters of the string.
However, we can use the: (colon) operator in Python to access the substring from the given
string. Consider the following example.
INTRODUCTION TO PYTHON PROGRAMMING
Here, we must notice that the upper range given in the slice operator is always exclusive i.e., if
str = 'HELLO' is given, then str[1:3] will always include str[1] = 'E', str[2] = 'L' and nothing else.
#Given String
str= "PYTHON"
#Start Oth index to end
print(str[0:])
Output:
We can do the negative slicing in the string; it starts from the right most character, which is
indicated as -1. The second rightmost index indicates -2, and so on. Consider the following
image.
str = 'PYTHON'
print(str[-1])
print(str[-3])
print(str[-2:])
print(str[-4:-1])
print(str[-7:-2])
print(str[::-1])
print(str[-12])
INTRODUCTION TO PYTHON PROGRAMMING
Output:
Parameters:
print(s)
print(s)
INTRODUCTION TO PYTHON PROGRAMMING
Output:
PESIAMS
# strings
num=100
s = str(num)
print(s, type(s))
num = 100.1
s = str(num)
print(s, type(s))
Output:
Operations on Strings
String Concatenation
String concatenation means add strings together.
Example - 1:
x="Python is"
y="awesome"
z=x+y
print(z)
Output:
Python is awesome
a="Hello"
b="World"
INTRODUCTION TO PYTHON PROGRAMMING
c=a+b
print(c)
Output:
Hello World
String Comparison
0th index till the end of the string. It then returns a Boolean value according to the operator used.
Example:
print("Iams" =="Iams")
print("Iams" < "iams")
print("Iams" > "iams")
print("Iams" != "Iams")
Output:
True
True
False
False
Example:
str1="Iams"
str2="Iams"
str3 = str1
print(str1 is str4)
Output:
ID of str1 =0xf98860
ID of str2 =0xf98860
ID of str3 =0xf98860
True
True
True
The object ID of the strings may vary on different machines. The object IDs of str1, str2 and str3
were the same therefore they the result is True in all the cases. After the object id of str1 is changed,
the result of str1 and str2 will be false. Even after creating str4 with the same contents as in the new
str1, the answer will be false as their object IDs are different. Vice-versa will happen with is not.
Slicing is a mechanism used to select a range of items from sequence. You can retrieve a slice (sub string)
of a string with a slice operation. The slicing operation is used by specifying the name of the sequence
followed by an optional pair of numbers separated by a colon enclosed within [ ] (square brackets).
The slice operator [ ] is used to access the individual characters of the string. However,
you can use the:(colon) operator in Python to access the substring.
Str P O R T I O N
Positive index 0 1 2 3 4 5 6
Negative index -7 -6 -5 -4 -3 -2 -1
INTRODUCTION TO PYTHON PROGRAMMING
#Slicing on a string
str= "PORTION"
print ('characters 1 to 3 is', str[1:3])
In Python, we can use the function split ( ) to split a string and join( ) to join a string. The split ( )
method in Python split a string into a list of strings after breaking the given string by the
specified separator. Python String join ( ) method is a string method and returns a string in which
the elements of the sequence have been joined by the str separator.
# input string
s='Python is dynamic interpreted high level language'
#print the string after split method
print(s.split(""))
#print the string after join method
print("-".join(s.split()))
Output:
['Python', 'is', 'dynamic', 'interpreted', 'high level', 'language']
INTRODUCTION TO PYTHON PROGRAMMING
Python-is-dynamic-interpreted-high level-language
String Traversing:
Traversing a string means accessing all the elements of the string one after the other by
using subscript or index. The string can be traversed character-by-character using for loop or
while.
#String traversal using for loop
str="PYTHON"
for i in str:
print(i)
Output:
String formatting
String formatting is the process of infusing things in the string dynamically and presenting the
string.
There are five different ways to perform string formatting in Python:
Formatting with % Operator.
Formatting with format( ) string method.
Formatting with string literals, called f-strings.
Formatting with String Template Class
Formatting with center( )string method.
Method 1: Formatting string using % Operator
It is the oldest method of string formatting. Here we use the modulo % operator. The modulo
% is also known as the “string-formatting operator”.
Output:
x = 'interpreted'
print("Python is %s and %s language" %('dynamic' ,x))
Output:
Python is dynamic and interpreted language
NOTE:
‘%s’ is used to inject strings similarly ‘%d’ for integers, ‘%f’ for floating-point
values, ‘%b’ for binary format.
Output:
variable=12
print(string)
Output:
Variable as integer = 12
Variable as float=12.000000
format( ) method was introduced with Python3 for handling complex string formatting more
efficiently. Formatters work by putting in one or more replacement fields and placeholders
defined by a pair of curly braces {} into a string and calling the str.format(). The value we
wish to put into the placeholders and concatenate with the string passed as parameters into the
format function.
Output:
We all are equal.
The format() method has many advantages over the place holder method:
We can insert object by using index-based position:
Output:
Read the directions.
Output:
a: 1, b: Two, c: 12.3
INTRODUCTION TO PYTHON PROGRAMMING
In Python 3.6 introduced a new string formatting mechanism known as Literal String
Interpolation or more commonly as F-strings (because of the leading f character preceding the
string literal). The idea behind f-strings is to make string interpolation simpler.
To create an f-string, prefix the string with the letter “f”. The string itself can be formatted in
much the same way that you would with str.format(). F-strings provide a concise and convenient
way to embed python expressions inside string literals for formatting.
Output:
b=10
Output:
He said his age is 30.
Example: Float Precision using F-strings
num=3.14159
allows it to be followed by more alpha numeric letters with no intervening spaces. Writing
$$creates a single escaped$:
Example: Formatting string using Template Class
#Python program to demonstrate
# string interpolation
n1 = 'Hello'
n2 ='Python language'
# template string.
print(n.substitute(n3=n1, n4=n2))
Output:
Hello! This is Python language.
Output:
INTRODUCTION TO PYTHON PROGRAMMING
To insert characters that are illegal in a string, use an escape character. An escape character is a
backslash \ followed by the character you want to insert.
Example: The escape character allows you to use double quotes when you normally would not be
allowed:
txt="Python is\"DYNAMIC\"Language."
print(txt)
Output:
Python is "DYNAMIC" Language.
Escape Use
character
\b Gives a backspace.
The below functions are used to change the case of the strings.
print(text.swapcase())
Output:
INTRODUCTION TO PYTHON PROGRAMMING
Function Name
Description
capitalize( ) Converts the first character of the string to a capital (uppercase) letter
Specifies the amount of space to be substituted with the “\t” symbol in the
expandtabs( )
string
Function Name
Description
isnumeric( ) Returns “True” if all characters in the string are numeric characters
Returns “True” if all characters in the string are printable or the string is
isprintable( )
empty
isspace( ) Returns “True” if all characters in the string are white space characters
ljust( ) Leftalignsthestringaccordingtothewidthspecified
Function Name
Description
Rindex( ) Returns the highest index of the substring inside the string
rsplit( ) Split the string from the right by the specified separator
strip( ) Returns the string with both leading and trailing characters
Function Name
Description
Returns a copy of the string with ‘0’ characters padded to the left side of
zfill( )
the string