You are on page 1of 51

What is 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 History
Python was invented by Guido van Rossum in 1991 at CWI in Netherland. The idea of Python
programming language has taken from the ABC programming language or we can say that ABC is a
predecessor of Python language.

There is also a fact behind the choosing name Python. Guido van Rossum was a fan of the popular BBC
comedy show of that time, "Monty Python's Flying Circus". So he decided to pick the name Python for
his newly created programming language.

Python has the vast community across the world and releases its version within the short period.

Why learn Python?


Python provides many useful features to the programmer. These features make it most popular and widely
used language. We have listed below few-essential feature of Python.

o Easy to use and Learn


o Expressive Language
o Interpreted Language
o Object-Oriented Language
o Open Source Language
o Extensible
o Learn Standard Library
o GUI Programming Support
o Integrated
o Embeddable
o Dynamic Memory Allocation
o Wide Range of Libraries and Frameworks

Where is Python used?


Python is a general-purpose, popular programming language and it is used in almost every technical field. The
various areas of Python use are given below.

o Data Science
o Date Mining
o Desktop Applications
o Console-based Applications
o Mobile Applications
o Software Development
o Artificial Intelligence
o Web Applications
o Enterprise Applications
o 3D CAD Applications
o Machine Learning
o Computer Vision or Image Processing Applications.
o Speech Recognitions
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 straightforward 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.

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

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 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.
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 Versions
 Python 3.9.7, documentation released on 30 August 2021.

 Python 3.9.6, documentation released on 28 June 2021.

 Python 3.9.5, documentation released on 3 May 2021.

 Python 3.9.4, documentation released on 4 April 2021.

 Python 3.9.3, documentation released on 2 April 2021.

 Python 3.9.2, documentation released on 19 February 2021.

 Python 3.9.1, documentation released on 8 December 2020.

 Python 3.9.0, documentation released on 5 October 2020.

 Python 3.8.12, documentation released on 30 August 2021.

 Python 3.8.11, documentation released on 28 June 2021.

 Python 3.8.10, documentation released on 3 May 2021.

 Python 3.8.9, documentation released on 2 April 2021.

 Python 3.8.8, documentation released on 19 February 2021.

 Python 3.8.7, documentation released on 21 December 2020.

 Python 3.8.6, documentation released on 23 September 2020.

 Python 3.8.5, documentation released on 20 July 2020.

 Python 3.8.4, documentation released on 13 July 2020.

 Python 3.8.3, documentation released on 13 May 2020.

 Python 3.8.2, documentation released on 24 February 2020.

 Python 3.8.1, documentation released on 18 December 2019.

 Python 3.8.0, documentation released on 14 October 2019.

 Python 3.7.12, documentation released on 4 September 2021.

 Python 3.7.11, documentation released on 28 June 2021.

 Python 3.7.10, documentation released on 15 February 2021.

 Python 3.7.9, documentation released on 17 August 2020.

 Python 3.7.8, documentation released on 27 June 2020.

 Python 3.7.7, documentation released on 10 March 2020.

 Python 3.7.6, documentation released on 18 December 2019.

 Python 3.7.5, documentation released on 15 October 2019.

 Python 3.7.4, documentation released on 08 July 2019.


 Python 3.7.3, documentation released on 25 March 2019.

 Python 3.7.2, documentation released on 24 December 2018.

 Python 3.7.1, documentation released on 20 October 2018.

 Python 3.7.0, documentation released on 27 June 2018.

 Python 3.6.15, documentation released on 4 September 2021.

 Python 3.6.14, documentation released on 28 June 2021.

 Python 3.6.13, documentation released on 15 February 2021.

 Python 3.6.12, documentation released on 17 August 2020.

 Python 3.6.11, documentation released on 27 June 2020.

 Python 3.6.10, documentation released on 18 December 2019.

 Python 3.6.9, documentation released on 02 July 2019.

 Python 3.6.8, documentation released on 24 December 2018.

 Python 3.6.7, documentation released on 20 October 2018.

 Python 3.6.6, documentation released on 27 June 2018.

 Python 3.6.5, documentation released on 28 March 2018.

 Python 3.6.4, documentation released on 19 December 2017.

 Python 3.6.3, documentation released on 03 October 2017.

 Python 3.6.2, documentation released on 17 July 2017.

 Python 3.6.1, documentation released on 21 March 2017.

 Python 3.6.0, documentation released on 23 December 2016.

 Python 3.5.10, documentation released on 5 September 2020.

 Python 3.5.8, documentation released on 1 November 2019.

 Python 3.5.7, documentation released on 18 March 2019.

 Python 3.5.6, documentation released on 8 August 2018.

 Python 3.5.5, documentation released on 4 February 2018.

 Python 3.5.4, documentation released on 25 July 2017.

 Python 3.5.3, documentation released on 17 January 2017.

 Python 3.5.2, documentation released on 27 June 2016.

 Python 3.5.1, documentation released on 07 December 2015.

 Python 3.5.0, documentation released on 13 September 2015.

 Python 3.4.10, documentation released on 18 March 2019.


 Python 3.4.9, documentation released on 8 August 2018.

 Python 3.4.8, documentation released on 4 February 2018.

 Python 3.4.7, documentation released on 25 July 2017.

 Python 3.4.6, documentation released on 17 January 2017.

 Python 3.4.5, documentation released on 26 June 2016.

 Python 3.4.4, documentation released on 06 December 2015.

 Python 3.4.3, documentation released on 25 February 2015.

 Python 3.4.2, documentation released on 4 October 2014.

 Python 3.4.1, documentation released on 18 May 2014.

 Python 3.4.0, documentation released on 16 March 2014.

 Python 3.3.7, documentation released on 19 September 2017.

 Python 3.3.6, documentation released on 12 October 2014.

 Python 3.3.5, documentation released on 9 March 2014.

 Python 3.3.4, documentation released on 9 February 2014.

 Python 3.3.3, documentation released on 17 November 2013.

 Python 3.3.2, documentation released on 15 May 2013.

 Python 3.3.1, documentation released on 7 April 2013.

 Python 3.3.0, documentation released on 29 September 2012.

 Python 3.2.6, documentation released on 11 October 2014.

 Python 3.2.5, documentation released on 15 May 2013.

 Python 3.2.4, documentation released on 7 April 2013.

 Python 3.2.3, documentation released on 10 April 2012.

 Python 3.2.2, documentation released on 4 September 2011.

 Python 3.2.1, documentation released on 10 July 2011.

 Python 3.2, documentation released on 20 February 2011.

 Python 3.1.5, documentation released on 9 April 2012.

 Python 3.1.4, documentation released on 11 June 2011.

 Python 3.1.3, documentation released on 27 November 2010.

 Python 3.1.2, documentation released on 21 March 2010.

 Python 3.1.1, documentation released on 17 August 2009.

 Python 3.1, documentation released on 27 June 2009.


 Python 3.0.1, documentation released on 13 February 2009.

 Python 3.0, documentation released on 3 December 2008.

 Python 2.7.18, documentation released on 20 April 2020

 Python 2.7.17, documentation released on 19 October 2019

 Python 2.7.16, documentation released on 02 March 2019

 Python 2.7.15, documentation released on 30 April 2018

 Python 2.7.14, documentation released on 16 September 2017

 Python 2.7.13, documentation released on 17 December 2016

 Python 2.7.12, documentation released on 26 June 2016.

 Python 2.7.11, documentation released on 5 December 2015.

 Python 2.7.10, documentation released on 23 May 2015.

 Python 2.7.9, documentation released on 10 December 2014.

 Python 2.7.8, documentation released on 1 July 2014.

 Python 2.7.7, documentation released on 31 May 2014.

 Python 2.7.6, documentation released on 10 November 2013.

 Python 2.7.5, documentation released on 15 May 2013.

 Python 2.7.4, documentation released on 6 April 2013.

 Python 2.7.3, documentation released on 9 April 2012.

 Python 2.7.2, documentation released on 11 June 2011.

 Python 2.7.1, documentation released on 27 November 2010.

 Python 2.7, documentation released on 4 July 2010.

 Python 2.6.9, documentation released on 29 October 2013.

 Python 2.6.8, documentation released on 10 April 2012.

 Python 2.6.7, documentation released on 3 June 2011.

 Python 2.6.6, documentation released on 24 August 2010.

 Python 2.6.5, documentation released on 19 March 2010.

 Python 2.6.4, documentation released on 25 October 2009.

 Python 2.6.3, documentation released on 2 October 2009.

 Python 2.6.2, documentation released on 14 April 2009.

 Python 2.6.1, documentation released on 4 December 2008.

 Python 2.6, documentation released on 1 October 2008.


 Python 2.5.4, documentation released on 23 December 2008.

 Python 2.5.3, documentation released on 19 December 2008.

 Python 2.5.2, documentation released on 21 February 2008.

 Python 2.5.1, documentation released on 18 April 2007.

 Python 2.5, documentation released on 19 September 2006.

 Python 2.4.4, documentation released on 18 October 2006.

 Python 2.4.3, documentation released on 29 March 2006.

 Python 2.4.2, documentation released on 28 September 2005.

 Python 2.4.1, documentation released on 30 March 2005.

 Python 2.4, documentation released on 30 November 2004.

 Python 2.3.5, documentation released on 8 February 2005.

 Python 2.3.4, documentation released on 27 May 2004.

 Python 2.3.3, documentation released on 19 December 2003.

 Python 2.3.2, documentation released on 3 October 2003.

 Python 2.3.1, documentation released on 23 September 2003.

 Python 2.3, documentation released on 29 July 2003.

 Python 2.2.3, documentation released on 30 May 2003.

 Python 2.2.2, documentation released on 14 October 2002.

 Python 2.2.1, documentation released on 10 April 2002.

 Python 2.2p1, documentation released on 29 March 2002.

 Python 2.2, documentation released on 21 December 2001.

 Python 2.1.3, documentation released on 8 April 2002.

 Python 2.1.2, documentation released on 16 January 2002.

 Python 2.1.1, documentation released on 20 July 2001.

 Python 2.1, documentation released on 15 April 2001.

 Python 2.0.1, documentation released on 22 June 2001.

 Python 2.0, documentation released on 16 October 2000.

 Python 1.6, documentation released on 5 September 2000.

 Python 1.5.2p2, documentation released on 22 March 2000.

 Python 1.5.2p1, documentation released on 6 July 1999.

 Python 1.5.2, documentation released on 30 April 1999.


 Python 1.5.1p1, documentation released on 6 August 1998.

 Python 1.5.1, documentation released on 14 April 1998.

 Python 1.5, documentation released on 17 February 1998.

 Python 1.4, documentation released on 25 October 1996.

Usage of Python
Python is a general purpose, open source, high-level programming language and also provides number of
libraries and frameworks. Python has gained popularity because of its simplicity, easy syntax and user-friendly
environment. The usage of Python as follows.

o Desktop Applications
o Web Applications
o Data Science
o Artificial Intelligence
o Machine Learning
o Scientific Computing
o Robotics
o Internet of Things (IoT)
o Gaming
o Mobile Apps
o Data Analysis and Pre-processing

Run the Python program:


Let us execute programs in different modes of programming.

 Interactive Mode Programming:

Invoking the interpreter without passing a script file as a parameter

 Script Mode Programming

Invoking the interpreter with a script parameter begins execution of the script and continues
until the script is finished. When the script is finished, the interpreter is no longer active.
Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module or other object. An identifier
starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores and
digits (0 to 9).

Python does not allow punctuation characters such as @, $, and % within identifiers.

Python is a case sensitive programming language. Thus, College and college are two different identifiers in
Python.

Python Identifiers – Naming Conventions:

 Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
 Starting an identifier with a single leading underscore indicates that the identifier is private.
 Starting an identifier with two leading underscores indicates a strong private identifier.
 If the identifier also ends with two trailing underscores, the identifier is a language-defined special
name.

Keywords
 Keywords are the reserved words in Python.
 We cannot use a keyword as a variable name, function name or any other identifier. They are used to
define the syntax and structure of the Python language.
 In Python, keywords are case sensitive.
– All the keywords except True, False and None are in lowercase and they must be written as it is.

 There are 33 keywords in Python 3.7

False class finally is return

None continue for lambda try

True def from nonlocal while

and del global not with

as elif if or yield

assert else import pass

break except in raise


Python Comments
 Comments can be used to explain Python code.
 Comments can be used to make the code more readable.
 Comments can be used to prevent execution when testing code.
 Comments starts with a #, and Python will ignore them:

#This is a comment

print("Hello, World!")

Comments can be placed at the end of a line, and Python will ignore the rest of the line:

print("Hello, World!") #This is a comment

A comment does not have to be text that explains the code, it can also be used to prevent Python
from executing code:

#print("Hello, World!")

print("Python !")

Multi Line Comments


Python does not really have a syntax for multi line comments.

To add a multiline comment you could insert a # for each line:

#This is a comment

#written in

#more than just one line

print("Hello, World!")

Or, not quite as intended, you can use a multiline string.

Since Python will ignore string literals that are not assigned to a variable, you can add a multiline
string (triple quotes) in your code, and place your comment inside it:

"""

This is a comment

written in

more than just one line

"""

print("Hello, World!")

As long as the string is not assigned to a variable, Python will read the code, but then ignore it, and you have
made a multiline comment.
Data types in Python
Built-in Data Types
In programming, data type is an important concept. Variables can store data of different types, and different
types can do different things.

Python has the following data types built-in by default, in these categories:

Text Type: str

Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: dict

Boolean Type: bool

Python Numbers Datatype:


There are three numeric types in Python:

 int
 float
 complex

Variables of numeric types are created when you assign a value to them:

x = 1 # int
y = 2.8 # float
z = 1j # complex

To verify the type of any object in Python, use the type() function:

print(type(x))

print(type(y))

print(type(z))

Int :

Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.

x = 1

y = 35656222554887711

z = -3255522

print(type(x))
print(type(y))

print(type(z))

Float

Float, or "floating point number" is a number, positive or negative, containing one or more decimals.

x = 1.10

y = 1.0

z = -35.59

print(type(x))

print(type(y))

print(type(z))

Float can also be scientific numbers with an "e" to indicate the power of 10.

x = 35e3

y = 12E4

z = -87.7e100

print(type(x))

print(type(y))

print(type(z))

Complex

Complex numbers are written with a "j" as the imaginary part:

x = 3+5j
y = 5j
z = -5j

print(type(x))
print(type(y))
print(type(z))
Python Strings Data type
Strings

Strings in python are surrounded by either single quotation marks, or double quotation marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:

print("Hello")

print('Hello')

a = "Hello"

print(a)

Multiline Strings

You can assign a multiline string to a variable by using three quotes: ( three double quotes or three
single quotes)

a = """Lorem ipsum dolor sit amet,

consectetur adipiscing elit,

sed do eiusmod tempor incididunt

ut labore et dolore magna aliqua."""

print(a)

a = '''Lorem ipsum dolor sit amet,

consectetur adipiscing elit,

sed do eiusmod tempor incididunt

ut labore et dolore magna aliqua.'''

print(a)

Python Boolean Data type


Booleans represent one of two values: True or False.

Boolean Values

In programming you often need to know if an expression is True or False.

You can evaluate any expression in Python, and get one of two answers, True or False.

When you compare two values, the expression is evaluated and Python returns the Boolean answer:

print(10 > 9)

print(10 == 9)
print(10 < 9)

When you run a condition in an if statement, Python returns True or False:

Print a message based on whether the condition is True or False:

a = 200
b = 33

if b > a:
print("b is greater than a")
else:
print("b is not greater than a")

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

In the example below, we use the + operator to add together two values:

print(10 + 5) o/p: 15

Python divides the operators in the following groups:

1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Logical operators
5. Identity operators
6. Membership operators
7. 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

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


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

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

not Reverse the result, returns False if the result is true not(x < 5 and x < 10)

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 object x is y

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

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 value is present in the object x in y

not in Returns True if a sequence with the specified value is not present in the object x not in y
Python Bitwise Operators
Bitwise operators are used to compare (binary) numbers:

Operator Name Description

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

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

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

~ NOT Inverts all the bits

<< Zero fill left shift Shift left by pushing zeros in from the right and let

the leftmost bits fall off

>> Signed right shift Shift right by pushing copies of the leftmost bit in

from the left, and let the rightmost bits fall off
Input & Output Statements in Python
input ():

To get input from user interactively, you can use built in function input ().

The function input() is used in the following manner:

Syntax:

variable = input(“message to be displayed”)

For example :

name = input(“What is your name?”)


Age = input(“Enter your age”)

The input function always return a value of String type, i.e. whatever value we enter through input() function
is treated as a String.

So whenever we are entering any number through input() then it will be treated as a String and no
calculations can be done on that.

Python does not allow any mathematical operation on Strings.

READING NUMBERS

String values cannot be used for arithmetic or numeric operations.

Python offers two functions int() and float() to be used with input() to convert the values received through
input() into int and float types.

Note: int is used for integer values and float represents decimal/fractional values in python.

Syntax:

variable = int(input(“Message to be displayed”))


variable = float(input(“Message to be displayed”))

Examples:

To input the age of a person we will write:

Age = int(input(“Enter your age”))

To input the marks of the student:

Marks = float(input(“Enter your marks: “))

While inputting integer values using int() with input(), make sure that the value being entered must be of
integer type. If you will enter decimal /fractional value then Python will give error.

While inputting the float values using float() with input(), make sure that the value being entered must be
float type.
Print() :
The print() function of python is used to print or to send any output to monitor.

Syntax for simple print():

print(“message”)
print(variable)
print(expression)

Consider the following examples with output to understand:

Example statement 1 :

print(“Python is wonderful”)

will print the output as:

Python is wonderful

Example statement 2 :

print (17.5)

will print the output as:

17.5

Example statement 3 :

print(“Sum of 2 and 3 is”,2+3)

will print the output as:

Sum of 2 and 3 is 5

Note: A print() without any value will print a blank line.

Features of print() statement

 It auto converts the items to strings i.e if you are printing a numeric value, it will automatically
convert it into equivalent string and print it.

For Numeric expressions it first evaluates them and then converts the result to string, before printing
.

 It inserts spaces between items automatically because the default value of sep argument is space(‘ ‘).
The sep argument specifies the separator character i.e if there are more than one outputs then they
will be separated by space while printing on screen.
Consider the following code:
print(“My”, “name”, “is”, “Amit”)
[Four different strings with no space in them are being printed]

will print
My name is Amit

[But the output line has automatically spaces inserted in between them because default sep character
is a space.]

Now we will change the value of sep character and see the effect of this:
print(“My”, “name”, “is”, “Amit”, sep = „...‟)

will print :
My...name...is...Amit

[This time the print() separated the items with the given sep character , which is ‘...’ ]

 It appends a newline character at the end of the line unless you give your own end argument .

Consider the following code:


print(“My name is Amit.”)
print(“I am 16 years old”)

It will produce the output as :


My name is Amit.
I am 16 years old

So , a print() statement appended a newline at the end because we have not specified any end
argument with it and n default print() takes value for end argument as ‘\n’ – the newline character.

If you explicitly give an end argument with a print() function then the print() will print the line and
end it with the string specified with the end argument.

See the following code:


print(“My name is Amit”, end= „$‟)
print(“I am 16 years old.”)

will print output as :


My name is Amit $ I am 16 years old.

[This time the print() ended the line with the given end character, which is ‘$’ here.]

Note: If we want the next output to appear in the same line then in end argument we need to specify
space ‘ ‘.
Consider the following code:

a,b = 10, 20
print(“a=”, a, end „ „)
print(“b =”,b)

Now the output produced will be like this:


a=10 b=20

This space is because of end =’ ‘ in print(). And the next output is coming along with the first one.

Now we will look at some of the example program related to input/output in python.

Program to obtain three numbers and print their sum

# to input 3 numbers and print their sum


num1= int(input(“Enter number 1:”))
num2 = int(input(“Enter number2:”))
num3 = int(input(“Enter number3:”))
sum = num1+num2+num3
print(“Three numbers are: “,num1,num2,num3)
print(“The sum is : “, sum)

The output produced by above program is :

Enter number 1: 1
Enter number 2: 2
Enter number 3: 3
Three numbers are : 1 2 3
The sum is : 6

Program to obtain length and breadth of a rectangle and calculate its area.

#to input length and breadth of a rectangle and display its area
length=float(input(“Enter length of the rectangle: “))
breadth=float(input(“Enter breadth of the rectangle: “))
area = length * breadth
print(“Rectangle specifications:” )
print(“Length = “, length, end= „ ‟)
print(“Breadth=”,breadth)
print(“Area =”,area)

The Output produced by above program is :

Enter length of the rectangle:12


Enter breadth of the rectangle:4.5
Rectangle specifications:
Length = 12 Breadth= 4.5
Area = 54.0
Python Flow Control statements
Decision making statements
Decision making is the most important aspect of almost all the programming languages. As the name implies,
decision making allows us to run a particular block of code for a particular decision. Here, the decisions are
made on the validity of the particular conditions. Condition checking is the backbone of decision making.

In python, decision making is performed by the following statements.

1. If Statement
2. If - else Statement
3. Nested if Statement

Indentation in Python
In Python, indentation is used to declare a block. Python indentation is a way of telling a Python interpreter
that the group of statements belongs to a particular block of code. A block is a combination of all these
statements. If two statements are at the same indentation level, then they are the part of the same block.

Block can be regarded as the grouping of statements for a specific purpose. Most of the programming
languages like C, C++, Java use braces { } to define a block of code.

For the ease of programming and to achieve simplicity, python doesn't allow the use of parentheses for the
block level code. Python uses indentation to highlight the blocks of code. Whitespace is used for indentation
in Python.

Generally, four spaces are given to indent the statements which are a typical amount of indentation in
python.All the statements of one block are intended at the same level indentation.
The if statement
The if statement is used to test a particular condition and if the condition is true, it executes a block of code
known as if-block. The condition of if statement can be any valid logical expression which can be either
evaluated to true or false.

The syntax of the if-statement is given below.

if expression:
statement
Example :

num = int(input("enter the number?"))


if num%2 == 0:
print("Number is even")

The if-else statement


The if-else statement provides an else block combined with the if statement which is executed in the false
case of the condition.

If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.

The syntax of the if-else statement is given below.

if condition:
#block of statements
else:
#another block of statements (else-block)

Example 1 : Program to check whether a person is eligible to vote or not.

age = int (input("Enter your age? "))


if age>=18:
print("You are eligible to vote !!");
else:
print("Sorry! you have to wait !!");

The elif statement


The elif statement enables us to check multiple conditions and execute the specific block of statements
depending upon the true condition among them. We can have any number of elif statements in our program
depending upon our need. However, using elif is optional.

The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if statement.
The syntax of the elif statement is given below.

if expression 1:
# block of statements

elif expression 2:
# block of statements

elif expression 3:
# block of statements

else:
# block of statements

Example 1

number = int(input("Enter the number?"))


if number==10:
print("number is equals to 10")
elif number==50:
print("number is equal to 50");
elif number==100:
print("number is equal to 100");
else:
print("number is not equal to 10, 50 or 100");
Python Loops
The flow of the programs written in any programming language is sequential by default. Sometimes we may
need to alter the flow of the program. The execution of a specific code may need to be repeated several
numbers of times.

For this purpose, The programming languages provide various types of loops which are capable of repeating
some specific code several numbers of times. Consider the following diagram to understand the working of a
loop statement.

There are the following loop statements in Python.

1. for loop
2. while loop

for loop
The for loop in Python is used to iterate the statements or a part of the program several times. It is frequently
used to traverse the data structures like list, tuple, or dictionary.

The syntax of for loop in python is given below.

for iterating_var in sequence:


statement(s)
For loop Using Sequence
Example-1: Iterating string using for loop

str = "Python"
for i in str:
print(i)
Example- 2: Program to print the table of the given number .

list = [1,2,3,4,5,6,7,8,9,10]
n = 5
for i in list:
c = n*i
print(c)
For loop Using range() function
The range() function

To loop through a set of code a specified number of times, we can use the range() function.

The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by
default), and ends at a specified number.

The syntax of the range() function is given below.

range(start, stop, step size)

 The start represents the beginning of the iteration.


 The stop represents that the loop will iterate till stop-1. The range(1,5) will generate numbers 1 to 4
iterations. It is optional.
 The step size is used to skip the specific numbers from the iteration. It is optional to use. By default,
the step size is 1. It is optional.

Example-1: Program to print numbers in sequence.

for i in range(10):
print(i,end = ' ')
Note that range(10) is not the values of 0 to 10, but the values 0 to 9.

Example - 2: Program to print table of given number.

n = int(input("Enter the number "))


for i in range(1,11):
c = n*i
print(n,"*",i,"=",c)
Example-3: Program to print even number using step size in range().

n = int(input("Enter the number "))


for i in range(2,n,2):
print(i)
We can also use the range() function with sequence of numbers. The len() function is combined with
range() function which iterate through a sequence using indexing.

Consider the following example.

list = ['VPT','MAPPD','Python','Linux',‟IOT‟]
for i in range(len(list)):
print("I am learning ",list[i])
Example: Using the start parameter:

for x in range(2, 6):


print(x)
The range() function defaults to increment the sequence by 1, however it is possible to specify the increment
value by adding a third parameter: range(2, 30, 3):

for x in range(2, 30, 3):


print(x)

The break Statement


With the break statement we can stop the loop before it has looped through all the items:

Exit the loop when x is "banana":

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)
if x == "banana":
break
Exit the loop when x is "banana", but this time the break comes before the print:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
if x == "banana":
break
print(x)

The continue Statement


With the continue statement we can stop the current iteration of the loop, and continue with the next:

Do not print banana:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
if x == "banana":
continue
print(x)

Else in For Loop


The else keyword in a for loop specifies a block of code to be executed when the loop is finished:

Print all numbers from 0 to 5, and print a message when the loop has ended:

for x in range(6):
print(x)
else:
print("Finally finished!")
Note: The else block will NOT be executed if the loop is stopped by a break statement.
Break the loop when x is 3, and see what happens with the else block:

for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")

#If the loop breaks, the else block is not executed.

Nested Loops
A nested loop is a loop inside a loop.

The "inner loop" will be executed one time for each iteration of the "outer loop":

Syntax

for iterating_var1 in sequence: #outer loop


for iterating_var2 in sequence: #inner loop
#block of statements
#Other statements

Example:

# User input for number of rows


rows = int(input("Enter the rows:"))
# Outer loop will print number of rows
for i in range(0,rows+1):
# Inner loop will print number of Astrisk
for j in range(i):
print("*",end = '')
print()

The pass Statement


for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass
statement to avoid getting an error.

for x in [0, 1, 2]:


pass

# having an empty for loop like this, would raise an error


without the pass statement
While loop
The Python while loop allows a part of the code to be executed until the given condition returns false. It is
also known as a pre-tested loop.

It can be viewed as a repeating if statement. When we don't know the number of iterations then the while
loop is most effective to use.

The syntax is given below.

while expression:
statements
Here, the statements can be a single statement or a group of statements. The expression should be any valid
Python expression resulting in true or false. The true is any non-zero value and false is 0.

Example-Print i as long as i is less than 6:

i = 1
while i < 6:
print(i)
i += 1
Note: remember to increment i, or else the loop will continue forever.

The while loop requires relevant variables to be ready, in this example we need to define an indexing variable,
i, which we set to 1.

The break Statement


With the break statement we can stop the loop even if the while condition is true:

Example: Exit the loop when i is 3:

i = 1
while i < 6:
print(i)
if (i == 3):
break
i += 1

The continue Statement


With the continue statement we can stop the current iteration, and continue with the next:

Example-Continue to the next iteration if i is 3:

i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)

# Note that number 3 is missing in the result


The else Statement
With the else statement we can run a block of code once when the condition no longer is true:

Example-Print a message once the condition is false:

i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")

Python Strings
Strings

Strings in python are surrounded by either single quotation marks, or double quotation marks.

'hello' is the same as "hello".

You can display a string literal with the print () function:

#You can use double or single quotes


print("Hello")
print('Hello')
Assign String to a Variable

Assigning a string to a variable is done with the variable name followed by an equal sign and the string:

a = "Hello"
print(a)
Multiline Strings

a = """Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)

Strings are Arrays

Like many other popular programming languages, strings in Python are arrays of bytes representing unicode
characters.

However, Python does not have a character data type, a single character is simply a string with a length of 1.

Square brackets can be used to access elements of the string.

Example

a = "Hello, World!"
print(a[1])
Looping Through a String

Since strings are arrays, we can loop through the characters in a string, with a for loop.

for x in "banana":
print(x)
String Length

To get the length of a string, use the len() function.

The len() function returns the length of a string:

a = "Hello, World!"
print(len(a))

Check String

To check if a certain phrase or character is present in a string, we can use the keyword in.

Check if "free" is present in the following text:

txt = "The best things in life are free!"


print("free" in txt)
Use it in an if statement:

Print only if "free" is present:

txt = "The best things in life are free!"


if "free" in txt:
print("Yes, 'free' is present.")
Check if NOT

To check if a certain phrase or character is NOT present in a string, we can use the keyword not in.

Check if "expensive" is NOT present in the following text:

txt = "The best things in life are free!"


print("expensive" not in txt)

Use it in an if statement:

print only if "expensive" is NOT present:


txt = "The best things in life are free!"
if "expensive" not in txt:
print("No, 'expensive' is NOT present.")
Python - Slicing Strings

Slicing

You can return a range of characters by using the slice syntax.

Specify the start index and the end index, separated by a colon, to return a part of the string.
Get the characters from position 2 to position 5 (not included):

b = "Hello, World!"
print(b[2:5])
Slice From the Start

By leaving out the start index, the range will start at the first character:

Get the characters from the start to position 5 (not included):

b = "Hello, World!"
print(b[:5])
Slice To the End

By leaving out the end index, the range will go to the end:

Get the characters from position 2, and all the way to the end:

b = "Hello, World!"
print(b[2:])
Negative Indexing

Use negative indexes to start the slice from the end of the string. Get the characters:

From: "o" in "World!" (position -5)

To, but not included: "d" in "World!" (position -2):

b = "Hello, World!"
print(b[-5:-2])

Python String Methods


Python has a set of built-in methods that you can use on strings.

Note: All string methods returns new values. They do not change the original string.

1. title () Method

The title() method returns a string where the first character in every word is upper case. Like a header, or a
title.

If the word contains a number or a symbol, the first letter after that will be converted to upper case.

Syntax

string.title()
Example:

txt = "python is a very powerful programming language"


txt1 = "Python is 3rd subject in mca sy"

x = txt.title()
y=txt1.title()
print(x)
print(y)
Output:

Python Is A Very Powerful Programming Language


Python Is 3Rd Subject In Mca Sy

2. upper() Method

The upper() method returns a string where all characters are in upper case.

Symbols and Numbers are ignored.

Syntax

string.upper()
3. lower() Method

The lower() method returns a string where all characters are lower case.

Symbols and Numbers are ignored.

Syntax

string.lower()

Example:

txt = "Python Programming"


txt1 = "PYTHON Programming"
x = txt.upper()
y=txt1.lower()
print(x)
print(y)

Output:

PYTHON PROGRAMMING
python programming

4. swapcase() Method

The swapcase() method returns a string where all the upper case letters are lower case and vice versa.

Syntax

string.swapcase()
Example:

txt = "Hello My Name Is SACHIN"

x = txt.swapcase()

print(x)
Output:

hELLO mY nAME iS Sachin

5. split() Method
The split() method splits a string into a list.

You can specify the separator, default separator is any whitespace.

Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

Syntax

string.split(separator, maxsplit)
Parameter Values

Separator- Optional. Specifies the separator to use when splitting the string. By default any whitespace is a
separator

Maxsplit- Optional. Specifies how many splits to do. Default value is -1, which is "all occurrences"

Example:

txt = "welcome to the Python Programming"

x = txt.split()

print(x)

Output:

['welcome', 'to', 'the', 'Python', 'Programming']


Example2:

Split the string, using comma, followed by a space, as a separator:

txt = "In MCA Second Year, We have , VPT , Mobile Development ,


Python , Linux , IOT subjects"

x = txt.split(", ")

print(x)

Output:

['In MCA Second Year', 'We have ', 'VPT ', 'Mobile Development ',
'Python ', 'Linux ', 'IOT subjects']
Example3:

Use a hash character as a separator:


txt = "VPT#ANDROID#PYTHON#LINUX#IOT"

x = txt.split("#")

print(x)

Output:

['VPT', 'ANDROID', 'PYTHON', 'LINUX', 'IOT']

Example4:

Split the string into a list with max 2 items:

txt = "VPT#ANDROID#PYTHON#LINUX#IOT"

# setting the maxsplit parameter to 1, will return a list with 2


elements!
x = txt.split("#", 1)
print(x)
Output:

['VPT', 'ANDROID#PYTHON#LINUX#IOT']

6. strip() Method
The strip() method removes any leading (spaces at the beginning) and trailing (spaces at the end) characters
(space is the default leading character to remove)

Syntax

string.strip(characters)
Parameter Values

characters Optional. A set of characters to remove as leading/trailing characters

Example:

txt = " Python "

x = txt.strip()
print(x)

print("Out of all subjects", x, "is my favorite subject")

Output:

Python
Out of all subjects Python is my favorite subject
Example2:

txt = ",,,,,rrttgg.....Python....rrr"
x = txt.strip(",.grt")
print(x)

Output:

Python

7. find() Method

The find() method finds the first occurrence of the specified value.

The find() method returns -1 if the value is not found.

The find() method is almost the same as the index() method, the only difference is that the index() method
raises an exception if the value is not found. (See example below)

Syntax

string.find(value, start, end)


Parameter Values

value Required. The value to search for

start Optional. Where to start the search. Default is 0

end Optional. Where to end the search. Default is to the end of the string.

Example:

txt = "VPT,Android,Python,Linux, IOT,Python Lab, VPT lab, Android


Lab"

x = txt.find("Python")

print(x)
Output:

12

Example2:

Where in the text is the first occurrence of the letter "Python" when you only search between
position20 and 40?:

txt = "VPT,Android,Python,Linux, IOT,Python Lab, VPT lab, Android


Lab"

x = txt.find("Python",20,40)

print(x)
Output:

30

8. replace() Method
The replace() method replaces a specified phrase with another specified phrase.

Note: All occurrences of the specified phrase will be replaced, if nothing else is specified.

Syntax

string.replace(oldvalue, newvalue, count)


Parameter Values

oldvalue Required. The string to search for

newvalue Required. The string to replace the old value with

count Optional. A number specifying how many occurrences of the old value you want to replace. Default
is all occurrences

Example:

txt = "I am learning Python language"

x = txt.replace("Python", "Android")

print(x)

Output:

I am learning Android language

Example2:

Replace all occurrence of the word "one":

txt = "one one was a race horse, two two was one too."

x = txt.replace("one", "three")

print(x)
Output:

three three was a race horse, two two was three too.
Example:

Replace the two first occurrence of the word "one":

txt = "one one was a race horse, two two was one too."

x = txt.replace("one", "three", 2)

print(x)

Output:

three three was a race horse, two two was one too.

9. startswith() Method

The startswith() method returns True if the string starts with the specified value, otherwise False.

Syntax

string.startswith(value, start, end)


Parameter Values

value Required. The value to check if the string starts with

start Optional. An Integer specifying at which position to start the search

end Optional. An Integer specifying at which position to end the search

Example:

txt = "Hello, welcome to Python Programming."


x = txt.startswith("Hello")
print(x)

Output:

True
Example2:

Check if position 7 to 20 starts with the characters "wel":

txt = "Hello, welcome to Python Programming."


x = txt.startswith("wel", 7, 20)
print(x)

Output:

True
10. endswith() Method

The endswith() method returns True if the string ends with the specified value, otherwise False.

Syntax

string.endswith(value, start, end)


Parameter Values

value Required. The value to check if the string ends with

start Optional. An Integer specifying at which position to start the search

end Optional. An Integer specifying at which position to end the search

Example

Check if the string ends with a punctuation sign (.):

txt = "Hello, welcome to Python Programming."

x = txt.endswith(".")

print(x)

Output:
True

Example2:

Check if the string ends with the phrase " Python Programming.":

txt = "Hello, welcome to Python Programming."

x = txt.endswith("Python Programming.")

print(x)

Output:
True

Example3:

Check if position 5 to 11 ends with the phrase " Python Programming.":

txt = "Hello, welcome to Python Programming."

x = txt.endswith("Python Programming.", 5, 11)

print(x)

Output:
False
11. index() Method

The index() method finds the first occurrence of the specified value.

The index() method raises an exception if the value is not found.

The index() method is almost the same as the find() method, the only difference is that the find() method
returns -1 if the value is not found. (See example below)

Syntax

string.index(value, start, end)

Parameter Values

value Required. The value to search for

start Optional. Where to start the search. Default is 0

end Optional. Where to end the search. Default is to the end of the string

Example

Where in the text is the word "Python"?:

txt = "Hello, welcome to Python Programming."


x = txt.index("Python")
print(x)

Output:

18

Example2:

Where in the text is the first occurrence of the letter "e"?:

txt = "Hello, welcome to Python Programming."


x = txt.index("e")
print(x)

Output:
1

Example3:
Where in the text is the first occurrence of the letter "e" when you only search between position 5
and 10?:

txt = "Hello, welcome to Programming."


x = txt.index("e", 5, 10)
print(x)

Output:
8
Example4:
If the value is not found, the find() method returns -1, but the index() method will raise an exception:

txt = "Hello, welcome toPython Programming."


print(txt.find("q"))
print(txt.index("q"))

Output:
-1
Traceback (most recent call last):

File "C:\Users\Pranav\string_index3.py", line 3, in <module>


print(txt.index("q"))

ValueError: substring not found

12. center() Method

The center() method will center align the string, using a specified character (space is default) as the fill
character.

Syntax

string.center(length, character)

Parameter Values

length Required. The length of the returned string

character Optional. The character to fill the missing space on each side. Default is " " (space)

Example:

Print the word " Python ", taking up the space of 20 characters, with " Python " in the middle:

txt = "Python"
x = txt.center(20)
print(x)

Output:
Python
Example2:

Using the letter "O" as the padding character:

txt = "Python"
x = txt.center(20,"O")
print(x)

Output:
OOOOOOOPythonOOOOOOO
13. format() Method
The format() method formats the specified value(s) and insert them inside the string's placeholder.

The placeholder is defined using curly brackets: {}. Read more about the placeholders in the
Placeholder section below.

The format() method returns the formatted string.

Syntax
string.format(value1, value2...)

Parameter Values
value1, value2... Required. One or more values that should be formatted and inserted in the
string.
The values are either a list of values separated by commas, a key=value list, or
a combination of both.

The values can be of any data type.

Example:
Insert the price inside the placeholder, the price should be in fixed point, two-decimal
format:
txt = "For only {price:.2f} dollars!"
print(txt.format(price = 49))

Output:
For only 49.00 dollars!

The Placeholders
The placeholders can be identified using named indexes {price}, numbered indexes {0}, or even
empty placeholders {}.

Example
Using different placeholder values:

#named indexes:
txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age
= 36)
#numbered indexes:
txt2 = "My name is {0}, I'm {1}".format("John",36)
#empty placeholders:
txt3 = "My name is {}, I'm {}".format("John",36)

print(txt1)
print(txt2)
print(txt3)
Output:
My name is John, I'm 36
My name is John, I'm 36
My name is John, I'm 36
Docstring:
Python docstrings are the string literals that appear right after the definition of a function, method,
class, or module.

Let's take an example.


Example 1: Docstrings
def square(n):
'''Takes in a number n, returns the square of n'''
return n**2
Here, the string literal:
'''Takes in a number n, returns the square of n'''
Inside the triple quotation marks is the docstring of the function square() as it appears right after its
definition.

Note: We can also use triple """ quotations to create docstrings.

Python Comments vs Docstrings

Python Comments
Comments are descriptions that help programmers better understand the intent and functionality of
the program. They are completely ignored by the Python interpreter.

In Python, we use the hash symbol # to write a single-line comment. For example,
# Program to print "Hello World"
print("Hello World")

Python Comments Using Strings

If we do not assign strings to any variable, they act as comments. For example,
"I am a single-line comment"

'''
I am a
multi-line comment!
'''

print("Hello World")

Note: We use triple quotation marks for multi-line strings.


Python docstrings

As mentioned above, Python docstrings are strings used right after the definition of a function,
method, class, or module (like in Example 1). They are used to document our code.

We can access these docstrings using the __doc__ attribute.

Python __doc__ attribute


Whenever string literals are present just after the definition of a function, module, class or method,
they are associated with the object as their __doc__ attribute. We can later use this attribute to
retrieve this docstring.

Example 2: Printing docstring

def square(n):
'''Takes in a number n, returns the square of n'''
return n**2

print(square.__doc__)

Output
Takes in a number n, returns the square of n

Here, the documentation of our square() function can be accessed using the __doc__ attribute.

Single-line docstrings in Python


Single line docstrings are the documents that fit in one line.

Standard conventions to write single-line docstrings:


 Even though they are single-lined, we still use the triple quotes around these docstrings as
they can be expanded easily later.
 The closing quotes are on the same line as the opening quotes.
 There's no blank line either before or after the docstring.
 They should not be descriptive, rather they must follow "Do this, return that" structure
ending with a period.

Example 4: Write single-line docstrings for a function


def multiplier(a, b):
"""Takes in two numbers, returns their product."""
return a*b

Multi-line Docstrings in Python


Multi-line docstrings consist of a summary line just like a one-line docstring, followed by a blank line,
followed by a more elaborate description.

The PEP 257 document provides the standard conventions to write multi-line docstrings for various
objects.
Some have been listed below:

1. Docstrings for Python Modules

 The docstrings for Python Modules should list all the available classes, functions, objects and
exceptions that are imported when the module is imported.
 They should also have a one-line summary for each item.
 They are written at the beginning of the Python file.

Let's look at the docstrings for the built-in module in Python called pickle.

Example 4: Docstrings of Python module

import pickle
print(pickle.__doc__)
Output

Create portable serialized representations of Python objects.

See module copyreg for a mechanism for registering custom


picklers.
See module pickletools source for extensive comments.

Classes:

Pickler
Unpickler

Functions:

dump(object, file)
dumps(object) -> string
load(file) -> object
loads(string) -> object

Misc variables:

__version__
format_version
compatible_formats

Here, we can see that the docstring written at the beginning of the pickle.py module file can be
accessed as its docstring.

Docstrings for Python Functions


 The docstring for a function or method should summarize its behavior and document its
arguments and return values.
 It should also list all the exceptions that can be raised and other optional arguments.
Example 5: Docstrings for Python functions

def add_binary(a, b):


'''
Returns the sum of two decimal numbers in binary digits.

Parameters:
a (int): A decimal integer
b (int): Another decimal integer

Returns:
binary_sum (str): Binary string of the sum of a and b
'''
binary_sum = bin(a+b)[2:]
return binary_sum

print(add_binary.__doc__)

Output:
Returns the sum of two decimal numbers in binary digits.

Parameters:
a (int): A decimal integer
b (int): Another decimal integer

Returns:
binary_sum (str): Binary string of the sum of a and b

As you can see, we have included a short description of what the function does, the parameter it takes
in and the value it returns. The string literal is embedded to the function add_binary as its __doc__
attribute.
3. Docstrings for Python Classes
 The docstrings for classes should summarize its behavior and list the public methods and
instance variables.
 The subclasses, constructors, and methods should each have their own docstrings.

Example 6: Docstrings for Python class


Suppose we have a Person.py file with the following code:

class Person:
"""
A class to represent a person.

...

Attributes
----------
name : str
first name of the person
surname : str
family name of the person
age : int
age of the person

Methods
-------
info(additional=""):
Prints the person's name and age.
"""

def __init__(self, name, surname, age):


"""
Constructs all the necessary attributes for the person
object.

Parameters
----------
name : str
first name of the person
surname : str
family name of the person
age : int
age of the person
"""

self.name = name
self.surname = surname
self.age = age

def info(self, additional=""):


"""
Prints the person's name and age.

If the argument 'additional' is passed, then it is


appended after the main info.

Parameters
----------
additional : str, optional
More info to be displayed (default is None)

Returns
-------
None
"""

print(f'My name is {self.name} {self.surname}. I am


{self.age} years old.' + additional)

Here, we can use the following code to access only the


docstrings of the Person class:
print(Person.__doc__)

Output
A class to represent a person.

...

Attributes
----------
name : str
first name of the person
surname : str
family name of the person
age : int
age of the person

Methods
-------
info(additional=""):
Prints the person's name and age

You might also like