0% found this document useful (0 votes)
6 views69 pages

1. Introduction to Python Programming

The document provides an introduction to Python programming, highlighting its features such as ease of learning, versatility, and support for multiple programming paradigms. It covers Python's applications in various domains including web development, scientific computing, and business applications, as well as its installation process and popular IDEs. Additionally, it outlines the history and evolution of Python versions, emphasizing its growth and adaptability in the software development landscape.

Uploaded by

RANJITH. T.E.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views69 pages

1. Introduction to Python Programming

The document provides an introduction to Python programming, highlighting its features such as ease of learning, versatility, and support for multiple programming paradigms. It covers Python's applications in various domains including web development, scientific computing, and business applications, as well as its installation process and popular IDEs. Additionally, it outlines the history and evolution of Python versions, emphasizing its growth and adaptability in the software development landscape.

Uploaded by

RANJITH. T.E.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

INTRODUCTION TO PYTHON PROGRAMMING

Introduction to Python Programming


Python
Python is a general purpose, dynamic, high-level, and interpreted programming language. It
supports Object Oriented programming approach to develop applications. It is simple and easy to
learn and provides lots of high-level data structures.

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 supports multiple programming pattern, including object-oriented, imperative, and


functional or procedural programming styles.

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.

1. Easy to Learn and Use

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.

5. Free and Open Source

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.

8. Large Standard Library

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.

9. GUI Programming Support

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.

12. Dynamic Memory Allocation

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.

Here, we are specifying application areas where Python can be applied.


INTRODUCTION TO PYTHON PROGRAMMING

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:

o Django and Pyramid framework(Use for heavy applications)

o Flask and Bottle(Micro-framework)

o Plone and Django CMS(Advance Content management)

2. Desktop GUI Applications

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 Kivy(used for writing multi touch applications )

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 SCons is used to build control.


INTRODUCTION TO PYTHON PROGRAMMING

o Buildbot and Apache Gumps are used for automated continuous compilation and testing.

o Round or Trac for bug tracking and project management.

5. Scientific and Numeric

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.

7. Audio or Video-based Applications

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.

10. Image Processing Application

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

Java vs Python Program

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

public class HelloWorld{


public static void main(String[] args){
INTRODUCTION TO PYTHON PROGRAMMING

//Prints "Hello, World" to the terminal window.


System.out.println("Hello World");
}
}

Python Program

On the other hand, we can do this using one statement in Python.

print("HelloWorld")

Both programs will print the same result, but it takes only one statement without using a semicolon
or curly braces in Python.

Python Basic Syntax

There is no use of curly braces or semicolon in Python programming language. It is English-like


language. But Python uses the indentation to define a block of code. Indentation is nothing but
adding whitespace before the statement when it is needed. For example -

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.

Python History and Versions


o Python laid its foundation in the late 1980s.
o The implementation of Python was started in December 1989 by Guido Van Rossum at
CWI in Netherland.
INTRODUCTION TO PYTHON PROGRAMMING

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

Why the Name Python?

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 Version List

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.

A list of Python versions with its released date is given below.


INTRODUCTION TO PYTHON PROGRAMMING

Python Version Released Date

Python 1.0 January1994

Python 1.5 December 31,1997

Python 1.6 September 5,2000

Python 2.0 October16,2000

Python 2.1 April17,2001

Python 2.2 December21,2001


Python 2.3 July29,2003
Python 2.4 November30,2004

Python 2.5 September19,2006

Python 2.6 October1,2008

Python 2.7 July3,2010

Python 3.0 December3,2008

Python 3.1 June27,2009

Python 3.2 February20,2011

Python 3.3 September29,2012

Python 3.4 March16,2014

Python 3.5 September13,2015

Python 3.6 December23,2016

Python 3.7 June27,2018

Python 3.8 October14,2019


INTRODUCTION TO PYTHON PROGRAMMING

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.

Installing Python on Windows takes a series of few easy steps.

Step 1 – Select Version of Python to Install

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.

Step2 – Download Python Executable Installer

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).

The download size is less than 30MB.


INTRODUCTION TO PYTHON PROGRAMMING

Step3 – Run Executable Installer

We downloaded the Python 3.9.1 Windows64 bit installer.

Run the installer. Make sure to select both the checkboxes at the bottom and then click Install New.

On clicking the Install Now, the installation process starts.

The installation process will take few minutes to complete and once the installation is successful,
the following screen is displayed.
INTRODUCTION TO PYTHON PROGRAMMING

Step 4 − Verify Python is installed on Windows

To ensure if Python is successfully installed on your system. Follow the given steps−

 Open the command prompt.

 Type ‘python’ and press enter.

 The version of the python which you have installed will be displayed if the python is
successfully installed on your windows.

Step5 – Verify Pip was installed

Pip is a powerful package management system for Python software packages. Thus, make sure that
you have it installed.

To verify if pip was installed, follow the given steps−

 Open the command prompt.

 Enter pip –V to check if pip was installed.

 The following output appears if pip is installed successfully.

We have successfully installed python and pip on our Windows system.


INTRODUCTION TO PYTHON PROGRAMMING

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.

4. Jupyter Notebook/ JupyterLab: Jupyter Notebook and JupyterLab are web-based


environments widely used in data science and research for creating interactive documents that
combine code, visualizations, and explanatory text.

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.

 It can be a combination of A-Z, a-z, 0-9, or underscore.


 It should start with an alphabet character or an underscore(_).
 It should not contain any special character other than an underscore(_).

Examples of Python Identifiers


Valid identifiers:
 var1
 _var1
 _1_var
 var_1
INTRODUCTION TO PYTHON PROGRAMMING

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.

Data types in Python


A variable can hold different types of values. For example, a person's name must be stored as a
string whereas its id must be stored as an integer.
INTRODUCTION TO PYTHON PROGRAMMING

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

What is Python type() Function?


To define the values of various data types and check their data types we use the type()
function.

Numeric Data Type in Python


The numeric data type in Python represents the data that has a numeric value. A numeric
value can be an integer, a floating number, or even a complex number. These values are
defined as Python int, Python float, and Python complex classes in Python.
 Integers–This value is represented by int class. It contains positive or negative whole
numbers (without fractions or decimals). In Python, there is no limit to how long an integer
value can be.
 Float–This value is represented by the float class. It is a real number with a floating- point
representation. It is specified by a decimal point. Optionally, the character e or E followed
by a positive or negative integer may be appended to specify scientific notation.
 Complex Numbers – Complex number is represented by a complex class. It is
specified as (real part) + (imaginary part)j. For example – 2+3j
INTRODUCTION TO PYTHON PROGRAMMING

Note – type() function is used to determine the type of data type.


Example:
#Python program to demonstrate numeric value
a=5
print("Type of a:",type(a))

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'>

Type of b:<class 'float'>

Type of c:<class 'complex'>

Sequence Data Type in Python


The sequence Data Type in Python is the ordered collection of similar or different data types.
Sequences allow storing of multiple values in an organized and efficient fashion. There are several
sequence types in Python –

 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.

List Data Type


Lists are just like arrays, declared in other language which is an ordered collection of data.
It is very flexible as the items in a list do not need to be of the same type.
INTRODUCTION TO PYTHON PROGRAMMING
Note: Lists in Python can be created by just placing the sequence inside the square brackets[].

Tuple Data Type


Just like a list, a tuple is also an ordered collection of Python objects. The only difference
between a tuple and a list is that tuples are immutable i.e. tuples cannot be modified after it is
created. It is represented by a tuple class.
Creating a Tuple
In Python tuples are created by placing a sequence of values separated by a ‘comma’ with or
without the use of parentheses for grouping the data sequence. Tuples can contain any number of
elements and of any data type (like strings, integers, lists, etc.). Note: Tuples can also be created
with a single element, but it is a bit tricky. Having one element in the parentheses is not sufficient;
there must be a trailing ‘comma’ to make it a tuple.

Boolean Data Type in Python

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.

Dictionary Data Type in Python


A dictionary in Python is an unordered collection of data values, used to store data values
like a map, unlike other Data Types that hold only a single value as an element, a Dictionary holds a
key: value pair. Key-value is provided in the dictionary to make it more Optimized. Each key-value
pair in a Dictionary is separated by a colon(:), whereas each key is separated by a ‘comma’.
Create a Dictionary
In Python, a Dictionary can be created by placing a sequence of elements within curly {} braces,
separated by ‘comma’. Values in a dictionary can be of any data type and can be duplicated,
whereas keys can’t be repeated and must be immutable. The dictionary can also be created by the
built-in function dict(). An empty dictionary can be created by just placing it in curly braces { }.
Note – Dictionary keys are case sensitive, the same name but different cases of Key will be treated
distinctly.
INTRODUCTION TO PYTHON PROGRAMMING

Python Operators

Operators are used to perform operations on variables and values. Python

divides the operators in the following groups:

 Arithmetic operators

 Assignment operators

 Comparison operators

 Logical operators

 Identity operators

 Membership operators

 Bitwise operators

Python Arithmetic Operators


Arithmetic operators are used with numeric values to perform common mathematical operations:

Operator Name Example

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

** Exponentiation x**y

// Floor division x//y


INTRODUCTION TO PYTHON PROGRAMMING
Python Assignment Operators

Assignment operators are used to assign values to variables:

Operator Example Same As

= 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

&= 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


INTRODUCTION TO PYTHON PROGRAMMING

Python Comparison Operators

Comparison operators are used to compare two values:

Operator Name Example

== Equal x==y

!= Not equal x!=y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x>=y

<= Less than or equal to x<=y

Python Logical Operators

Logical operators are used to combine conditional statements:

Operator Description Example

and Returns True if both statements are true x<5 and x<10

or Returns True if one of the statements is true x<5 or x <4


INTRODUCTION TO PYTHON PROGRAMMING

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:

Operator Description Example

is Returns True if both variables are the same X is y


object

Is not Returns True if both variables are not the same X is not y
object

Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:

Operator Description Example

in Returns True if a sequence with the specified x in y


value is present in the object

not in Returns True if a sequence with the specified x not in y


value is not present in the object

Python Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

Operator Name Description Example

& AND Sets each bit to 1 if both bits are 1 X&y


INTRODUCTION TO PYTHON PROGRAMMING

| OR Sets each bit to 1 if one of two bits is 1 X|y

^ XOR Sets each bit to 1 if only one of two bits is 1 X^y

~ NOT Inverts all the bits ~x

<< 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

Operator precedence describes the order in which operations are performed.

Example

A parenthesis has the highest precedence, meaning that expressions inside parenthesis
must be evaluated first:

print ((6 + 3) - ( 6 + 3))

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

+x –x ~x Unary plus, unary minus, and bitwise NOT

* / // % Multiplication, division, floor division, and


modulus

+- Addition and subtraction

<< >> Bitwise left and right shifts

& Bitwise AND

^ Bitwise XOR

| Bitwise OR

== != > >= < <= is is not in not Comparisons, identity, and membership
in operators

not Logical NOT

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.

Python uses indentation to indicate a block of code.

Example - 1

If 5>2:
print("Five is greater than two!")

Output:

Five is greater than two!

Example - 2

Syntax Error:

If 5>2:
print("Five is greater than two!")
INTRODUCTION TO PYTHON PROGRAMMING

Output:

File "demo_indentation_test.py", line2


print("Five is greater than two!")
^
Indentation Error: expected an indented block

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.

There are two types of comments in Python:

 Single line Comments

 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

Single-Line 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!” To console

print("PESIAMS")

Output

PESIAMS

Multi-Line Comments in Python

Python does not provide the option for multiline comments. However, there are different ways
through which we can write multiline comments.

Multiline comments using multiple hashtags(#)

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

Console Input in Python

How to Take Input from User in Python

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.

Example1: Python get user input with a message

#Taking input from the user

name=input("Enter your name:")

# Output

print("Hello,"+name)

print(type(name))

Output:

Enter your name: GFG

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

Example 2: Integer input in Python

#Taking input from the user as integer

num = int(input("Enter a number: "))

add= num+ 1

# Output

print(add)

Output:

Enter a number: 25

26

How to take Multiple Inputs in Python:

We can take multiple inputs of the same data type at a time in python, using map( ) method

in python.

a, b, c = map(int, input("Enter the Numbers : ").split())

print("The Numbers are : ",end = "")

print(a, b, c)

Output:

Enter the Numbers:2 3 4

The Number sare:2 3 4


INTRODUCTION TO PYTHON PROGRAMMING

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.

1. Taking List/Set elements one by one by using the append()/add() methods.

2. Using map() and list()/set() methods.

Taking List/Set elements one by one

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()

l = int(input("Enter the size of the List : "))

s = int(input("Enter the size of the Set: "))

print("Enter the List elements : ")

for i in range(0, l):

List.append(int(input()))

print("Enter the Set elements:")

for i in range(0, s):

Set.add(int(input()))

print(List)

print(Set)

Output:

Enter the size of the List: 4

Enter the size of the Set: 3


INTRODUCTION TO PYTHON PROGRAMMING
Enter the List elements:

9013

Enter the Set elements:

291

[9, 0, 1, 3]

{9, 2, 1}

Using map() and list()/set()Methods

List = list(map(int, input("Enter List elements : ").split()))

Set = set(map(int, input("Enter the Set elements :").split()))

print(List)

print(Set)

Output:

Enter List elements: 3 4 8 9 0 11

Enter the Set elements: 34 230 234 88 123

[3, 4, 8, 9, 0, 11]

{34, 230, 234, 88, 123}

Taking Input for Tuple

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("Tuple before adding new element")

print(T)

L=list(T)

L.append(int(input("Enter the new element :")))

T = tuple(L)

print("Tuple After adding the new element")

print(T)

Output:

Tuple before adding new element

(2,3, 4, 5, 6)

Enter the new element: 35

Tuple After adding the new element

(2, 3, 4, 5, 6, 35)

Console Output in Python

How to Display Output in Python

Python provides the print() function to display output to the standard output devices.

Syntax: print(value(s), sep = ‘ ‘, end=‘\n’, file = file, flush = flush)

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

file: (Optional) An object with a write method.Default : sys.stdout


flush: (Optional) A Boolean, specifying if the output is flushed (True) or buffered (False). Default:
False

Returns: It returns output to the screen.

Example: Python Print Output

# Python program to demonstrate #

print() method

print("GFG")

#code for disabling the softspace feature

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() method with sep & end

print("GFG", end="@")

#code for disabling the softspace feature

print('G', 'F', 'G', sep="#")


INTRODUCTION TO PYTHON PROGRAMMING

Output:

GFG@G#F#G

Formatting Output

Formatting output in Python can be done in many ways. Let’s discuss them below

1. Using formatted string literals

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.

Example: Python String formatting using F string

#Declaring a variable

name = "Gfg"

# Output

print(f'Hello {name}! How are you?')

Output:

Hello Gfg! How are you?

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.

Example: Python string formatting using format() function

#Initializing variables
a=20
b=10

sum = a + b
INTRODUCTION TO PYTHON PROGRAMMING

# subtraction

sub = a- b

# Output

print('The value of a is {} and b is {}'.format(a, b))

print('{2} is the sum of {0} and {1}'.format(a, b, sum))

print('{sub_value} is the subtraction of {value_a} and {value_b}'.format(value_a=a,

value_b = b,

sub_value

=sub))

Output:

The value of a is 20 and b is 10

30 is the sum of 20 and 10

10 is the subtraction of 20 and 10

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:

#Taking input from the user

num=int(input("Enter a value:"))

add = num + 5

# Output

print("The sum is %d" %add)

Output:

Enter a value: 50

The sum is 55

Type Conversion in Python

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.

There are two types of Type Conversion in Python:

1. Implicit Type Conversion


2. Explicit Type Conversion

Implicit Type Conversion

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.

Explicit Type Conversion

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

Explicit type conversions are explained below:

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.

# Python code to demonstrate Type conversion

# using int(), float()

#initializing string
s = "10010"

#printing string converting to int base 2


c = int(s,2)
print ("After converting to integer base 2:", end="")
print (c)

#printing string converting to float


e = float(s)
print ("After converting to float:", end="")
print (e)

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.

# Python code to demonstrate Type conversion

# using ord(), hex(), oct()


INTRODUCTION TO PYTHON PROGRAMMING

#initializing integer
s = '4'

#printing character converting to integer


c = ord(s)
print ("After converting character to integer:", end="")
print (c)

#printing integer converting to hexadecimal string


c = hex(56)
print ("After converting 56 to hexadecimal string:", end="")
print (c)

#printing integer converting to octal string


c = oct(56)
print ("After converting 56 to octal string:", end="")
print (c)
Output:
After converting character to integer: 52
After converting 56to hexadecimal string: 0x38

After converting 56 to octal string: 0o70


6. tuple(): This function is used to convert to a tuple.
7. set(): This function returns the type after converting to set.
8. list(): This function is used to convert any data type to a list type.

# Python code to demonstrate Type conversion

# using tuple(), set(), list()


INTRODUCTION TO PYTHON PROGRAMMING

#initializing string

s = 'geeks'

#printing string converting to tuple


c = tuple(s)
print("After converting string to tuple:", end="")
print (c)

#printing string converting to set


c = set(s)
print("After converting string to set :", end="")
print (c)

#printing string converting to list


c = list(s)
print ("After converting string to list:", end="")
print (c)

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.

# Python code to demonstrate Type conversion

# using dict(), complex(), str()


INTRODUCTION TO PYTHON PROGRAMMING

#initializing integers
a=1
b=2

#initializing tuple
tup=(('a', 1), ('f', 2), ('g', 3))

#printing integer converting to complex number


c = complex(1,2)
print ("After converting integer to complex number:", end="")
print (c)

#printing integer converting to string


c = str(a)
print ("After converting integer to string:", end="")
print (c)

#printing tuple converting to expression dictionary


c = dict(tup)
print ("After converting tuple to dictionary:", end="")
print (c)

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

#Convert ASCII value to characters


a = chr(76)
b= chr(77)

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.

Python standard library

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.

7. Scikit-learn: It is a famous Python library to work with complex data. Scikit-learn is an


open-source library that supports machine learning. It supports variously supervised and
unsupervised algorithms like linear regression, classification, clustering, etc. This library
works in association with Numpy and SciPy.

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.

Use of Libraries in Python Program

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.

Let’s have a look at exemplar code:

#Importing math library

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.

Importing 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.

Let’s look at an exemplar code:


INTRODUCTION TO PYTHON PROGRAMMING

#Importing specific items

from math import sqrt, sin

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.

Consider the following example in Python to create string.

Syntax:

str = "Hi Python!"

Here, if we check the type of the variable str using a Python script

print(type(str)), then it will print a string (str).

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.

Creating String in Python

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.

#Using single quotes

str1 = 'Hello Python'

print(str1)

#Using double quotes


INTRODUCTION TO PYTHON PROGRAMMING

str2="Hello Python"

print(str2)

#Using triple quotes

str3='''''Triple quotes are generally used for represent

the multiline or

doc string'''

print(str3)

Output:

Hello Python

Hello Python

Triple quotes are generally used for

represent the multiline or

doc string

Strings indexing and splitting

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

Consider the following example:

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:

IndexError: string index out of range

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.

Consider the following example:

#Given String
str= "PYTHON"
#Start Oth index to end
print(str[0:])

#Starts 1th index to 4th index


print(str[1:5])

#Starts 2nd index to 3rd index


print(str[2:4])

#Starts 0th to 2nd index


print(str[:3])

#Starts 4th to 6th index


print(str[4:7])
INTRODUCTION TO PYTHON PROGRAMMING

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.

Consider the following example

str = 'PYTHON'

print(str[-1])

print(str[-3])

print(str[-2:])

print(str[-4:-1])

print(str[-7:-2])

#Reversing the given string

print(str[::-1])

print(str[-12])
INTRODUCTION TO PYTHON PROGRAMMING

Output:

Python str() function

Python str() function returns the string version of the object.

Syntax: str(object, encoding=’utf-8?, errors=’strict’)

Parameters:

 object: The object whose string representation is to be returned.

 encoding: Encoding of the given object.

 errors: Response when decoding fails.

Returns: String version of the given object

Python str() function example

Example1: Demonstration of str() function


#Python program to demonstrate #
strings
#Empty string
s = str()

print(s)

#String with values


s=str("PESIAMS")

print(s)
INTRODUCTION TO PYTHON PROGRAMMING
Output:

PESIAMS

Example2: Converting to string

#Python program to demonstrate

# strings
num=100
s = str(num)
print(s, type(s))

num = 100.1
s = str(num)
print(s, type(s))

Output:

100 <class 'str'>

101 <class 'str'>

Operations on Strings
String Concatenation
String concatenation means add strings together.

Use the + character to add a variable to another variable

Example - 1:

x="Python is"
y="awesome"

z=x+y

print(z)

Output:
Python is awesome

Example-2: Merge variable a with variable b into variable

a="Hello"
b="World"
INTRODUCTION TO PYTHON PROGRAMMING
c=a+b

print(c)

Output:
Hello World

String Comparison

Method 1: Using Relational Operators


The relational operators compare the Unicode values of the characters of the strings from the

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

Method 2: Using is and is not


The == operator compares the values of both the operands and checks for value equality.
Whereas is operator checks whether both the operands refer to the same object or not. The same
is the case for != and is not.

Example:

str1="Iams"
str2="Iams"
str3 = str1

print("ID of str1=", hex(id(str1)))


print("ID of str2=", hex(id(str2)))
print("ID of str3=", hex(id(str3)))
print(str1 is str1)
print(str1 is str2)
print(str1 is str3)
INTRODUCTION TO PYTHON PROGRAMMING
str1 +="PES"
str4 = "Pesiams"

print("\n ID of changed str1=", hex(id(str1)))


print(" ID of str4 = ", hex(id(str4)))

print(str1 is str4)

Output:

ID of str1 =0xf98860
ID of str2 =0xf98860
ID of str3 =0xf98860
True
True
True

ID of changed str1 = 0xfd45e0


ID of str4 = 0xfbf9c0
False

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 and joining in string

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])

print ('characters 2 to end is', str[2:])

print ('characters 1 to -1 is', str[1:-1])

print ('characters 0 to -1 is', str[:-1])


print('characters-7to-1is',str[-7:-1])
print('characters -5 to -3 is', str[-5:-3])
print('characters start to end is', str[:])
Output:

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.

#python code to split and join given string

# 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 traversal using while loop


str="PYTHON"
i=0
while i<len(str):
print(str[i])
i=i+1
INTRODUCTION TO PYTHON PROGRAMMING

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”.

Example 1: Formatting string using % operator


print("The python is %s language" %'dynamic')

Output:

The python is dynamic language

Example 2: Injecting multiple strings using %operator

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.

print('The value of pi is: %5.4f' %(3.141592))

Output:

The value of pi is:3.1416


INTRODUCTION TO PYTHON PROGRAMMING

variable=12

string="Variable as integer= %d\n\


Variable as float=%f"% (variable, variable)

print(string)

Output:
Variable as integer = 12

Variable as float=12.000000

Method 2: Formatting string using format( ) method

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.

Syntax: ‘String here {} then also{}’.format(‘something1′,’something2’)

print('We all are{}.'.format('equal'))

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:

print('{2} {1} {0}'.format('directions', 'the', 'Read'))

Output:
Read the directions.

 We can insert objects by using assigned keywords:

print('a: {a}, b: {b}, c: {c}'.format(a = 1, b = 'Two', c = 12.3))

Output:
a: 1, b: Two, c: 12.3
INTRODUCTION TO PYTHON PROGRAMMING

Method 3: Formatted String using F-strings

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.

Example: Formatting string with F-Strings


name= 'Dynamic'

print(f"Python is {name} language")

Output:

Python is Dynamic language

Example: Arithmetic operations using F-strings


a=5

b=10

print(f"He said his age is {2*(a+b)}.")

Output:
He said his age is 30.
Example: Float Precision using F-strings
num=3.14159

print(f"The value of pi is:{num:{1}.{5}}")

Output: The value of pi is: 3.1416

Method 4: String Template Class


In the String module, Template Class allows us to create simplified syntax for output
specification. The format uses placeholder names formed by $ with valid Python identifiers
(alpha numeric characters and underscores). Surrounding the place holder with braces
INTRODUCTION TO PYTHON PROGRAMMING

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

from string import Template

n1 = 'Hello'
n2 ='Python language'

#made a template which we used to

# pass two variable so n3 and n4


#formal and n1 and n2 actual

n=Template('$n3 ! This is $n4.')

# and pass the parameters into the

# template string.

print(n.substitute(n3=n1, n4=n2))

Output:
Hello! This is Python language.

Method4: String center( ) method


The center( ) method is a built-in method in Python’s str class that returns an new string that is
centered within a string of a specified width.
Example: Formatting string using center( )method
string="PRASHANTH KUMAR R!"
width=30
centered_string = string.center(width)
print(centered_string)

Output:
INTRODUCTION TO PYTHON PROGRAMMING

Escape Sequences in python

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

\' Prints a single quote inside a string enclosed with single


quotes.

\" Prints a double quote inside a string enclosed with


double-quotes.

\n Prints the succeeding part of \n even if in the same line, in


a new line

\t Gives a tab space equivalent to 8 normal spaces.

\r Brings the cursor to the starting of the line, called as


'carriage return.'

\b Gives a backspace.

\f Creates an f-string which is a whole new string


formatting mechanism

\ooo Gives the octal representation


INTRODUCTION TO PYTHON PROGRAMMING

\\ Prints a back slash character

\xhh Gives the hexadecimal representation

Python String Methods

Case Changing of Strings

The below functions are used to change the case of the strings.

 lower( ):Converts all upper case characters in a string into lowercase


 upper( ):Converts all lower case characters in a string into uppercase
 title( ):Convert string to title case
 swapcase( ):Swap the cases of all characters in a string
 capitalize( ):Convert the first character of a string to uppercase

Example: Changing the case of Python Strings


#Python program explore string functions
text= 'welcome To PesIams'

# upper( ) function to convert

# string to upper case

print("\n Converted String:")


print(text.upper())

#lower( ) function to convert


# string to lower case
print("\n Converted String:")
print(text.lower())

#converts the first character to


#uppercaseandresttolowercase
print("\nConverted String:")
print(text.title())
INTRODUCTION TO PYTHON PROGRAMMING

#swaps the case of all characters in the string


#upper case character to lower case and vice versa
print("\n Converted String:")

print(text.swapcase())

#convert the first character of a string to upper case


print("\n Converted String:")
print(text.capitalize())

#original string never changes


print("\n Original String")
print(text)

Output:
INTRODUCTION TO PYTHON PROGRAMMING

Table of Python String Methods

Function Name
Description

capitalize( ) Converts the first character of the string to a capital (uppercase) letter

casefold( ) Implements caseless string matching

center( ) Pad the string with the specified character.

count( ) Returns the number of occurrences of a substring in the string.

encode( ) Encodes strings with the specified encoded scheme

endswith( ) Returns “True” if a string ends with the given suffix

Specifies the amount of space to be substituted with the “\t” symbol in the
expandtabs( )
string

find( ) Returns the lowest index of the substring if it is found

format( ) Formats the string for printing it to console

format_map( ) Formats specified values in a string using a dictionary

index( ) Returns the position of the first occurrence of a substring in a string

Checks whether all the characters in a given string is alphanumeric or not


isalnum( )

isalpha( ) Returns “True” if all characters in the string are alphabets


INTRODUCTION TO PYTHON PROGRAMMING

Function Name
Description

isdecimal( ) Returns true if all characters in a string are decimal

isdigit( ) Returns “True” if all characters in the string are digits

isidentifier( ) Check whether a string is a valid identifier or not

islower( ) Checks if all characters in the string are lower case

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

istitle( ) Returns “True” if the string is a title cased string

isupper( ) Checks if all characters in the string are uppercase

join( ) Returns a concatenated String

ljust( ) Leftalignsthestringaccordingtothewidthspecified

lower( ) Converts all upper-case characters in a string into lower case

lstrip( ) Returns the string with leading characters removed

maketrans( ) Returns a translation table


INTRODUCTION TO PYTHON PROGRAMMING

Function Name
Description

partition( ) Splits the string at the first occurrence of the separator

replace( ) Replaces all occurrences of a substring with another substring

rfind( ) Returns the highest index of the substring

Rindex( ) Returns the highest index of the substring inside the string

rjust( ) Right aligns the string according to the width specified

rpartition( ) Split the given string into three parts

rsplit( ) Split the string from the right by the specified separator

rstrip( ) Removes trailing characters

splitlines( ) Split the lines at line boundaries

startswith( ) Returns “True” if a string starts with the given prefix

strip( ) Returns the string with both leading and trailing characters

swapcase( ) Converts all upper-case characters to lowercase and vice versa

title( ) Convert string to title case

translate( ) Modify string according to given translation mappings


INTRODUCTION TO PYTHON PROGRAMMING

Function Name
Description

upper( ) Converts all lower-case characters in a string in to upper case

Returns a copy of the string with ‘0’ characters padded to the left side of
zfill( )
the string

You might also like