Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
10 views93 pages

Ict Python Solved Lab Manual by Herry

Uploaded by

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

Ict Python Solved Lab Manual by Herry

Uploaded by

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

PYTHON PROGRAMMING

(DI02032011)

LAB MANUAL

DEPARTMENT OF INFORMATION & COMMUNICATION TECHNOLOGY

DR. S. & S.S. GHANDHY COLLEGE OF ENGINEERING AND TECHNOLOGY SURAT

MAJURA GATE, SURAT - 395001


Subject: Python Programming
Sub Code: DI02032011

Lab Manual
Certificate

This is to certify that Mr./Ms ………………………………………………………………………………..

Enrolment No. ………….…………………… of …………….………. Semester of Diploma

In ................................................................................................................. …………………………………….of

………………………………………………………………………. (GTU Code) has satisfactorily completed the term work

in course ..................................................................................................... for the academic

year:….…………………………………………….. Term: Odd/Even prescribed in the GTU curriculum.

Place:………………..

Date: …………………..

Signature of Course Faculty Head of the Department


Continuous Assessment Sheet
Students Name: Enrolment No:
Subject Name with code:

Sr
Practical Outcome/Title of Date TS WQ CO IN TOTAL SIGN
No.
experiment (5) (5) (5) (5) (20)
Prepare flowchart and algorithm for a given
1. problem.(Following are the sample programs.
Faculty can select any other similar programs for
the practice of the students.)
i.Find the sum of two given numbers.
ii.Find a maximum out of two given numbers.
iii.Find whether a given number is odd or even.
iv.Find a maximum out of three given numbers.

A) Write a Program to print your name, mobile


2. number, and date of birth.
B) Develop a Program to identify data-types in
python.
A) Create a Program to read three numbers from
3. the user and find the average of the numbers.
B) Develop a Program that can calculate simple
interest and compound interest on given data.
C) Write a Program to convert temperature from
Fahrenheit to Celsius unit using eq: C=(F-32)/1.8
A) Identify whether the scanned number is even or
4. odd and print an appropriate message.
B) Create a Program to find a maximum number
among the given threenumbers.
5. Develop a Program to demonstrate the basic
functionalities of a standard calculator.
A) Write a Python program to print 1 to 10
6. numbers using loops.
B) Write a Program to show whether the entered
number is prime or not.
Write a Program to display the following patterns.
7. A) B)
1 *****
12 ****
123 ***
1234 **
12345 *

Create a User-defined function to print the


8. Fibonacci series of 0 to N numbers.
(Where N is an integer number and passed as an
argument)
A) Develop a User-defined function to find the
9. factorial of a given number.
B) Write a Program using the function that reverses
the entered value.
Write a Program that determines whether a given
number is an‗Armstrong number‘ or a palindrome
10. using a user-defined function.
A) Write a Program to find the length of a string.
11. B) Write a Program to reverse words in a given
sentence.
C) Write a Program to check if a substring is
present in a given string.
D) Write a Program to count and display the
number of vowels,
consonants, uppercase, lowercase characters in a
string.
Develop Programs to perform the following list
operations.
12. A)To swap given two elements in a list.
B)To find the sum of elements in a list.
A)Given a List saved in variable: a = [1, 4, 9, 16,
25, 36, 49, 64, 81, 100]. Write one line of Python
13. that takes this list and makes a new list that has
only the even elements of this list in it.
B)Create a List containing the square of all odd
numbers from range 1 to 10.
14 Write a Program to demonstrate the set functions
and operations.

TS : TECHNICAL SKILL
WQ: WORK QUALITY
CO: COLLABORATION
IN: INITIATIVE
Practical-1
Prepare flowchart and algorithm for a given problem.

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Aim:- To prepare flowchart and algorithm for given problem
statements.

Theory:-
An introduction to Algorithm

What is Algorithm?

The word Algorithm means ―a process or set of rules to be followed in calculations or


other problem-solving operations‖. Therefore Algorithm refers to a set of rules/instructions that
step-by-step define how a work is to be executed upon in order to get the expected results.

It can be understood by taking an example of cooking a new recipe. To cook a new


recipe, one reads the instructions and steps and execute them one by one, in the given sequence.
The result thus obtained is the new dish cooked perfectly. Similarly, algorithms help to do a
task in programming to get the expected output.

The Algorithm designed are language-independent, i.e. they are just plain instructions
that can be implemented in any language, and yet the output will be the same, as expected.

How to Design an Algorithm?

In order to write an algorithm, following things are needed as a pre-requisite:

1. The problem that is to be solved by this algorithm.


2. The constraints of the problem that must be considered while solving the
problem.
3. The input to be taken to solve the problem.
4. The output to be expected when the problem the is solved.
5. The solution to this problem, in the given constraints.

Algorithm to add 3 numbers and print their sum:

Step 1. START

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Step 2. Declare 3 integer variables num1, num2 and num3.
Step 3. Take the three numbers, to be added, as inputs in variables num1, num2, and
num3 respectively.
Step 4. Declare an integer variable sum to store the resultant sum of the 3 numbers.
Step 5. Add the 3 numbers and store the result in the variable sum.
Step 6. Print the value of variable sum
Step 7. END

What is a Flowchart?

Flowchart is a graphical representation of an algorithm. Programmers often use it as a program-


planning tool to solve a problem. It makes use of symbols which are connected among them to
indicate the flow of information and processing. The process of drawing a flowchart for an
algorithm is known as ―flowcharting‖.
Basic Symbols used in Flowchart Designs
1. Terminal: The oval symbol indicates Start, Stop and Halt in a program‘s logic
flow. A pause/halt is generally used in a program logic under some error
conditions. Terminal is the first and last symbols in the flowchart.

2. Input/Output: A parallelogram denotes any function of input/output type.


Program instructions that take input from input devices and display output on
output devices are indicated with parallelogram in a flowchart.

3. Processing: A box represents arithmetic instructions. All arithmetic processes


such as adding, subtracting, multiplication and division are indicated by action
or process symbol.

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


4. Decision Diamond symbol represents a decision point. Decision based operations
such as yes/no question or true/false are indicated by diamond in flowchart.

5. Connectors: Whenever flowchart becomes complex or it spreads over more


than one page, it is useful to use connectors to avoid any confusions. It is
represented by a circle.

6. Flow lines: Flow lines indicate the exact sequence in which instructions are
executed. Arrows represent the direction of flow of control and relationship
among different symbols of flowchart.

7. Subroutine: This symbol is used for user defined function or sub


program.

8. Page Break:
When flowchart does not fit into single page then page break and page continue
symbols are used.
Page Break symbol indicate break in current page.

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


9. Page Continue
Page continue symbol indicate continue flowchart in another page.

Example : Draw a flowchart to input two numbers from user and display the largest of
two numbers

Exercise
Ex-1- Draw flowchart and write algorithm to Find the sum of two given numbers.
Ex-2- Draw flowchart and write algorithm to Find a maximum out of two given
numbers.
Ex-3- Draw flowchart and write algorithm to Find whether a given number is odd or
even.
Ex-4- Draw flowchart and write algorithm to Find a maximum out of three given
numbers.

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Ex-1- Draw flowchart and write algorithm to Find the sum of two given numbers
Flowchart:

Algorithm:
Step 1:Start

Step 2:Get num1,num2 from the user

Step 3:Sum=num1+num2

Step 4:Display/Print Sum

Step 5:End
Ex-2-Draw flowchart and write algorithm to Find maximum out of two given
numbers
Flowchart:

Input a,b

If a>b

Print a Print b
is max is max

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Algorithm:
Step 1:Start

Step 2:Get value of a,b from the user

Step 3:Check if a>b is true then go to step number 4,else go to step


number 5

Step 4:Print a is max

Step 5:Print b is max

Step 6:Stop
Ex-3- Draw flowchart and write algorithm to Find whether a given number is
odd or even
Flowchart:

Algorithm:

Step 1:Start

Step 2:Get Number from the user

Step 3:Check if Number%2==0 is true then go to step number 4 ,


else go to step number 5

Step 4:Display Even Number

Step 5:Display Odd Number

Step 6:End

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Ex-4- Draw flowchart and write algorithm to Find a maximum out of three given
numbers
Flowchart:

Algorithm:
Step 1:Start

Step 2:Read three numbers A,B,C from the user

Step 3:Check is A>B is true(yes) then go to step number 4,


else go to step number 5

Step 4:Check is A>C is true(yes) then go to step number 6,


else go to step number 8

Step 5:Check is B>C is true(yes) then go to step number 7,


else go to step number 8

Step 6:Print A is the largest number

Step 7:Print B is the largest number

Step 8:Print C is the largest number

SSGP SURAT Step 9:End


INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING
Practical-2 [A]

To create programs using print.

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Aim: To create programs using print.

Theory:-

Using the print() Function:

The print() function is used whenever you want to print text to the screen. Try the following
example in your Python shell:

> > > print(“Hello World!”)


When you press Enter, you should see the following:

Hello World!

Now that you know how to use the print() function, you can begin to work with the different
types of ‗ and ― (quotes) .

Try the examples:


> > > print(„This is a string using a single quote!‟)
This is a string using a single quote!
> > > print(“This is a string using a double quote!”)
This is a string using a double quote!
> > > print(“””This string has three quotes!
Look at what it can do!”””)
This string has three quotes
Look at what it can do!
In this example, you see that the single quote ( ' ) and double quote ( " ) are interchangeable.

However, when you want to work with a contraction, such as don ’ t , or if you want to quote
someone quoting something, observe what happens:

> > > print(“I said, “Don‟t do it”)

When you press Enter to execute the function, you will get the error message: SyntaxError:
invalid

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


syntax ( < pyshell#10 > , line 1).

There is a simple solution to this, known as an escape. Retry the preceding code, adding an
escape character to this string:

> > > print(“I said, \”Don‟t do it”)

I said, “Don‟t do it

Triple quote allows you to write some text on multiple lines, without being processed
until you close it with another triple quote. This technique is useful if you have a large
amount of data that you do not wish to print on one line, or if you want to create line breaks
within your code.
Here, in the next example, you write a poem using this method:
> > > print(“””Roses are red
Violets are blue
I just printed multiples lines
And you did too!”””)
Roses are red
Violets are blue
I just printed multiple lines
And you did too!
There is another way to print text on multiple lines using the newline ( \n ) escape character,
which is the most common of all the escape characters. I ‘ ll show it to you here briefly, and
come back to discuss it in more depth in a later chapter. Try this code out:

> > > print(“Roses are red \n Violets are blue \n


I just printed multiple
lines \n And you did too!”)
Roses are red
Violets are blue
I just printed multiple lines
And you did too!

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


To print several things at once, separate them by commas. Python will automatically insert
spaces between them. Below is an example and the output it produces.
print('The value of 3+4 is', 3+4)
print('A', 1, 'XYZ', 2)
The value of 3+4 is 7
A 1 XYZ 2

The print function will automatically advance to the next line. For instance, the following
will print on two lines:
print('On the first line')
print('On the second line')
On the first line
On the second line
There is an optional argument called end that you can use to keep the print function from
advancing to the next line. Here is an example:

print('On the first line', end='')


print('On the second line')
On the first lineOn the second line

Use of separator ‘sep’ in print function


‗sep‘ stands for separator and is assigned a single space (' ') by default. It determines the
value to join elements with.
It has to be either a string or None, but the latter has the same effect as the default space:

>>> print('hello', 'world', sep=None)


hello world
>>> print('hello', 'world', sep=' ')
hello world
>>> print('hello', 'world')
hello world

If you wanted to suppress the separator completely, you‘d have to pass an empty string ('')
instead:

>>> print('hello', 'world', sep='')


helloworld

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


You may want print() to join its arguments as separate lines. In that case, simply pass the
escaped newline character described earlier:

>>>
>>> print('hello', 'world', sep='\n')
hello
world
A more useful example of the sep parameter would be printing something like file paths:

>>>
>>> print('home', 'user', 'documents', sep='/')
home/user/documents

Program:- Create a program to print your name, mobile number,


and date of birth.
First method:
print("Name=ABC)
print("Mobile No.= 9122222222”)
print("Date of birth=22-01-2003")

Second method:
name="ABC"
mobile_no="9122222222"
dob="22-01-2003"

print("Name=",name)
print("Mobile No.=",mobile_no)
print("Date of birth=",dob)

Output:
Name= ABC
Mobile No.= 9122222222
Date of birth= 22-01-2003

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Practical-2 [B]
To Develop a program to identify data-types in python.

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Aim: To Develop a program to identify data-types in python.
Theory:

Data Types
Every value belongs to a specific data type in Python. Data type identifies the type of data
values a variable can hold and the operations that can be performed on that data.

● Number
Number data type stores numerical values only. It is further classified into three different
types: int, float and complex.

Boolean data type (bool) is a subtype of integer. It is a unique data type, consisting of two
constants, True and False. Boolean True value is non-zero, non-null and non-empty. Boolean
False is the value zero.

We can try to execute few statements in interactive mode to determine the data type of the
variable using built-in function type().
Example
>>> num1 = 10
>>> type(num1)
<class 'int'>
>>> num2 = -1210
>>> type(num2)

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


<class 'int'>
>>> var1 = True
>>> type(var1)
<class 'bool'>
>>> float1 = -1921.9
>>> type(float1)
<class 'float'>
>>> float2 = -9.8*10**2
>>> print(float2, type(float2))
-980.0000000000001 <class 'float'>
>>> var2 = -3+7.2j
>>> print(var2, type(var2))
(-3+7.2j) <class 'complex'>

● Sequence
A Python sequence is an ordered collection of items, where each item is indexed by an integer.
The three types of sequence data types available in Python are Strings, Lists and Tuples. We
will learn about each of them in detail in later chapters. A brief introduction to
these data types is as follows:
(A) String
String is a group of characters. These characters may be alphabets, digits or special haracters
including spaces. String values are enclosed either in single quotation marks (e.g., ‗Hello‘) or
in double quotation marks (e.g., ―Hello‖). The quotes are not a part of the string, they are
used to mark the beginning and end of the string for the interpreter. For example,
>>> str1 = 'Hello Friend'
>>> str2 = "452"
We cannot perform numerical operations on strings, even when the string contains a numeric
value, as in str2.
(B) List
List is a sequence of items separated by commas and the items are enclosed in square
brackets [ ].
Example
#To create a list
>>> list1 = [5, 3.4, "New Delhi", "20C", 45]

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


#print the elements of the list list1
>>> print(list1)
[5, 3.4, 'New Delhi', '20C', 45]
(C) Tuple
Tuple is a sequence of items separated by commas and items are enclosed in parenthesis ( ).
This is unlike list, where values are enclosed in brackets [ ]. Once created, we cannot change
the tuple.
Example
#create a tuple tuple1
>>> tuple1 = (10, 20, "Apple", 3.4, 'a')
#print the elements of the tuple tuple1
>>> print(tuple1)
(10, 20, "Apple", 3.4, 'a')

● Set
Set is an unordered collection of items separated by commas and the items are enclosed in
curly brackets { }. A set is similar to list, except that it cannot have duplicate entries. Once
created, elements of a set cannot be changed.
Example
#create a set
>>> set1 = {10,20,3.14,"New Delhi"}
>>> print(type(set1))
<class 'set'>
>>> print(set1)
{10, 20, 3.14, "New Delhi"}
#duplicate elements are not included in set
>>> set2 = {1,2,1,3}
>>> print(set2)
{1, 2, 3}

● None
None is a special data type with a single value. It is used to signify the absence of value in a
situation. None supports no special operations, and it is neither False nor 0 (zero).
Example

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


>>> myVar = None
>>> print(type(myVar))
<class 'NoneType'>
>>> print(myVar)
None

● Mapping
Mapping is an unordered data type in Python. Currently, there is only one standard mapping
data type in Python called dictionary.
(A) Dictionary
Dictionary in Python holds data items in key-value pairs. Items in a dictionary are enclosed in
curly brackets { }. Dictionaries permit faster access to data. Every key is separated from its
value using a colon (:) sign. The key : value pairs of a dictionary can be accessed using the
key. The keys are usually strings and their values can be any data type. In order to access any
value in the dictionary, we have to specify its key in square brackets
[ ].
Example
#create a dictionary
>>> dict1 = {'Fruit':'Apple',
'Climate':'Cold', 'Price(kg)':120}
>>> print(dict1)
{'Fruit': 'Apple', 'Climate': 'Cold',
'Price(kg)': 120}
>>> print(dict1['Price(kg)'])
120

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Program:- Create a program to demonstrate different number datatypes in
Python
i=7
c=24+8j
f=7.01
m=[1,2,3]
t=(5,2,4)
k={'a',7,9,'tree'}
s='HELLO EVERYONE!!'
b=True
d={'a':1,'b':2}
print("the value of i is:",i,'its type is:',type(i))
print("the value of f is:",f,'its type is:',type(f))
print("the value of c is:",c,'its type is:',type(c))
print("the value of s is:",s,'its type is:',type(s))
print("the value of b is:",b,'nits type is:',type(b))
print('the value of m is:',m ,'and its type is:',type(m))
print('the value of t is:',t ,'and its type is:',type(t))
print('the value of k is:',k ,'and its type is:',type(k))
print('the value of d is:',d ,'and its type is:',type(d))
Output:
the value of i is: 7 its type is: <class 'int'>
the value of f is: 7.01 its type is: <class 'float'>
the value of c is: (24+8j) its type is: <class 'complex'>
the value of s is: HELLO EVERYONE!! its type is: <class 'str'>
the value of b is: True nits type is: <class 'bool'>
the value of m is: [1, 2, 3] and its type is: <class 'list'>
the value of t is: (5, 2, 4) and its type is: <class 'tuple'>
the value of k is: {9, 'tree', 7, 'a'} and its type is: <class 'set'>
the value of d is: {'a': 1, 'b': 2} and its type is: <class 'dict'>

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Practical-3[A]
Create a program to read three numbers from the user
and find the average of the numbers.

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Aim:- Create a program to read three numbers from the user and find the
average of the numbers.

num1=int(input("Enter a number:"))
num2=int(input("Enter a number:"))
num3=int(input("Enter a number:"))

average=(num1+num2+num3)/3

print("Average of",num1,num2,num3,"is:",average)

Output:
Enter a number:10
Enter a number:20
Enter a number:30
Average of 10 20 30 is: 20.0

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Practical-3[B]
Develop a program that can calculate simple interest
and compound interest on given data.

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Aim:- Develop a program that can calculate simple interest and
compound interest on given data.

Formulae:
Simple Interest,
SI = P × (R/100) × T
Where P= Principal amount
R=Rate of interest
T=No. of years
Compound Interest,
CI = P( 1 + R/100)T – P
Where P=Principal amount
R= Rate of interest
T=No. of years

Program:
p=int(input("Enter principal amount="))
r=int(input("Enter rate of interest="))
t=int(input("Enter number of years="))

si=p*(r/100)*t
ci=p*(1+(r/100))**t-p

print("Simple interest=",si)
print("Compound interest=",ci)
Output:
Enter principal amount=1000
Enter rate of interest=5
Enter number of years=2
Simple interest= 100.0
Compound interest= 102.5

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Practical-3[C]
Write a program to convert temperature from
Fahrenheit to Celsius unit using eq: C=(F-32)/1.8

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Aim: Write a program to convert temperature from Fahrenheit to
Celsius unit using eq: C=(F-32)/1.8

Program:

f=int(input("Enter temperature in Fahrenheit:"))

c=(f-32)/1.8

print("Temperatur in Celcious=%0.2f" %c)

Output:
Enter temperature in Fahrenheit:23
Temperatur in Celcious=-5.00

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Practical-4[A]
Identify whether the scanned number is even or odd
and print an appropriate message.

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Aim: Write a program to identify whether the scanned number is
even or odd and print an appropriate message.

Theory:
If..else statement :
In programming, concept of decision making or selection is implemented
with the help of if..else statement.
The syntax of if statement is:
if condition:
statement(s)

If the condition is true, then the indented statement(s) are executed. The
indentation implies that its execution is dependent on the condition. There is
no limit on the number of statements that can appear as a block under the if
statement.
Example
age = int(input("Enter your age "))
if age >= 18:
print("Eligible to vote")

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


A variant of if statement called if..else statement allows us to write two alternative
paths and the control condition determines which path gets executed. The syntax
for if..else statement is as follows.
if condition:
statement(s)
else:
statement(s)

Let us now modify the example on voting with the condition that if the age entered
by the user is greater than 18, then to display that the user is eligible to vote.
Otherwise display that the user is not eligible to vote.
age = int(input("Enter your age: "))
if age >= 18:
print("Eligible to vote")
else:
print("Not eligible to vote")

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Program:

n=int(input("Enter an integer number:"))

if n%2==0:
print(n,"is an even number")
else:
print(n,"is an odd number")

Output:
Enter an integer number:24
24 is an even number

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Practical-4[B]
Create a program to find a maximum number among
the given three numbers.

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Aim: Create a program to find a maximum number among the
given three numbers.

Theory:
if..elif statement
Many a times there are situations that require multiple conditions to be checked
and it may lead to many alternatives. In such cases we can chain the conditions
using if..elif (elif means else..if).
The syntax for a selection structure using elif is as shown below.
if condition:
statement(s)
elif condition:
statement(s)
elif condition:
statement(s)
else:
statement(s)

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


In some cases there exists an if..else condition within the elif block.
This is called nested if. We can have many levels of nesting inside if..else
statements.
A nested if is an if statement that is the target of another if statement.
Nested if statements mean an if statement inside another if statement. Python
allows us to nest if statements within if statements. i.e, we can place an if
statement inside another if statement.
Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Program:

n1=int(input("Enter a number:"))
n2=int(input("Enter a number:"))
n3=int(input("Enter a number:"))

if(n1>n2)and (n1>n3):
print(n1,"is largest number")
elif (n2>n1) and (n2>n3):
print(n2,"is largest number")
else:
print(n3,"is largest number")

Output:
Enter a number:10
Enter a number:20
Enter a number:30
30 is largest number

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Practical-5
Develop a program to demonstrate the basic
functionalities of a standard calculator.

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Aim: Develop a program to demonstrate the basic functionalities
of a standard calculator.

Program:
a=float(input("Enter a number:"))
b=float(input("Enter a number:"))
print("Enter 1 for addition,2 for subtraction,3 for multiplication and 4 for
division:")
c=int(input("Choice:"))

if c==1:
print("Addition of a and b=",a+b)
elif c==2:
print("Subtraction of b from a=",a-b)
elif c==3:
print("Multiplication of a and b is=",a*b)
elif c==4:
print("a divided by b=",a/b)
else:
print("Invalid choice")
Output:
Enter a number:10
Enter a number:2
Enter 1 for addition,2 for subtraction,3 for multiplication and 4 for division:
Choice:3
Multiplication of a and b= 20.0

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Practical-6[A]
Write a python program to print 1 to 10 numbers
using loops.

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Aim: Write a python program to print 1 to 10 numbers using
loops.

Theory:
Python programming language provides following types of loops to handle
looping requirements. Python provides three ways for executing the loops. While
all the ways provide similar basic functionality, they differ in their syntax and
condition checking time.
While Loop:
In python, while loop is used to execute a block of statements repeatedly until a
given a condition is satisfied. And when the condition becomes false, the line
immediately after the loop in program is executed.
while expression:
statement(s)

All the statements indented by the same number of character spaces after a
programming construct are considered to be part of a single block of code. Python
uses indentation as its method of grouping statements.

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Example:
count=0
while (count<3):
count=count+1
print(“hello world!”)
Output:
hello world!
hello world!
hello world!
The ‘For’ Loop:
The for statement is used to iterate over a range of values or a sequence. With
every iteration of the loop, the control variable checks whether each of the
values in the range have been traversed or not. When all the items in the range
are exhausted, the statements within loop are not executed; the control is then
transferred to the statement immediately following the for loop.
Syntax of the For Loop
for <control-variable> in <sequence/ items in range>:
<statements inside body of the loop>

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Example:
n=4
for i in range(0,n):
print(“hello world”)
Output:
hello world
hello world
hello world
The range() Function:
The range() is a built-in function in Python.
Syntax of range() function is:
range([start], [stop], [step])
It is used to create a list containing a sequence of integers from the given start
value upto stop value (excluding stop value), with a difference of the given step
value.
>>list(range(2, 10))
>>[2, 3, 4, 5, 6, 7, 8, 9]
>>range(0, -9, -1)
>>[0, -1, -2, -3, -4, -5, -6, -7, -8]

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Program:
Using for loop:
n=10
for i in range(1,n+1):
print(i)

Using while loop:


n=1
while (n<=10):
print(n)
n=n+1

Output:
for Loop
1
2
3
4
5
6
7
8
9
10
While Loop
1
2
3
4
5
6
7
8
9
10

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Practical-6[B]
Write a program to show whether the entered
number is prime or not.

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Aim: Write a program to show whether the entered number is
prime or not.

Program:
n=int(input("Enter a number:"))
flag=0
for i in range(2,int(n/2)):
if(n%i==0):
flag=1

if (flag==0):
print(n,"is prime number")
else:
print(n,"is not a prime number")

Output:
Enter a number:117
117 is not a prime number

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Practical-7
Create a program to display the given patterns.

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Aim: Create a program to display the given patterns.

Program:

(i)
1
12
123
1234
12345

n=int(input("Enter a number:"))
for i in range(1,n+1):
for j in range(1,i+1):
print(j,end=" ")
print("")

(ii)
*****
****
***
**
*
n=int(input("Enter a number:"))
for i in range(n,0,-1):
for j in range(1,i+1):
print("*",end=" ")
print("")

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Practical-8
Create a user-defined function to print the Fibonacci
series of 0 to N numbers. (Where N is an integer
number and passed as an argument)

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Aim: Create a user-defined function to print the Fibonacci series
of 0 to N numbers. (Where N is an integer number and
passed as an argument)

Theory:
Introduction to function:
In programming, the use of function is one of the means to achieve modularity
and reusability. Function can be defined as a named group of instructions that
accomplish a specific task when it is invoked. Once defined, a function can be
called repeatedly from different places of the program without writing all the
codes of that function every time, or it can be called from inside another function,
by simply writing the name of the function and passing the required parameters,
if any.
The Advantages of Function
Following are the advantages of using functions in a program:
• Increases readability, particularly for longer code as by using functions, the
program is better organised and easy to understand.
• Reduces code length as same code is not required to be written at multiple places
in a program. This als o makes debugging easier.
• Increases reusability, as function can be called from another function or another
program. Thus, we can reuse or build upon already defined functions and avoid
repetitions of writing the same piece of code.
• Work can be easily divided among team members and completed in parallel.

User Defined Functions


Taking advantage of reusability feature of functions, there is a large number of
functions already available in Python under standard library. We can directly call
these functions in our program without defining them. However, in addition to
the standard library functions, we can define our own functions while writing the
program. Such functions are called user defined functions. Thus, a function

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


defined to achieve some task as per the programmer's requirement is called a user
defined function.
Creating User Defined Function
A function definition begins with def (short for define).
The syntax for creating a user defined function is as follows:

• The items enclosed in "[ ]" are called parameters and they are optional. Hence,
a function may or may not have parameters. Also, a function may or may not
return a value.
• Function header always ends with a colon (:).
• Function name should be unique. Rules for naming identifiers also applies for
function naming.
• The statements outside the function indentation are not considered as part of
the function.
Example: Write a user defined function to add 2 numbers and display their sum.
#function definition
def addnum():
fnum = int(input("Enter first number: "))
snum = int(input("Enter second number: "))
sum = fnum + snum
print("The sum of ",fnum,"and ",snum,"is ",sum)
#function call
addnum()
Output:
Enter first number: 5
Enter second number: 6
The sum of 5 and 6 is 11

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Function Arguments and Parameters:
An argument is a value passed to the function during the function call which is
received in corresponding parameter defined in function header.
Example: Write a program using a user defined function that displays sum of
first n natural numbers, where n is passed as an argument.

#function header
def sumSquares(n): #n is the parameter
sum = 0
for i in range(1,n+1):
sum = sum + i
print("The sum of first",n,"natural numbers is:
",sum)
num = int(input("Enter the value for n: "))
#num is an argument referring to the value input by
the user
sumSquares(num) #function call

Program: Create a user-defined function to print the Fibonacci series of 0 to N


numbers. (Where N is an integer number and passed as an argument)

def fibo(n):
f1=0
f2=1
print(f1)
print(f2)
for i in range(2,n):
f3=f1+f2
f1=f2
f2=f3

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


print(f3)
num=int(input('Enter a number:'))
fibo(num)

Output:
Enter a number:12
0
1
1
2
3
5
8
13
21
34
55
89

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Practical-9[A]
Develop a user-defined function to find the factorial
of a given number.

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Aim: Develop a user-defined function to find the factorial of a
given number.

Theory:
Functions Returning Value
A function may or may not return a value when called. The return statement
returns the values from the function. In the examples given so far, the function
performs calculations and display result(s).They do not return any value. Such
functions are called void functions. But a situation may arise, wherein we need to
send value(s) from the function to its calling function.
This is done using return statement.
The return statement does the following:
• returns the control to the calling function.
• return value(s) or None.

Program:
def calcFact(num):
fact = 1
for i in range(num,0,-1):
fact = fact * i
return fact
num = int(input("Enter the number: "))
factorial=calcFact(num)
print(num,"!=",factorial,sep='')

Output:
Enter the number: 5
5!=120

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Practical-9[B]
Write a program using the function that reverses the
entered value.

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Aim: Write a program using the function that reverses the entered
value.

Program:
def reverse(n):
reversed_num = 0

while n!= 0:
digit = n%10
reversed_num = reversed_num * 10 + digit
n=n//10
return reversed_num
num=int(input("Enter a number:"))
ans=reverse(num)
print("Reversed number is=",ans)

Output:
Enter a number:96705
Reversed number is= 50769

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Practical-10
Write a program that determines whether a given
number is an armstrong number or a palindrome using
a user-defined function.

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Aim: Write a program that determines whether a given number is
an armstrong number or a palindrome using a user-defined
function.

What is Armstrong number?


Armstrong number is a number that is equal to the sum of cubes of its digits.
For example 0, 1, 153, 370, 371 and 407 are the Armstrong numbers.

What is a Palindrome Number?


A Palindrome no. is the number that remains the same when its digits get
reversed.

Ex: 15451, for example: If we take 131 and reverse it then after reversing the
number remains the same.

Program:
def armstrong(n):
sum=0
number=n
while n!= 0:
digit = n%10
sum=sum+digit**3
n=n//10
if(sum==number):
print(number, "is an Armstrong number")
else:
print(number, "is not an Armstrong number")
def palindrome(n):
rev_num=0
number=n

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


while n!= 0:
digit = n%10
rev_num=rev_num*10+digit
n=n//10
if(rev_num==number):
print(number, "is a Palindrome number")
else:
print(number, "is not a Palindrome number")

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

Output:
Enter a number:171
171 is not an Armstrong number
171 is a Palindrome number

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Practical-11[A]
Write a program to find the length of a string.

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Aim: Write a program to find the length of a string.

Theory:

 Strings
String is a sequence which is made up of one or more UNICODE characters.
Here the character can be a letter, digit, whitespace or any other symbol. A
string can be created by enclosing one or more characters in single, double or
triple quote.
Example 8.1
>>> str1 = 'Hello World!'
>>> str2 = "Hello World!"
>>> str3 = """Hello World!"""
>>> str4 = '''Hello World!''
 Accessing Characters in a String
Each individual character in a string can be accessed using a technique called
indexing. The index specifies the character to be accessed in the string and is
written in square brackets ([ ]). The index of the first character (from left) in the
string is 0 and the last character is n-1 where n is the length of the string. If we
give index value out of this range then we get an IndexError. The index must be
an integer (positive, zero or negative).
#initializes a string str1
>>> str1 = 'Hello World!'
#gives the first character of str1
>>> str1[0]
'H'
#gives seventh character of str1
>>> str1[6]
'W'
#gives error as index is out of range
>>> str1[15]
IndexError: string index out of range

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Python allows an index value to be negative also. Negative indices are used when
we want to access the characters of the string from right to left. Starting from right
hand side, the first character has the index as -1 and the last character has the
index –n where n is the length of the string.
>>> str1[-1] #gives first character from right
'!'
>>> str1[-12]#gives last character from right
'H'

 Traversing a String:
We can access each character of a string or traverse a string using for loop
and while loop.
(A) String Traversal Using for Loop:
str1 = 'Hello World!'
for ch in str1:
print(ch,end = '')
Output:
Hello World! #output of for loop
In the above code, the loop starts from the first character of the string str1
and automatically ends when the last character is accessed.
(B) String Traversal Using while Loop:
str1 = 'Hello World!'
index = 0
#len(): a function to get length of string

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


while index < len(str1):
print(str1[index],end = '')
index += 1
Output:
Hello World! #output of while loop
Here while loop runs till the condition index < len(str) is True, where index
varies from 0 to len(str1) -1.

Program: Write a program to find the length of a string including spaces.


str="Hello world!"
length=0
for ch in str:
length=length+1

print("length of string is",length)

Output:
length of string is 12

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Practical-11 [B]
Write a program to reverse words in a given sentence.

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Aim: Write a program to reverse words in a given sentence.

Theory:
 String methods
Strings come with a ton of methods, functions that return information about
the string or return a new string that is a modified version of the original. Here
are some of the most useful ones:
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
Returns the number of times a specified value occurs in a string
count()
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
Searches the string for a specified value and returns the position of where it
find() was found
format() Formats specified values in a string
format_map() Formats specified values in a string
Searches the string for a specified value and returns the position of where it
index() was found
Returns True if all characters in the string are alphanumeric
isalnum()
Returns True if all characters in the string are in the alphabet
isalpha()
Returns True if all characters in the string are ascii characters
isascii()
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Returns True if all characters in the string are whitespaces
isspace()
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
Returns a tuple where the string is parted into three parts
partition()
Returns a string where a specified value is replaced with a specified value
replace()
Searches the string for a specified value and returns the last position of
rfind() where it was found
Searches the string for a specified value and returns the last position of
rindex() where it was found
rjust() Returns a right justified version of the string
Returns a tuple where the string is parted into three parts
rpartition()
Splits the string at the specified separator, and returns a list
rsplit()
rstrip() Returns a right trim version of the string
Splits the string at the specified separator, and returns a list
split()
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
Swaps cases, lower case becomes upper case and vice versa
swapcase()
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
Fills the string with a specified number of 0 values at the beginning
zfill()

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Program:
string = input(―Enter a string:‖)
words = string.split()
words = list(reversed(words))
print(" ".join(words))

Output:
Enter a stringpython is easy
easy is python

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Practical-11 [C]
Write a program to check if a substring is present in a
given string.

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Aim: Write a program to check if a substring is present in a given
string.

Theory:
 Membership:
Python has two membership operators 'in' and 'not in'. The 'in' operator takes
two strings and returns True if the first string appears as a substring in the
second string, otherwise it returns False.
>>> str1 = 'Hello World!'
>>> 'W' in str1
True
>>> 'Wor' in str1
True
>>> 'My' in str1
False
The 'not in' operator also takes two strings and returns True if the first string
does not appear as a substring in the second string, otherwise returns False.
>>> str1 = 'Hello World!'
>>> 'My' not in str1
True
>>> 'Hello' not in str1
False
 Built in function find(str,start,end):
Returns the first occurrence of index of substring str occurring in the given
string. If we do not give start and end then searching starts from index 0 and
ends at length of the string. If the substring is not present in the given string,
then the function returns -1
>>> str1 = 'Hello World! Hello Hello'
>>> str1.find('Hello',10,20)
13
>>> str1.find('Hello',15,25)
19

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


>>> str1.find('Hello')
0
>>> str1.find('Hee')
-1
Program:
string=input("Enter string:")
sub_str=input("Enter word:")
if(string.find(sub_str)==-1):
print("Substring not found in string!")
else:
print("Substring in string!")

Output:
Enter string:python
Enter word:o
Substring in string!

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Practical-11 [D]
Write a program to count and display the number of
vowels, consonants, uppercase, lowercase characters
in a string.

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Aim: Write a program to count and display the number of vowels,
consonants, uppercase, lowercase characters in a string.

Program:
st=input("Enter a string:")
v=0
c=0
u=0
l=0
for i in range(0,len(st)):
if st[i].isspace() or not(st[i].isalpha()) :
continue
else:
if st[i]=='a' or st[i]=='e' or st[i]=='i' or st[i]=='o' or st[i]=='u':
v=v+1
else:
c=c+1
print(st[i])
if st[i].islower():
l=l+1
else:
u=u+1
print("uppercase=",u)
print("lowercase=",l)
print("vowels=",v)
print("consonants=",c)
Output: Enter a string:encyclopedia
n
c
y
c
l
p
d
uppercase= 0
lowercase= 12
vowels= 5
consonants= 7
SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING
Practical-12
Develop programs to perform the following list
operations.
a) To swap given two elements in a list.
b) To find the sum of elements in a list.

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Aim: Develop programs to perform the following list operations.
a)To swap given two elements in a list.
b)To find the sum of elements in a list.

Theory:

 Introduction to List:
The data type list is an ordered sequence which is mutable and made up of
one or more elements. Unlike a string which consists of only characters, a list
can have elements of different data types, such as integer, float, string, tuple
or even another list. A list is very useful to group together elements of mixed
data types. Elements of a list are enclosed in square brackets and are separated
by comma. Like string indices, list indices also start from 0.
Example
#list1 is the list of six even numbers
>>> list1 = [2,4,6,8,10,12]
>>> print(list1)
[2, 4, 6, 8, 10, 12]
#list2 is the list of vowels
>>> list2 = ['a','e','i','o','u']
>>> print(list2)
['a', 'e', 'i', 'o', 'u']
#list3 is the list of mixed data types
>>> list3 = [100,23.5,'Hello']
>>> print(list3)
[100, 23.5, 'Hello']
#list4 is the list of lists called nested
#list
>>> list4 =[['Physics',101],['Chemistry',202],

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


['Maths',303]]
>>> print(list4)
[['Physics', 101], ['Chemistry', 202],
['Maths', 303]]
 Accessing Elements in a List:
The elements of a list are accessed in the same way as characters are accessed in
a string.
Example:
#initializes a list list1
>>> list1 = [2,4,6,8,10,12]
>>> list1[0] #return first element of list1
2
>>> list1[3] #return fourth element of list1
8
#return error as index is out of range
>>> list1[15]
IndexError: list index out of range
#an expression resulting in an integer index
>>> list1[1+4]
12
>>> list1[-1] #return first element from right
12
#length of the list list1 is assigned to n
>>> n = len(list1)
>>> print(n)
6
#return the last element of the list1
>>> list1[n-1]
12
#return the first element of list1
>>> list1[-n]
2

 Lists are Mutable


In Python, lists are mutable. It means that the contents of the list can be changed
after it has been created.

#List list1 of colors


>>> list1 = ['Red','Green','Blue','Orange']
#change/override the fourth element of list1

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


>>> list1[3] = 'Black'
>>> list1 #print the modified list list1
['Red', 'Green', 'Blue', 'Black']

 Traversing a List:
We can access each element of the list or traverse a list using a for loop or a
while loop.
(A) List Traversal Using for Loop:
>>> list1 = ['Red','Green','Blue','Yellow',
'Black']
>>> for item in list1:
print(item)
Output:
Red
Green
Blue
Yellow
Black
Another way of accessing the elements of the list is using range() and len()
functions:
>>> for i in range(len(list1)):
print(list1[i])
Output:
Red
Green
Blue
Yellow
Black

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Program:
A) To swap given two elements in a list.
list=[1,5,2,10,21,7]
print("Original list:",list)
x =input("Enter positions of elements you want to swap x: ")

y=input("Enter positions of elements you want to swap y: ")

x=int(x)
y=int(y)

t=list[x]
list[x]=list[y]
list[y]=t
print("list after swap:",list)
Output:
Original list: [1, 5, 2, 10, 21, 7]
Enter positions of elements you want to swap x: 2
Enter positions of elements you want to swap y: 4
list after swap: [1, 5, 21, 10, 2, 7]

B) To find the sum of elements in a list.


list=[1,5,2,10,21,7]
sum=0

for i in range(0,len(list)):
sum=sum+list[i]

print("Sum of elements in list:",sum)

Output:
Sum of elements in list: 46

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Practical-13
a) Given a list saved in variable: a = [1, 4, 9, 16, 25, 36,
49, 64, 81, 100]. Write one line of Python that takes
this list and makes a new list that has only the even
elements of this list in it.
b) Create a list containing the square of all odd
numbers from range 1 to 10.

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Aim: Write programs for below task.
a) Given a list saved in variable: a = [1, 4, 9, 16, 25, 36,
49, 64, 81, 100]. Write one line of Python that takes
this list and makes a new list that has only the even
elements of this list in it.
b) Create a list containing the square of all odd
numbers from range 1 to 10.

Theory:
 List comprehensions:
List comprehensions are a powerful way to create lists. Here is a simple
example:
L = [i for i in range(5)]
This creates the list [0,1,2,3,4]
Here are a couple more examples of list comprehensions. For these examples,
assume the following:
string = 'Hello'
L = [1,14,5,9,12]
M = ['one', 'two', 'three', 'four', 'five', 'six']

Multiple fors You can use more than one for in a list comprehension:
L = [[i,j] for i in range(2) for j in range(2)]
[[0, 0], [0, 1], [1, 0], [1, 1]]

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Example 1 Write a program that generates a list L of 50 random numbers
between 1 and 100.
L = [randint(1,100) for i in range(50)]

Example 2 Replace each element in a list L with its square.


L = [i**2 for i in L]

Example 3 Count how many items in a list L are greater than 50.
len([i for i in L if i>50])

Programs:
a) Given a list saved in variable: a = [1, 4, 9, 16, 25, 36,
49, 64, 81, 100]. Write one line of Python that takes
this list and makes a new list that has only the even
elements of this list in it.

a = [1, 4, 9, 16, 25, 36,49, 64, 81, 100]


b = [i for i in a if i % 2 == 0]
Print(b)
Output:
[4, 16, 36, 64, 100]

b) Create a list containing the square of all odd numbers from range 1 to
10.

b = [i for i in range(1,11) if i % 2 == 1]
Print(b)

Output:
[1, 3, 5, 7, 9]

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Practical-14
Write a program to demonstrate the set functions and
operations.

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Aim:- Write a program to demonstrate the set functions andoperations.
Theory:-

Python Set functions:

A Set in Python is a collection of unique elements which are unordered and mutable. Python provides
various functions to work with Set.

Create set:

A set can be created in two ways. First, you can define a set with the built-in set() function:x = set(<iter>)
In this case, the argument <iter> is an iterable—again, for the moment, think list or tuple—that generates the
list of objects to be included in the set.

Example:

>>> x = set(['foo', 'bar', 'baz', 'foo', 'qux'])


>>> x
{'qux', 'foo', 'bar', 'baz'}
>>> x = set(('foo', 'bar', 'baz', 'foo', 'qux'))
>>> x
{'qux', 'foo', 'bar', 'baz'}

Strings are also iterable, so a string can be passed to set() as well. You have already seen that list(s)
generates a list of the characters in the string s. Similarly, set(s) generates a set of the characters in s:

Example:
>>> s = 'quux'
>>> list(s)
['q', 'u', 'u', 'x']
>>> set(s)
{'x', 'u', 'q'}

Alternately, a set can be defined with curly braces ({}): x =


{<obj>, <obj>, ..., <obj>}

Thus, the sets shown above can also be defined like this:

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


>>> x = {'foo', 'bar', 'baz', 'foo', 'qux'}
>>> x
{'qux', 'foo', 'bar', 'baz'}
>>> x = {'q', 'u', 'u', 'x'}
>>> x
{'x', 'q', 'u'}

A set can be empty. However, recall that Python interprets empty curly braces ({}) as anempty
dictionary, so the only way to define an empty set is with the set() function:

>>> x = set()
>>> type(x)
<class 'set'>
>>> x
set()
>>> x = {}
>>> type(x)
<class 'dict'>

An empty set is falsy in a Boolean context:

>>> x = set()
>>> bool(x)False

Don‘t forget that set elements must be immutable. For example, a tuple may be included in aset:
>>>
>>> x = {42, 'foo', (1, 2, 3), 3.14159}
>>> x
{42, 'foo', 3.14159, (1, 2, 3)}
But lists and dictionaries are mutable, so they can‘t be set elements:

>>>
>>> a = [1, 2, 3]
>>> {a}
Traceback (most recent call last):
File "<pyshell#70>", line 1, in <module>
{a}
TypeError: unhashable type: 'list'
>>> d = {'a': 1, 'b': 2}
>>> {d}
Traceback (most recent call last):
File "<pyshell#72>", line 1, in <module>
{d}

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Set Size and Membership
The len() function returns the number of elements in a set, and the in and not in operators canbe used to test
for membership:

>>> x = {'foo', 'bar', 'baz'}


>>> len(x)3
>>> 'bar' in xTrue
>>> 'qux' in xFalse

Modifying Sets:
Python supports several methods that modify sets.

x.add(<elem>)
Adds an element to a set.
x.add(<elem>) adds <elem>, which must be a single immutable object, to x:
>>>
>>> x = {'foo', 'bar', 'baz'}
>>> x.add('qux')
>>> x
{'bar', 'baz', 'foo', 'qux'}

x.remove(<elem>)
Removes an element from a set.
x.remove(<elem>) removes <elem> from x. Python raises an exception if <elem> isnot in x:
>>>
>>> x = {'foo', 'bar', 'baz'}
>>> x.remove('baz')
>>> x
{'bar', 'foo'}
>>> x.remove('qux')
Traceback (most recent call last):
File "<pyshell#58>", line 1, in <module>
x.remove('qux')
KeyError: 'qux'

x.discard(<elem>)
Removes an element from a set.
x.discard(<elem>) also removes <elem> from x. However, if <elem> is not in x, thismethod quietly
does nothing instead of raising an exception:
>>> x = {'foo', 'bar', 'baz'}
>>> x.discard('baz')
>>> x
{'bar', 'foo'}
>>> x.discard('qux')
>>> x
{'bar', 'foo'}

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


x.pop()
Removes a random element from a set.
x.pop() removes and returns an arbitrarily chosen element from x. If x is empty, x.pop()
raises an exception:
>>>
>>> x = {'foo', 'bar', 'baz'}
>>> x.pop()'bar'
>>> x
{'baz', 'foo'}
>>> x.pop()'baz'
>>> x
{'foo'}
>>> x.pop()'foo'
>>> x
set()
>>> x.pop()
Traceback (most recent call last):
File "<pyshell#82>", line 1, in <module>x.pop()
KeyError: 'pop from an empty set'

x.clear()
Clears a set.
x.clear() removes all elements from x:
>>>
>>> x = {'foo', 'bar', 'baz'}
>>> x
{'foo', 'bar', 'baz'}
>>>
>>> x.clear()
>>> x
set()

Set operations :

Below is a list of the set operations available in Python. Some are performed by operator, some by method,
and some by both. The principle outlined above generally applies: where a set is expected, methods will
typically accept any iterable as an argument, but operators require actual sets as operands.

Union operation:
x1.union(x2[, x3 ...])
x1 | x2 [| x3 ...]

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


Set Union
x1.union(x2) and x1 | x2 both return the set of all elements in either x1 or x2:
>>>
>>> x1 = {'foo', 'bar', 'baz'}
>>> x2 = {'baz', 'qux', 'quux'}
>>> x1.union(x2)
{'foo', 'qux', 'quux', 'baz', 'bar'}
>>> x1 | x2
{'foo', 'qux', 'quux', 'baz', 'bar'}
More than two sets may be specified with either the operator or the method:
>>>
>>> a = {1, 2, 3, 4}
>>> b = {2, 3, 4, 5}
>>> c = {3, 4, 5, 6}
>>> d = {4, 5, 6, 7}
>>> a.union(b, c, d)
{1, 2, 3, 4, 5, 6, 7}
>>> a | b | c | d
{1, 2, 3, 4, 5, 6, 7}

 Intersection Operation:

x1.intersection(x2[, x3 ...]) x1 & x2


[& x3 ...]

x1.intersection(x2) and x1 & x2 return the set of elements common to both x1 and
x2:
>>>
>>> x1 = {'foo', 'bar', 'baz'}
>>> x2 = {'baz', 'qux', 'quux'}
>>> x1.intersection(x2)
{'baz'}

>>> x1 & x2
{'baz'}
You can specify multiple sets with the intersection method and operator, just like you can with set union:
>>>
>>> a = {1, 2, 3, 4}
>>> b = {2, 3, 4, 5}
>>> c = {3, 4, 5, 6}
>>> d = {4, 5, 6, 7}
>>> a.intersection(b, c, d)
{4}
>>> a & b & c & d
{4}

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


 Difference Operation:

x1.difference(x2[, x3 ...])
x1 - x2 [- x3 ...]
Compute the difference between two or more sets.

x1.difference(x2) and x1 - x2 return the set of all elements that are in x1 but not in x2:

>>> x1 = {'foo', 'bar', 'baz'}


>>> x2 = {'baz', 'qux', 'quux'}
>>> x1.difference(x2)
{'foo', 'bar'}
>>> x1 - x2
{'foo', 'bar'}

>>> a = {1, 2, 3, 30, 300}


>>> b = {10, 20, 30, 40}
>>> c = {100, 200, 300, 400}
>>> a.difference(b, c)
{1, 2, 3}
>>> a - b - c
{1, 2, 3}

 Symmetric difference Operation:

x1.symmetric_difference(x2)
x1 ^ x2 [^ x3 ...]
Compute the symmetric difference between sets.

x1.symmetric_difference(x2) and x1 ^ x2 return the set of all elements in either


x1 or x2, but not both:
>>>
>>> x1 = {'foo', 'bar', 'baz'}
>>> x2 = {'baz', 'qux', 'quux'}

>>> x1.symmetric_difference(x2)
{'foo', 'qux', 'quux', 'bar'}
>>> x1 ^ x2
{'foo', 'qux', 'quux', 'bar'}

The ^ operator also allows more than two sets:


>>>
>>> a = {1, 2, 3, 4, 5}
>>> b = {10, 2, 3, 4, 50}
>>> c = {1, 50, 100}
>>> a ^ b ^ c
{100, 5, 10}

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


As with the difference operator, when multiple sets are specified, the operation is performedfrom left to
right.

Curiously, although the ^ operator allows multiple sets, the .symmetric_difference()


method doesn‘t:
>>>
>>> a = {1, 2, 3, 4, 5}
>>> b = {10, 2, 3, 4, 50}
>>> c = {1, 50, 100}
>>> a.symmetric_difference(b, c) Traceback
(most recent call last):
File "<pyshell#11>", line 1, in <module>
a.symmetric_difference(b, c)
TypeError: symmetric_difference() takes exactly one argument (2given)

 Disjoint or not:

x1.isdisjoint(x2)
Determines whether or not two sets have any elements in common.
x1.isdisjoint(x2) returns True if x1 and x2 have no elements in common:
>>>
>>> x1 = {'foo', 'bar', 'baz'}
>>> x2 = {'baz', 'qux', 'quux'}
>>> x1.isdisjoint(x2)False
>>> x2 - {'baz'}
{'quux', 'qux'}
>>> x1.isdisjoint(x2 - {'baz'})True
If x1.isdisjoint(x2) is True, then x1 & x2 is the empty set:
>>>
>>> x1 = {1, 3, 5}
>>> x2 = {2, 4, 6}
>>> x1.isdisjoint(x2)True
>>> x1 & x2

set()
Note: There is no operator that corresponds to the .isdisjoint() method.

 Subset or not:

x1.issubset(x2)
x1 <= x2
Determine whether one set is a subset of the other.
In set theory, a set x1 is considered a subset of another set x2 if every element of x1 is in x2.
x1.issubset(x2) and x1 <= x2 return True if x1 is a subset of x2:
>>>
>>> x1 = {'foo', 'bar', 'baz'}
>>> x1.issubset({'foo', 'bar', 'baz', 'qux', 'quux'})
True

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


>>> x2 = {'baz', 'qux', 'quux'}
>>> x1 <= x2
False
A set is considered to be a subset of itself:
>>>
>>> x = {1, 2, 3, 4, 5}
>>> x.issubset(x)True
>>> x <= x
True

It seems strange, perhaps. But it fits the definition—every element of x is in x.x1 < x2
Determines whether one set is a proper subset of the other.
A proper subset is the same as a subset, except that the sets can‘t be identical. A set x1 is considered a
proper subset of another set x2 if every element of x1 is in x2, and x1 and x2are not equal.
x1 < x2 returns True if x1 is a proper subset of x2:

>>>
>>> x1 = {'foo', 'bar'}
>>> x2 = {'foo', 'bar', 'baz'}
>>> x1 < x2
True
>>> x1 = {'foo', 'bar', 'baz'}
>>> x2 = {'foo', 'bar', 'baz'}
>>> x1 < x2
False
While a set is considered a subset of itself, it is not a proper subset of itself:
>>>
>>> x = {1, 2, 3, 4, 5}
>>> x <= x
True
>>> x < xFalse

Note: The < operator is the only way to test whether a set is a proper subset. There is no
corresponding method.

 Superset or not:

x1.issuperset(x2)x1 >= x2
Determine whether one set is a superset of the other.
A superset is the reverse of a subset. A set x1 is considered a superset of another set x2 if
x1 contains every element of x2.
x1.issuperset(x2) and x1 >= x2 return True if x1 is a superset of x2:
>>>
>>> x1 = {'foo', 'bar', 'baz'}
>>> x1.issuperset({'foo', 'bar'})True
>>> x2 = {'baz', 'qux', 'quux'}
>>> x1 >= x2
False
>>> x = {1, 2, 3, 4, 5}
>>> x.issuperset(x)True
SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING
>>> x >= x
True

x1 > x2
Determines whether one set is a proper superset of the other.
A proper superset is the same as a superset, except that the sets can‘t be identical. A set x1 isconsidered a
proper superset of another set x2 if x1 contains every element of x2, and x1 and x2 are not equal.
x1 > x2 returns True if x1 is a proper superset of x2:
>>>
>>> x1 = {'foo', 'bar', 'baz'}
>>> x2 = {'foo', 'bar'}
>>> x1 > x2
True
>>> x1 = {'foo', 'bar', 'baz'}
>>> x2 = {'foo', 'bar', 'baz'}
>>> x1 > x2
False
A set is not a proper superset of itself:
>>>
>>> x = {1, 2, 3, 4, 5}
>>> x > xFalse

Exercise

# Create two sample sets


set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

# Print the original sets


print("set1: ", set1)
print("set2: ", set2)

# Union of two sets


set_union = set1.union(set2)
print("Union of set1 and set2: ", set_union)

# Intersection of two sets


set_intersection = set1.intersection(set2)
print("Intersection of set1 and set2: ", set_intersection)

# Difference between two sets


set_difference = set1.difference(set2)
print("Difference between set1 and set2: ", set_difference)

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING


# Symmetric difference between two sets
set_sym_difference = set1.symmetric_difference(set2)
print("Symmetric difference between set1 and set2: ", set_sym_difference)

# Subset and superset check


print("Is set1 a subset of set2? ", set1.issubset(set2))
print("Is set1 a superset of set2? ", set1.issuperset(set2))

# Adding and removing elements from a set


set1.add(6)
set2.remove(8)
print("set1 after adding 6: ", set1)
print("set2 after removing 8: ", set2)

# Clearing a set
set1.clear()
print("set1 after clearing: ", set1)

Output:

set1: {1, 2, 3, 4, 5}
set2: {4, 5, 6, 7, 8}
Union of set1 and set2: {1, 2, 3, 4, 5, 6, 7, 8}
Intersection of set1 and set2: {4, 5}
Difference between set1 and set2: {1, 2, 3}
Symmetric difference between set1 and set2: {1, 2, 3, 6, 7, 8}
Is set1 a subset of set2? False
Is set1 a superset of set2? False
set1 after adding 6: {1, 2, 3, 4, 5, 6}
set2 after removing 8: {4, 5, 6, 7}
set1 after clearing: set()

SSGP SURAT INFORMATION & COMMUNICATION TECHNOLOGY PYTHON POGRAMMING

You might also like