Python Lab Manual
Python Lab Manual
How to Download and install Anaconda and how to launch juypter and
Spyder
Aim: To How to Download and install Anaconda and how to launch juypter and
Spyder
Description:
To begin, open your preferred web browser and go to the Anaconda download
page.
You will notice two options: "Anaconda Individual Edition" and "Anaconda
Team Edition." For most individual users, the Individual Edition is sufficient.
Click the download button next to the Individual Edition.
Choose the version of Anaconda that matches your system's architecture (32-
bit or 64-bit). Most modern PCs are 64-bit, but you can confirm your system
type by right-clicking on "This PC" or "My Computer," selecting "Properties,"
and checking the "System type" under the "System" section.
Click the "Download" button to start downloading the Anaconda installer for
Windows.
User need to provide email to download distributed. Type email and click on
submit button.
Click on next button.
It show required path defaulty and click button next then it will started
installation.
Installation successfully.
Finally screen.
JUPYTER NOTEBOOK
This will launch a new browser window (or a new tab) showing the Notebook
Dashboard, a sort of control panel that allows (among other things) to select
which notebook to open.
When started, the Jupyter Notebook App can access only files within its start-
up folder (including any sub-folder).
No configuration is necessary if you place your notebooks in your home folder
or subfolders. Otherwise, you need to choose a Jupyter Notebook App start-up
folder which will contain all the notebooks. See below for platform-specific
instructions on how to start Jupyter Notebook App in a specific folder.
Starting Spyder
The Spyder editor supports interactive testing, debugging, a variable explorer
and other nice things.
Then ..
Finally spyder will be opened and it takes fews seconds for first time, to
connect with kernel. Then it will ready to write up our code
Result:
Finally we successfully download anaconda and installed it. Then we lauch
both spyder and Jupyter Notebook
2. Write steps to download and installation of python
Introduction
The Python programming language is an increasingly popular choice for both beginners
and experienced developers. Flexible and versatile, Python has strengths in scripting,
automation, data analysis, machine learning, and back-end development.
In this Experiment you’ll install Python on Windows using the Python installer for
Windows.
Documentation: recommended
pip: recommended if you want to install other Python packages, such as NumPy or
pandas
tcl/tk and IDLE: recommended if you plan to use IDLE or follow tutorials that use it
Python test suite: recommended for testing and learning
py launcher and for all users: recommended to enable users to launch Python from
the command line
6. Click Next.
7. The Advanced Options dialog displays.
Select the options that suit your requirements:
Install for all users: recommended if you’re not the only user on this computer
Associate files with Python: recommended, because this option associates all the
Python file types with the launcher or editor
Create shortcuts for installed applications: recommended to enable shortcuts for
Python applications
Add Python to environment variables: recommended to enable launching Python
Precompile standard library: not required, it might down the installation
Download debugging symbols and Download debug binaries: recommended only if
you plan to create C or C++ extensions
Make note of the Python installation directory in case you need to reference it later.
Skip this step if you selected Add Python to environment variables during installation.
If you want to access Python through the command line but you didn’t add Python to
your environment variables during installation, then you can still do it manually.
Before you start, locate the Python installation directory on your system. The following
directories are examples of the default directory paths:
C:\Program Files\Python312: if you selected Install for all users during installation,
then the directory will be system wide
Note that the folder name will be different if you installed a different version, but will still
start with Python.
If you selected Install for all users during installation, select Path from
the list of System Variables and click Edit.
If you didn’t select Install for all users during installation,
select Path from the list of User Variables and click Edit.
5. Click New and enter the Python directory path, then click OK until all the dialogs are
closed.
You can verify whether the Python installation is successful either through the command
line or through the Integrated Development Environment (IDLE) application, if you
chose to install it.
Go to Start and enter cmd in the search bar. Click Command Prompt.
You can also check the version of Python by opening the IDLE application. Go to Start and
enter python in the search bar and then click the IDLE app, for example IDLE (Python 3.12 64-
bit).
You can start coding in Python using IDLE or your preferred code editor.
Conclusion
You’ve installed Python on your Windows computer and are ready to start learning and
programming in Python. Next, you can write your first program in Python 3 and continue
your learning with more Python tutorials.
3. Write programs to demostrate read and write function like print() and input()
Aim : To write programs to demostrate read and write function like print() and
input()
Description :
input () function:
The purpose of input() function is to read input from the standard input
(the keyboard, by default).
It accepts all user input as a string.
The user may enter a number or a string but the input() function treats
them as strings only.
OUTPUT:
Enter the first number: 10
Enter second number: 30
The sum of 10 and 30 is 40
OUTPUT:
Enter the first number: 10.5
Enter second number: 30.5
The sum of 10 and 30 is 41.0
Program:
name,Class,Marks = input("Enter your Name,Class,Marks
separated by space: ").split()
print("User Details: ",name, Class,Marks)
OUTPUT:
Enter your Name,Class,Marks separated by space:
Lakshman 4 98
User Details: Lakshman 4 98
print () function
The print ( ) function allows you to print out the value of a variable and
strings in parenthesis.
The print() function will print as strings everything in a comma-
separated sequence of expressions, and it will separate the results with
single blanks by default.
The print() function prints strings in between quotes (either single or
double). If a print statement has quotes around text, the computer will
print it out just as it is written.
To print multiple items, separate them with commas. The print()
function inserts a blank between objects.
The print() function automatically appends a newline to output. To print
without a newline, use end separator after the last object.
Where,
• sep: The optional parameter sep is a separator between the output
values. We can use a character, integer or a string as a separator. The
default separator is space.
• end: This is also optional and it allows us to specify any string to be
appended after the last value. The default is a new line.
• The file is the object where the values are printed and its default
value is sys.stdout (screen).
• flush force it to "flush" the buffer, meaning that it will write
everything in the buffer to the terminal, even if normally waits before
doing so.
The print() function prints a value, message or both message and values
and vice versa.
For example:
N1 = 20
N2 = 30
Sum = N1 + N2
Program:
print ('The sum of two numbers is', Sum)
# print is alternate way
print(Sum, "is the sum of", N1, "and", N2)
OUTPUT:
The sum of two numbers is 50
H-e-l-l-o
My*name*is*Lakshman
Aim: To write a program to find the largest element among three Numbers
Description:
To find the greatest of three numbers in python, these three numbers must be
taken as the input from the user, and the output of the programs will determine
the largest of all the numbers.
PROGRAM :
OUTPUT:
Program: Program:
OUTPUT:
8 OUTPUT:
Largest number in the list is: 400
Largest number in the list is: 400
5. Write a Program to display all prime numbers within an interval
The user is given two integer numbers, lower value, and upper value. The task
is to write the Python program for printing all the prime numbers between the
given interval (or range).
To print all the prime numbers between the given interval, the user has to
follow the following steps:
Program:
OUTPUT:
Please, Enter the Lowest Range Value: 10
Please, Enter the Upper Range Value: 50
The Prime Numbers in the range are:
11
13
17
19
23
29
31
37
41
43
47
Program:
import sympy
print(sympy.isprime(5))
print(list(sympy.primerange(0, 100)))
print(sympy.randprime(0, 100))
print(sympy.randprime(0, 100))
print(sympy.prime(3))
print(sympy.prevprime(50))
print(sympy.nextprime(50))
print list(sympy.sieve.primerange(0, 100))
OUTPUT:
True
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97]
83
41
5
47
53
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29,31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73,79,
83, 89, 97]
6. Write a program to swap two numbers without using a temporary
variable.
DESCRIPTION:
PROGRAM: PROGRAM:
a=int(input("Enter value of first variable: ")) a=int(input("Enter value of first variable: "))
b=int(input("Enter value of second variable: ")) b=int(input("Enter value of second variable:
a=a+b "))
b=a-b a=a*b
a=a-b b=a/b
print("a is:",a," b is:",b) a=a/b
print("a is:",a," b is:",b)
OUTPUT:
OUTPUT:
Enter value of first variable: 45
Enter value of second variable: 89 Enter value of first variable: 70
a is: 89 b is: 45 Enter value of second variable: 85
a is: 85.0 b is: 70.0
PROGRAM: PROGRAM:
a=int(input("Enter value of first variable: ")) a=int(input("Enter value of first variable: "))
b=int(input("Enter value of second variable: ")) b=int(input("Enter value of second variable: "))
a=a^b a,b = b,a
b=a^b print("a is:",a," b is:",b)
a=a^b
print("a is:",a," b is:",b)
OUTPUT: OUTPUT:
PROGRAM:
OUTPUT:
DESCRIPTION:
Operators in a programming language are used to perform various operations
on values and variables.
Arithmetic Operators
PROGRAM:
a = 21
b = 10
print ("a + b : ", a + b)
print ("a - b : ", a - b)
print ("a * b : ", a * b)
print ("a / b : ", a / b)
print ("a % b : ", a % b)
print ("a ** b : ", a ** b)
print ("a // b : ", a // b)
OUTPUT:
a + b : 31
a - b : 11
a * b : 210
a / b : 2.1
a %b: 1
a ** b : 16679880978201
a // b : 2
OUTPUT:
a == b : False
a != b : True
a > b : False
a < b : True
a >= b : False
a <= b : True
PROGRAM:
a = 10
a += 5
print ("a += 5 : ", a)
a -= 5
print ("a -= 5 : ", a)
a *= 5
print ("a *= 5 : ", a)
a /= 5
print ("a /= 5 : ",a)
a %= 3
print ("a %= 3 : ", a)
a **= 2
print ("a **= 2 : ", a)
a //= 3
print ("a //= 3 : ", a)
OUTPUT:
a += 5 : 15
a -= 5 : 10
a *= 5 : 50
a /= 5 : 10.0
a %= 3 : 1.0
a **= 2 : 1.0
a //= 3 : 0.0
PROGRAM:
a = 60
b = 13
c=a&b
print ("a & b : ", c)
c=a|b
print ("a | b : ", c)
c=a^b
print ("a ^ b : ", c)
c = ~a;
print ("~a : ", c)
c = a << 2;
print ("a << 2 : ", c)
c = a >> 2;
print ("a >> 2 : ", c)
OUTPUT:
a & b : 12
a | b : 61
a ^ b : 49
~a : -61
a << 2 : 240
a >> 2 : 15
PROGRAM:
x=5
y = 10
if x > 3 and y < 15:
print("Both x and y are within the specified range")
OUTPUT:
PROGRAM:
fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
print("Yes, banana is a fruit!")
else:
print("No, banana is not a fruit!")
OUTPUT:
Yes, banana is a fruit!
Python Identity Operators
PROGRAM:
x = 10
y=5
if x is y:
print("x and y are the same object")
else:
print("x and y are not the same object")
OUTPUT:
x and y are not the same object
Python Operators Precedence
Python Operator's Precedence can be explained by this given table,
Sr.No. Operator Description
1. ** Exponentiation (raise to the power)
2. ~+- Complement, unary plus and minus (method names
for the last two are +@ and -@)
3. * / % // Multiply, divide, modulo, and floor division
4. +- Addition and subtraction
5. >> << Right and left bitwise shift
6. & Bitwise 'AND'
7. ^| Bitwise exclusive `OR' and regular `OR'
8. <= < > >= Comparison operators
9. <> == != Equality operators
= %= /= //= -= +=
10. Assignment operators
*= **=
11. is is not Identity operators
12 in not in Membership operators
13. not or and Logical operators
PROGRAM:/OUTPUT:
>>> 5 - 7
-2
>>> 10 - 4 * 2
2
>>> (10 - 4) * 2
12
>>>print(5 * 2 // 3)
3
>>>print(5 * (2 // 3))
0
8. Write a program to add and multiply complex numbers
Aim: A complex number has two parts, real part and imaginary part.
Complex numbers are represented as A+Bi or A+Bj, where A is real part and
B is imaginary part.
Python supports complex data type as built-in feature which means we can
directly perform different operations on complex number in python.
>>> a=3+4j
>>> b=3+4i
SyntaxError: invalid syntax
python uses A+Bj notation to represent complex number meaning python will
recognize 3+4j as a valid number but 3+4i is not valid.
We can create complex number from two real numbers. Syntax for doing this
is:
c = complex(a,b)
Where, a & b are of real data types and c will be of complex data types.
PROGRAM: PROGRAM:
a=5 a = 5+6j
b=7 print(a.real)
c=complex(a,b) print(a.imag)
print(c) print(a)
OUTPUT: OUTPUT:
(5+7j) 5.0
6.0
(5+6j)
OUTPUT:
Enter complex number:30+42j
Given complex number is: (30-42j)
PROGRAM:
OUTPUT:
Enter complex number:30+42j
Enter complex number:22+8j
Addition of complex numbers : (52+50j)
Subtraction of complex numbers : (8+34j)
Multiplication of complex numbers : (324+1164j)
Division of complex numbers : (1.8175182481751824+1.2481751824817517j)
Error:
TypeError: can't mod complex numbers.
9. Write a program to print multiplication table of a given number.
AIM:
To write a program to print multiplication table of a given number.
Description:
Loops in Python programming come into use when we need to repeatedly
execute a block of statements.
There are 2 types of loop in Python and they are:
for Loop
while Loop
A for loop in Python is a repetition control structure which allows us to write a
loop that is executed a specific number of times. Python for loop can be used in
a list, tuple, set, string, etc.
PROGRAM: PROGRAM:
num=[10,12,8,25,82,64] fruit='SVPCET'
for x in num: for x in fruit:
print(x) print(x)
OUTPUT:
10 OUTPUT:
12 S
8 V
25 P
82 C
64 E
T
Use of range() Function in for Loop
Python range() function is used to generate a sequence of numbers. It is
commonly used in Python for loop and Python while loop. The range() function
accept only integer value as its parameters.
Syntax of range()
Start: Optional. If you don’t want to use the default 0, use this parameter to
specify which integer number will start the sequence.
Stop: Required. Use this parameter to specify which integer number will stop
the sequence.
A While loop is used to repeat a section of code an unknown number of times until
a specific condition is met.
OUTPUT:
Enter 2 numbers
10
5
Addition = 15
Subtraction = 5
Multiplication = 50
Division = 2.0
11. Aim: To Write a program to define a function using default
arguments.
Description:
In a function, arguments can have default values. We assign default
values to the argument using the ‘=’ (assignment) operator at the time of
function definition. You can define a function with any number of default
arguments.
The default value of an argument will be used inside a function if we do
not pass a value to that argument at the time of the function call. Due to this,
the default arguments become optional during the function call.
It overrides the default value if we provide a value to the default
arguments during function calls.
Program:
def student(name, age, grade="Five", school="Svpp School"):
print('Student Details:', name, age, grade, school)
student('lakshman', 19, 'Six')
student('hareesh', 20, 'Seven', 'SVPCET School')
OUTPUT:
Student Details: lakshman 19 Six Svpp School
Student Details: hareesh 20 Seven SVPCET School
12. Aim: Write a program to find the length of the string without using
any library functions.
Description:
When it is required to calculate the length of a string without using library
methods, a counter is used to increment every time an element of the string is
encountered.
Program:
OUTPUT:
Enter a String lakshman
The string is :
lakshman
The length of the string is 8
The length of the string using library function: 8
13. Write a program to check if the substring is present in a given string or not
Aim : To Write a program to check if the substring is present in a given string or not
Description:
Methods to Check if String Contains Substring
Using the ‘in’ Operator
Using the find() Method
Using the index() Method
Using Regular Expressions
Checking for Multiple Substrings
Using the ‘in’ Operator
Using the’ in’ operator is one of Python’s simplest and most commonly used
methods to check if a string contains a substring. This operator returns True if
the substring is found in the string and False otherwise.
Program:
Output:
Enter a Sentence :: i love svpcet college
Enter a string:: love
Substring found!
Using the find() Method
Another approach is to use the find() method, which returns the index of the
first occurrence of the substring in the string. If the substring is not found, it
returns -1.
Program:
OUTPUT
Enter a SentenceI am Studying in svpcet college
Enter a string to find in above sentencestudying
Substring not found.
Similar to the find() method, the index() method also returns the index of
the first occurrence of the substring in the string. However, if the substring
is not found, it raises a ValueError.
Program:
OUTPUT
OUTPUT:
Enter A Sentence :i love svpp college
Enter a string to sreach in sentence :svpp
Substring found!
Case Insensitive Substring Checking
By default, the methods mentioned above are case-sensitive. However, if
you want to perform a case-insensitive substring check, you can convert
the string and the substring to lowercase or uppercase using the lower() or
upper() methods.
PROGRAM:
OUTPUT:
Enter A Sentence :i love svpp college
Enter a string to sreach in sentence :College
Case-insensitive substring found!
Checking for Multiple Substrings
To check if a string contains multiple substrings, you can use a loop or
combine the ‘in’ operator with logical operators such as ‘and’ or ‘or’. any()
and all() functions
PROGRAM:
OUTPUT:
Enter A Sentence :i love svpp college
Enter a string to sreach in sentence :svpp college
All substrings found!
PROGRAM:
OUTPUT:
Enter A Sentence :i love svpp college
Enter a string to sreach in sentence :Svpp
All substrings found!
14. Write a program to perform the given operations on a list:
i. Addition ii. Insertion iii. slicing
Aim: To Write a program to perform the given operations on a list:
i. Addition ii. Insertion iii. Slicing
Description:
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of
data, the other 3 are Tuple, Set, and Dictionary, all with different
qualities and usage.
Lists are created using square brackets: [ ]
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has
index [1] etc.
Add List Items/inserting List Items/Slicing List Items
To add an item to the end of the list, use the append() method:
To insert a list item at a specified index, use the insert() method. The
insert() method inserts an item at the specified index:
To append elements from another list to the current list, use the extend()
method.The extend() method does not have to append lists, you can add
any iterable object (tuples, sets, dictionaries etc.).
List slicing is the process of accessing a part of the list using either
positive or negative indexing with the help of list slicing syntax given
below.
list_name[ start : end+1 : step]
Program:
mylist = ["apple", "banana", "cherry"]
mylist.append("orange")
print(mylist)
mylist.insert(1, "orange")
print(mylist)
tropical = ["mango", "pineapple", "papaya"]
mylist.extend(tropical)
print(mylist)
mytuple = ("kiwi", "orange")
mylist.extend(mytuple)
print(mylist)
a=[15,26,49,51,86,64,96,38]
print(a[0])
print(a[4])
print(a[-7])
print(a[0:3])
print(a[2:6])
print(a[-7:-4])
print(a[::2])
print(a[1::3])
print(a[2:5:2])
print(a[:])
Output:
['apple', 'banana', 'cherry', 'orange']
['apple', 'orange', 'banana', 'cherry', 'orange']
['apple', 'orange', 'banana', 'cherry', 'orange', 'mango', 'pineapple', 'papaya']
['apple', 'orange', 'banana', 'cherry', 'orange', 'mango', 'pineapple', 'papaya',
'kiwi', 'orange']
15
86
26
[15, 26, 49]
[49, 51, 86, 64]
[26, 49, 51]
[15, 49, 86, 96]
[26, 86, 38]
[49, 86]
[15, 26, 49, 51, 86, 64, 96, 38]
15. Write a program to check if a given key exists in a dictionary or
not, add a new key-value pair to an existing dictionary, and sum all the
items in a given dictionary
Aim: To Write a program to check if a given key exists in a dictionary or
not, add a new key-value pair to an existing dictionary, and sum all the
items in a given dictionary
Description:
Dictionary items are ordered, changeable, and do not allow duplicates.
A Dictionary is an ordered collection of some key:value pairs. The key
and its value is separated by a colon (:).
All the key:value pairs are inserted within a curly braces { } separated by
commas (,).
Dictionaries are mutable we can add or remove key:value pair in a
dictionary once it is created.
Note: Dictionaries are ordered from Python version 3.7 onwards and unordered
below version 3.7.
Example
# A dictionary containing an employee details
emp = {'id':'e156', 'name':'Allen', 'age':34, 'salary':15000}
Program:
Output:
Enter a Key to search in Dictonary=2
Present
5 Methods to Add new keys to a dictionary in Python
Using the Bracket Notation
Using the update() Method
Using the setdefault() Method
Using the fromkeys() Method
Using the dict() Constructor
Program:
Output:
{'name': 'John'}
{'name': 'John', 'age': 26, 'city': 'New York'}
{'name': 'John', 'age': 26, 'city': 'New York', 'salary': 25000}
{'name': 'Unknown', 'age': 'Unknown', 'city': 'Unknown'}
{'name': 'John', 'age': 25, 'city': 'New York'}
Output:
The sum of all items in the dictionary is: 600
The sum of all items in the dictionary is: 600
16. Write a program to create tuples (name, age, address, college) for at least two
members and concatenate the tuples and print the concatenated tuples.
Aim: To Write a program to create tuples (name, age, address, college) for at
least two members and concatenate the tuples and print the concatenated
tuples.
Description:
A file is the collection of data stored on a disk in one unit identified by
filename. file handling in Python, file operations such as opening a file, reading
from it, writing into it, closing it, renaming a file, deleting a file, and various file
methods. To store data temporarily and permanently,
There are four different methods (modes) for opening a file:
"r" - Read -
"a" - Append -
"w" - Write -
"x" – Create
use the built-in function,& method open() , read(), close() ,detach(), fileno()
flush(), isatty(), read(), readable(), readline(), readlines(), seek(),
seekable(), tell(), truncate(), writable(), write(), writelines()
Program:
Output:
17. Python program to print each line of a file in reverse order.
Aim: To Write a Python program to print each line of a file in reverse order.
Description:
Given a text file. The task is to reverse as well as stores the content from an
input file to an output file. This reversing can be performed in two types.
Full reversing: In this type of reversing all the content gets reversed.
Word to word reversing: In this kind of reversing the last word comes first
and the first word goes to the last position.
Program:
Output:
18. Write a program to create, display, append, insert and reverse the
order of the items in the array. Python Program to demonstrate NumPy
arrays creation using array () function.
Aim:
To Write a program to create, display, append, insert and reverse the
order of the items in the array. Python Program to demonstrate NumPy
arrays creation using array () function.
Description:
Creating an array: The np.array() function is used to create a NumPy array
from a list.
Displaying the array: We simply print the array using print().
Appending an element: The np.append() function appends a new element
at the end of the array.
Inserting an element: The np.insert() function inserts an element at a
specific index. In the example, 10 is inserted at index 2.
Reversing the array: The slicing method [::-1] is used to reverse the array.
Program:
Output:
19. Write a program to add, transpose and multiply two matrices.
Aim: To write a program to add, transpose and multiply two matrices.
Description:
In Python, arrays can be created using the array module. However,
Python's built-in list type provides more functionality and is more commonly
used in practice.
The Array can be created in Python by importing the array module to the
python program.
Program:
Output:
Enter the dimensions of Matrix A (rows x columns):
Number of rows in Matrix A: 2
Number of columns in Matrix A: 2
Enter the dimensions of Matrix B (rows x columns):
Number of rows in Matrix B: 2
Number of columns in Matrix B: 2
Enter the elements for a 2x2 matrix:
Element at position (1, 1): 1
Element at position (1, 2): 2
Element at position (2, 1): 3
Element at position (2, 2): 4
Enter the elements for a 2x2 matrix:
Element at position (1, 1): 1
Element at position (1, 2): 2
Element at position (2, 1): 3
Element at position (2, 2): 4
Resultant Matrix (A x B):
[7, 10]
[15, 22]
Resultant Matrix (A + B):
[2, 4]
[6, 8]
Resultant Transpose ( A' ):
[1, 3]
[2, 4]
20. Write python program to check whether a JSON string contains
complex object or not.
Aim: To Write python program to check whether a JSON string contains
complex object or not.
Description:
JSON (JavaScript Object Notation) is a lightweight, text-based format for
storing and exchanging data. It is easy for humans to read and write, and
easy for machines to parse and generate. JSON is primarily used for
transmitting data in web applications between a server and a client, and it
is language-independent, though it is often used in JavaScript
environments. Python provides built-in support for working with JSON data
through the json module.
In Python, JSON can be used to:
Parse JSON data (convert JSON strings to Python objects).
Convert Python objects to JSON strings (serialize data for transmission or
storage).
JSON and Python Data Types
In Python, the json module helps convert between Python's built-in data
types and their JSON equivalents:
-----------------------------------------------------------------------------------------
Python dictionaries (dict) map to JSON objects.
Python lists (list) map to JSON arrays.
Python strings (str) map to JSON strings.
Python integers (int) and floats (float) map to JSON numbers.
Python True/False maps to JSON true/false.
Python None maps to JSON null.
Working with JSON in Python
1. Converting Python objects to JSON (Serialization)
You can use the json.dumps() function to serialize a Python object into a
JSON string.
Program:
Output:
JSON 1 contains complex object: True
JSON 2 contains complex object: False
JSON 3 contains complex object: True
21. Write a Python program to create a class that represents a shape.
Include methods to calculate its area and perimeter. Implement
subclasses for different shapes like circle, triangle, and square
Aim:
To Write a Python program to create a class that represents a shape. Include
methods to calculate its area and perimeter. Implement subclasses for different
shapes like circle, triangle, and square
Description:
Shape Class: This is the base class with empty methods area() and
perimeter(). These methods are meant to be overridden by subclasses.
Circle Class: Inherits from Shape, has an __init__ method to initialize the
radius, and provides implementations for calculating the area and perimeter.
Triangle Class: Inherits from Shape, has an __init__ method for three sides
of the triangle, and uses Heron’s formula to calculate the area.
Square Class: Inherits from Shape, has an __init__ method to initialize the
side, and provides methods for area and perimeter.
Area: side2\text{side}^2side2
Perimeter: 4×side4 \times \text{side}4×side
Program:
Output: