0% found this document useful (0 votes)
6 views

Python Lab Manual

The document provides detailed instructions on downloading and installing Anaconda and Python on Windows, as well as launching Jupyter Notebook and Spyder. It includes examples of using the input() and print() functions in Python, along with programs to find the largest number among three inputs, display prime numbers within a range, and swap two numbers without a temporary variable. The document serves as a comprehensive guide for beginners in setting up their Python environment and understanding basic programming concepts.

Uploaded by

smtharunk
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Python Lab Manual

The document provides detailed instructions on downloading and installing Anaconda and Python on Windows, as well as launching Jupyter Notebook and Spyder. It includes examples of using the input() and print() functions in Python, along with programs to find the largest number among three inputs, display prime numbers within a range, and swap two numbers without a temporary variable. The document serves as a comprehensive guide for beginners in setting up their Python environment and understanding basic programming concepts.

Uploaded by

smtharunk
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

1.

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:

Anaconda is a powerful and popular platform that simplifies package


management and deployment of Python and R data science environments. If
you are a data scientist, analyst, or developer working on Windows, installing
Anaconda can be a game-changer. We will walk you through the process of
how to install Anaconda for Windows.

Step 1: Download Anaconda

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.

Recent days it show like this

User need to provide email to download distributed. Type email and click on
submit button.
Click on next button.

Just click on I Agree button.


Select radio button of “Just Me ( recommended ).

It show required path defaulty and click button next then it will started
installation.
Installation successfully.

Finally screen.

After completion of anaconda installation then we need to step in to the


launching of JUPTER NOTEBOOK and SPYDER.
Running the Jupyter Notebook
 Launching Jupyter Notebook App

The Jupyter Notebook App can be launched by clicking on the Jupyter


Notebook icon installed by Anaconda in the start menu (Windows) or by typing
in a terminal (cmd on Windows):

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.

To start Spyder, first open Anaconda Navigator:

Windows: You'll find Anaconda Navigator in the Start menu.


Then, click the Launch button below the Spyder icon on the Navigator Home
tab:

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

Aim: To 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.

Step 1 — Downloading the Python Installer


1. Go to the official Python download page for Windows.
2. Find a stable Python 3 release. This tutorial was tested with Python version 3.12.4.
3. Click the appropriate link for your system to download the executable file: Windows
installer (64-bit) or Windows installer (32-bit).

Step 2 — Running the Executable Installer


1. After the installer is downloaded, double-click the .exe file, for example python-
3.12.4-amd64.exe, to run the Python installer.
2. Select the Install launcher for all users checkbox, which enables all users of the
computer to access the Python launcher application.
3. Select the Add python.exe to PATH checkbox, which enables users to launch Python
from the command line.
4. If you’re just getting started with Python and you want to install it with default
features as described in the dialog, then click Install Now and go to Step 4 - Verify the
Python Installation. To install other optional and advanced features, click Customize
installation and continue.
5. The Optional Features include common tools and resources for Python and you can
install all of them, even if you don’t plan to use them.
Select some or all of the following options:

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

8. Click Install to start the installation.


9. After the installation is complete, a Setup was successful message displays
Step 3 — Adding Python to the Environment Variables (optional)

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

 C:\Users\Sammy\AppData\Local\Programs\Python\Python312: if you didn’t


select Install for all users during installation, then the directory will be in the Windows
user path

Note that the folder name will be different if you installed a different version, but will still
start with Python.

1. Go to Start and enter advanced system settings in the search bar.


2. Click View advanced system settings.
3. In the System Properties dialog, click the Advanced tab and then click Environment
Variables.
4. Depending on your installation:

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

Step 4 — Verify the Python Installation

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.

Enter the following command in the command prompt:


python --version

An example of the output is:


Output
Python 3.10.10

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.

The general format is:


input([prompt])

# Both input values are converted into integer type


Program:

num1 = int (input("Enter first number: "))


num2 = int(input("Enter second number: "))
sum = num1 + num2
print ('The sum of ', num1, ' and ', num2, ' is ',sum)

OUTPUT:
Enter the first number: 10
Enter second number: 30
The sum of 10 and 30 is 40

# Both input values are converted into float type


Program:

num1 = float (input("Enter first number: "))


num2 = float(input("Enter second number: "))
sum = num1 + num2
print ('The sum of ', num1, ' and ', num2, ' is ',sum)

OUTPUT:
Enter the first number: 10.5
Enter second number: 30.5
The sum of 10 and 30 is 41.0

Get multiple input values from a user in one line


In Python, we can accept two or three values from the user in
one input() call.

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.

The general form of print () function is:


print ( )
print (value/expr)
print (value, ...., sep=' ', end='\n', file=sys.stdout, flush=False)

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)

print("I Learn Python", "with SKILL ENHANCEMENT COURSE")


print("I Learn Python"+"with SKILL ENHANCEMENT COURSE ")
print('H','e','l','l','o',sep='-')

print("My", "name", "is", "Lakshman", sep="*")

print("My name is Lakshman", end = ', ')


print("M. Tech.,")
print("I am in SVPCET COLLEGE", end = ', ')
print("PUTTUR,TIRUPATHI DIST, AP, India.")

OUTPUT:
The sum of two numbers is 50

50 is the sum of 20 and 30

I Learn Python with SKILL ENHANCEMENT COURSE

I Learn Pythonwith SKILL ENHANCEMENT COURSE

H-e-l-l-o

My*name*is*Lakshman

My name is Lakshman, M. Tech.,

I am in SVPCET COLLEGE, PUTTUR,TIRUPATHI DIST, AP, India.


4. Write a program to find the largest element among three Numbers

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:

Enter first number: 56

Enter second number: 42

Enter third number: 75

The largest number is 75

Program: Program:

x=2 lis = [100, 43, 400, 63, 65]


y=5 lis.sort()
z=8 print("Largest number in the list is:", lis[-1])
print(max(x, y, z)) print("Largest number in the list is:", max (lis))

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

Aim: To write a Program to display all prime numbers within an interval

Description: A prime number is a natural number which is greater than 1 and


has no positive divisor other than 1 and itself, such as 2, 3, 5, 7, 11, 13, and so
on.

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

Before runnning this program install sympy package.

NOTE: pip install sympy

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.

Aim: To Write a program to swap two numbers without using a temporary


variable.

DESCRIPTION:

Swapping the values of two variables without using a temporary variable is


important in situations where you want to minimize memory usage or code
complexity.

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:

Enter value of first variable: 45 Enter value of first variable: 39


Enter value of second variable: 86 Enter value of second variable: 78
a is: 86 b is: 45 a is: 78 b is: 39

PROGRAM:

a=int(input("Enter value of first variable: "))


b=int(input("Enter value of second variable: "))
c=int(input("Enter value of second variable: "))
a,b,c = c,a,b
print("a is:",a," b is:",b, " c is:",c)

OUTPUT:

Enter value of first variable: 75


Enter value of second variable: 86
Enter value of second variable: 49
a is: 49 b is: 75 c is: 86
7. Demonstrate the following Operators in Python with suitable examples. i)
Arithmetic Operators ii) Relational Operators iii) Assignment Operatorsiv)
Logical Operators v) Bit wise Operators vi) Ternary Operator vii) Membership
Operators viii) Identity Operators

AIM: To Demonstrate the following Operators in Python with suitable


examples. i) Arithmetic Operators ii) Relational Operators iii) Assignment
Operatorsiv) Logical Operators v) Bit wise Operators vi) Ternary Operator vii)
Membership Operators viii) Identity Operators

DESCRIPTION:
Operators in a programming language are used to perform various operations
on values and variables.

TYPES OF PYTHON OPERATORS


Python language supports various types of operators, which are:
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators

Arithmetic Operators

 Mathematical operations including addition, subtraction, multiplication, and


division are commonly carried out using Python arithmetic operators.
 They are compatible with integers, variables, and expressions.
 In addition to the standard arithmetic operators, there are operators for
modulus, exponentiation, and floor division

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

Python Comparison Operators

 To compare two values, Python comparison operators are needed.


 Based on the comparison, they produce a Boolean value (True or False).

Operator Name Example


== Equal 4 == 5 is not true.
!= Not Equal 4 != 5 is true.
> Greater Than 4 > 5 is not true
< Less Than 4 < 5 is true
>= Greater than or Equal to 4 >= 5 is not true.
<= Less than or Equal to 4 <= 5 is true.
PROGRAM:
a=4
b=5
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 : False
a != b : True
a > b : False
a < b : True
a >= b : False
a <= b : True

Python Assignment Operators

 Python assignment operators are used to assign values to variables in


Python.
 The single equal symbol (=) is the most fundamental assignment
operator.
 It assigns the value on the operator's right side to the variable on the
operator's left side.

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

Python Bitwise Operators

 Python bitwise operators execute operations on individual bits of binary


integers.
 They work with integer binary representations, performing logical
operations on each bit location.
 Python includes various bitwise operators, such as AND (&), OR (|), NOT
(), XOR (), left shift (), and right shift (>>).

Operator Name Example


& Binary AND Sets each bit to 1 if both bits are 1
| Binary OR Sets each bit to 1 if one of the two bits is 1
^ Binary XOR Sets each bit to 1 if only one of two bits is 1
~ Binary Ones Complement Inverts all the bits
~ Binary Ones Complement Inverts all the bits
<< Binary Left Shift Shift left by pushing zeros in from the right
and let the leftmost bits fall off
>> Binary Right Shift Shift right by pushing copies of the leftmost
bit in from the left, and let the rightmost bits
fall off

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

Python Logical Operators

 Python logical operators are used to compose Boolean expressions and


evaluate their truth values.
 They are required for the creation of conditional statements as well as for
managing the flow of execution in programs.
 Python has three basic logical operators: AND, OR, and NOT.

Operator Description Example


and Logical AND If both of the operands are true then the (a and b) is
condition becomes true. true.
or Logical OR If any of the two operands is non-zero then (a or b) is true.
the condition becomes true.
not Logical NOT Used to reverse the logical state of its Not(a and b) is
operand false.

PROGRAM:
x=5
y = 10
if x > 3 and y < 15:
print("Both x and y are within the specified range")

OUTPUT:

Both x and y are within the specified range

Python Membership Operators

 Python membership operators are used to determine whether or not a


certain value occurs within a sequence.
 They make it simple to determine the membership of elements in
various Python data structures such as lists, tuples, sets, and strings.
 Python has two primary membership operators: the in and not in
kimioperators.

Operator Description Example


in Evaluates to true if it finds a variable in x in y, here in results in a 1 if x
the specified sequence and false is a member of sequence y.
otherwise.
not in Evaluates to true if it does not find a x not in y, here not in results in
variable in the specified sequence and a 1 if x is not a member of
false otherwise. sequence y.

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

 Python identity operators are used to compare two objects' memory


addresses rather than their values.
 If the two objects refer to the same memory address, they evaluate to
True; otherwise, they evaluate to False.
 Python includes two identity operators: the is and is not operators.

Operator Description Example


is Evaluates to true if the variables on either x is y, here are results in
side of the operator point to the same 1 if id(x) equals id(y)
object and false otherwise
is not Evaluates to false if the variables on either x is not y, there are no
side of the operator point to the same results in 1 if id(x) is not
object and true otherwise equal to id(y).

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)

Reading Complex Number From User


We can read complex number directly from user using built-in function input().
Since function input() returns STRING we must convert result to complex
using function complex().
PROGRAM:
a = complex(input('Enter complex number:'))
print('Given complex number is:',a)
OUTPUT:
Enter complex number:22+8j

Finding Conjugate of Complex Number


Complex data type has built-in method called conjugate() to find conjugate of
complex number.
PROGRAM:
a = complex(input('Enter complex number:'))
print('Given complex number is:',a.conjugate())

OUTPUT:
Enter complex number:30+42j
Given complex number is: (30-42j)

PROGRAM:

a = complex(input('Enter complex number:'))


b = complex(input('Enter complex number:'))
print('Addition of complex numbers :',a+b)
print('Subtraction of complex numbers :',a-b)
print('Multiplication of complex numbers :',a*b)
print('Division of complex numbers :',a/b)
print('Division of complex numbers :',a%b)

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.

Syntax of for Loop


for x in sequence:
# body of the for loop

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

range(start, stop, step)

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.

Step: Optional. Use this number to specify the incrementation or


decrementation of your sequence, if not a positive 1 (default).

PROGRAM: PROGRAM: PROGRAM: PROGRAM:

for x in range(5): for x in range(1,5): for x in range(1,14,3): for x in range(10,0,-2):


print(x) print(x) print(x) print(x)

OUTPUT: OUTPUT: OUTPUT: OUTPUT:


0 1 1 10
1 2 4 8
2 3 7 6
3 4 10 4
4 13 2

A While loop is used to repeat a section of code an unknown number of times until
a specific condition is met.

Syntax of while Loop


initialization
while test_Condition:
# body of the loop
# statements we want to execute
Expression_inc/dec
PROGRAM:
num = int(input(" Enter a number : "))
print("Table of: ")
for a in range(1,11):
print(num,'x',a,'=',num*a)
OUTPUT:
Enter a number : 8
Table of:
8x1=8
8 x 2 = 16
8 x 3 = 24
8 x 4 = 32
8 x 5 = 40
8 x 6 = 48
8 x 7 = 56
8 x 8 = 64
8 x 9 = 72
8 x 10 = 80
10. Aim: To Write a program to define a function with multiple return values.
Description :

Types of function arguments


There are various ways to use arguments in a function. In Python, we have the
following 4 types of function arguments.
1. Default argument
2. Keyword arguments (named arguments)
3. Positional arguments
4. Arbitrary arguments (variable-length arguments *args and **kwargs)
sometimes, there is a situation where we need to pass multiple arguments to
the function. Such types of arguments are called arbitrary arguments or
variable-length arguments.

We use variable-length arguments if we don’t know the number of arguments


needed for the function in advance.
Returning Results from a Function
We can return one or more results or output from a function using the keyword
return. The result can be an integer, float, string, list or any other type.
You can also return multiple values from a function. Use the return statement
by separating each expression by a comma.
Program:

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.

Note: find() method cant find Case Senstitive strings


Using the index() Method

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

Enter a SentenceI am Studying in svpcet college

Enter a string to find in above sentencesvpcet

Substring found at index: 17


Using Regular Expressions
For more advanced substring matching, regular expressions can be used. The
re-module in Python provides powerful tools for pattern matching. Here’s an
example of using regular expressions to check if a string contains a substring:
PROGRAM:

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.

Declaration Syntax of a Dictionary in Python


dictionary_name = {key:value, key:value,....}
Copy

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

Sum all the items in a given dictionary


Summing all items in a dictionary is a task that can be useful for statistical
analysis, inventory calculations, or aggregating any numerical data that is stored as
dictionary values.
Program:

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.

 Area: π×radius2\pi \times \text{radius}^2π×radius2


 Perimeter: 2×π×radius2 \times \pi \times \text{radius}2×π×radius

Triangle Class: Inherits from Shape, has an __init__ method for three sides
of the triangle, and uses Heron’s formula to calculate the area.

 Area: s(s−a)(s−b)(s−c)\sqrt{s(s-a)(s-b)(s-c)}s(s−a)(s−b)(s−c) where sss is the


semi-perimeter (a+b+c)/2(a + b + c) / 2(a+b+c)/2
 Perimeter: Sum of the three sides a+b+ca + b + ca+b+c

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:

You might also like