Professional Documents
Culture Documents
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.
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.
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.
Python is freely available for everyone. It is freely available on its official website www.python.org. It has a
large community across the world that is dedicatedly working towards make new python modules and
functions. Anyone can contribute to the Python community. The open-source means, "Anyone can
download its source code without paying any penny."
6) Object-Oriented Language
Python supports object-oriented language and concepts of classes and objects come into existence. It
supports inheritance, polymorphism, and encapsulation, etc. The object-oriented procedure helps to
programmer to write reusable code and develop applications in less code.
7) Extensible
It implies that other languages such as C/C++ can be used to compile the code and thus it can be used
further in our Python code. It converts the program into byte code, and any platform can use that byte code.
It provides a vast range of libraries for the various fields such as machine learning, web developer, and also
for the scripting. There are various machine learning libraries, such as Tensor flow, Pandas, Numpy, Keras,
and Pytorch, etc. Django, flask, pyramids are the popular framework for Python web development.
Graphical User Interface is used for the developing Desktop application. PyQT5, Tkinter, Kivy are the
libraries which are used for developing the web application.
10) Integrated
It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs code line by line like
C,C++ Java. It makes easy to debug the code.
11. Embeddable
The code of the other programming language can use in the Python source code. We can use Python source
code in another programming language as well. It can embed other language into our code.
In Python, we don't need to specify the data-type of the variable. When we assign some value to the variable,
it automatically allocates the memory to the variable at run time. Suppose we are assigned integer value 15
to x, then we don't need to write int x = 15. Just write x = 15.
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.
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
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.
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.
as elif if or yield
#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:
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 !")
#This is a comment
#written in
print("Hello, World!")
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
"""
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:
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
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.
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)
print(a)
print(a)
Boolean Values
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)
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
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:
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
== Equal x == y
!= Not equal x != y
and Returns True if both statements are true x < 5 and x < 1
not Reverse the result, returns False if the result is true not(x < 5 and x < 10)
is not Returns True if both variables are not the same object x is not y
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:
<< Zero fill left shift Shift left by pushing zeros in from the right and let
>> 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 ().
Syntax:
For example :
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.
READING NUMBERS
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:
Examples:
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.
print(“message”)
print(variable)
print(expression)
Example statement 1 :
print(“Python is wonderful”)
Python is wonderful
Example statement 2 :
print (17.5)
17.5
Example statement 3 :
Sum of 2 and 3 is 5
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 .
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.
[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)
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.
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)
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.
if expression:
statement
Example :
If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.
if condition:
#block of statements
else:
#another block of statements (else-block)
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
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.
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.
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.
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.
list = ['VPT','MAPPD','Python','Linux',‟IOT‟]
for i in range(len(list)):
print("I am learning ",list[i])
Example: Using the start parameter:
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!")
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
Example:
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.
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.
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.
i = 1
while i < 6:
print(i)
if (i == 3):
break
i += 1
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
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.
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
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.
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
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.
To check if a certain phrase or character is NOT present in a string, we can use the keyword not in.
Use it in an if statement:
Slicing
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:
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:
b = "Hello, World!"
print(b[-5:-2])
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:
x = txt.title()
y=txt1.title()
print(x)
print(y)
Output:
2. upper() Method
The upper() method returns a string where all characters are in upper case.
Syntax
string.upper()
3. lower() Method
The lower() method returns a string where all characters are lower case.
Syntax
string.lower()
Example:
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:
x = txt.swapcase()
print(x)
Output:
5. split() Method
The split() method splits a string into a list.
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:
x = txt.split()
print(x)
Output:
x = txt.split(", ")
print(x)
Output:
['In MCA Second Year', 'We have ', 'VPT ', 'Mobile Development ',
'Python ', 'Linux ', 'IOT subjects']
Example3:
x = txt.split("#")
print(x)
Output:
Example4:
txt = "VPT#ANDROID#PYTHON#LINUX#IOT"
['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
Example:
x = txt.strip()
print(x)
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 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
end Optional. Where to end the search. Default is to the end of the string.
Example:
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?:
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
count Optional. A number specifying how many occurrences of the old value you want to replace. Default
is all occurrences
Example:
x = txt.replace("Python", "Android")
print(x)
Output:
Example2:
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:
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
Example:
Output:
True
Example2:
Output:
True
10. endswith() Method
The endswith() method returns True if the string ends with the specified value, otherwise False.
Syntax
Example
x = txt.endswith(".")
print(x)
Output:
True
Example2:
Check if the string ends with the phrase " Python Programming.":
x = txt.endswith("Python Programming.")
print(x)
Output:
True
Example3:
print(x)
Output:
False
11. index() Method
The index() method finds the first occurrence of the specified value.
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
Parameter Values
end Optional. Where to end the search. Default is to the end of the string
Example
Output:
18
Example2:
Output:
1
Example3:
Where in the text is the first occurrence of the letter "e" when you only search between position 5
and 10?:
Output:
8
Example4:
If the value is not found, the find() method returns -1, but the index() method will raise an exception:
Output:
-1
Traceback (most recent call last):
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
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:
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.
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.
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.
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")
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")
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.
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.
The PEP 257 document provides the standard conventions to write multi-line docstrings for various
objects.
Some have been listed below:
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.
import pickle
print(pickle.__doc__)
Output
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.
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.
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.
"""
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
Parameters
----------
additional : str, optional
More info to be displayed (default is None)
Returns
-------
None
"""
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