You are on page 1of 53

EXPERIMENT NO.

Aim / Title: To understand the Basic syntax of Python

Problem Statement:
1) Write a program to print “Welcome”

2) Write a program sum.py that takes 2 numbers as command line arguments and prints its sum

Objectives: To create basic python Sketch

Outcomes: Students will have basic syntax understanding of python

Prerequisite: Basic knowledge of any programming language.

Hardware requirements:
Processors: Intel Atom® processor or Intel® Core™ i3 processor. Disk space: 1
GB
Software requirements:
Operating systems: Windows* 7 or later, macOS, and Linux.
Python versions: 2.7.X, 3.6.X. , Jupyter Notebook

Theory:

Python is a general-purpose interpreted, interactive, object-oriented, and high-level


programming language. It was created by Guido van Rossum during 1985- 1990.

Following are important characteristics of Python Programming − ∙ It supports functional and


structured programming methods as well as OOP.
∙ It can be used as a scripting language or can be compiled to byte-code for building large applications.
∙ It provides very high-level dynamic data types and supports dynamic type checking. ∙ It supports
automatic garbage collection.
∙ It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java. Applications

of Python

∙ Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This allows
the student to pick up the language quickly.
∙ Easy-to-read − Python code is more clearly defined and visible to the eyes.

1|Page
∙ Easy-to-maintain − Python's source code is fairly easy-to-maintain.
∙ A broad standard library − Python's bulk of the library is very portable and cross platform
compatible on UNIX, Windows, and Macintosh.
∙ Interactive Mode − Python has support for an interactive mode which allows interactive testing and
debugging of snippets of code.
∙ Portable − Python can run on a wide variety of hardware platforms and has the same interface on all
platforms.
∙ Extendable − You can add low-level modules to the Python interpreter. These modules enable
programmers to add to or customize their tools to be more efficient.
∙ Databases − Python provides interfaces to all major commercial databases.
∙ GUI Programming − Python supports GUI applications that can be created and ported to many system
calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window system
of Unix.
∙ Scalable − Python provides a better structure and support for large programs than shell scripting.

Python First Program

Unlike the other programming languages, Python provides the facility to execute the code using few lines.
For example - Suppose we want to print the "Hello World" program in Java; it will take three lines to print
it.

1. public class HelloWorld {


2. public static void main(String[] args){
3. // Prints "Hello, World" to the terminal window.
4. System.out.println("Hello World");
5. }
6. }

On the other hand, we can do this using one statement in Python.

1. print("Hello World")

Both programs will print the same result, but it takes only one statement without using a semicolon
or curly braces in Python.

Taking Input to the User

2|Page
Python provides the input() function which is used to take input from the user. Let's understand the
following example.

Example -

1. name = input("Enter a name of student:")


2. print("The student name is: ", name)

Output:

Enter a name of student: Jiya


The student name is: Jiya

By default, the input() function takes the string input but what if we want to take other data types as an
input.

If we want to take input as an integer number, we need to typecast the input() function into an integer.

Python 2 vs. Python 3

In most of the programming languages, whenever a new version releases, it supports the features and
syntax of the existing version of the language, therefore, it is easier for the projects to switch in the newer
version. However, in the case of Python, the two versions Python 2 and Python 3 are very much different
from each other.

A list of differences between Python 2 and Python 3 are given below:

1. Python 2 uses print as a statement and used as print "something" to print some string on the
console. On the other hand, Python 3 uses print as a function and used as print("something") to
print something on the console.
2. Python 2 uses the function raw_input() to accept the user's input. It returns the string representing the
value, which is typed by the user. To convert it into the integer, we need to use the int() function in
Python. On the other hand, Python 3 uses input() function which automatically interpreted the type
of input entered by the user. However, we can cast this value to any type by using primitive
functions (int(), str(), etc.).
3. In Python 2, the implicit string type is ASCII, whereas, in Python 3, the implicit string type is
Unicode.
4. Python 3 doesn't contain the xrange() function of Python 2. The xrange() is the variant of range()
function which returns a xrange object that works similar to Java iterator. The range() returns a
list for example the function range(0,3) contains 0, 1, 2.

3|Page
5. There is also a small change made in Exception handling in Python 3. It defines a keyword as which
is necessary to be used. We will discuss it in Exception handling section of Python programming
tutorial.

Instructions: N.A.
Program:
message=input("Enter welcome message : ")
print("Hello, ",message)

Output

Program
num1 = 1.5
num2 = 6.3

sum = num1 + num2

print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

Output

Sample Viva Questions and Answers:

1. Write three applications/software programs based on Python


Web Development.
Data Science — including machine learning, data analysis, and data visualization.
Scripting.

2. How to check data types in python


To check the data type of variable in Python, use the type() method. The type() is a built-in
Python method that returns the class type of the argument(object) passed as a parameter. You
place the variable inside a type() function, and Python returns the data type.

3. Write 2 advantages of using python


Ans interpreted Language. ...
Dynamically Typed. ...
Free and Open-Source. ...
Vast Libraries Support.

4. How do you print in python


Ans The print() function prints the specified message to the screen, or other standard output device. The
message can be a string, or any other object, the object will be converted into a string before written to the
screen.

5. How do you take input in python


Python program showing.
# a use of input()
name = input("Enter your name: ") # String Input.
age = int(input("Enter your age: ")) # Integer Input

4|Page
Roll Name of Date of Date of Grade Sign Sign of
No. Student Performan Evaluation Student Faculty
ce

059 Sunny shekhar

5|Page
EXPERIMENT NO. 2

Aim / Title: To understand the Basic concept of Python

Problem Statement:
1) Write a program to demonstrate basic data type in python.
2) Write a program to find the ASCII value of any three characters.

Objectives: To create basic python Sketch

Outcomes: Students will have understanding of variables, data-types, printing on console and taking input
from the user.

Pre-requisite: Basic knowledge of basic python

Hardware requirements:
Processors: Intel Atom® processor or Intel® Core™ i3 processor. Disk space: 1
GB
Software requirements:
Operating systems: Windows* 7 or later, macOS, and Linux.
Python versions: 2.7.X, 3.6.X. or latest , Jupyter Notebook Theory:

Why learn Python?

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

o Easy to use and Learn


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

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

o Data Science
o Date Mining
o Desktop Applications
o Console-based Applications
o Mobile Applications
o Software Development
o Artificial Intelligence
o Web Applications
o Enterprise Applications
o 3D CAD Applications
o Machine Learning
o Computer Vision or Image Processing Applications.
o Speech Recognitions.

Python Variables

Variable is a name that is used to refer to memory location. Python variable is also known as an identifier
and used to hold value.

In Python, we don't need to specify the type of variable because Python is a infer language and smart enough
to get variable type.

Variable names can be a group of both the letters and digits, but they have to begin with a letter or an
underscore.

It is recommended to use lowercase letters for the variable name. Rahul and rahul both are two different
variables.

Identifier Naming

Variables are the example of identifiers. An Identifier is used to identify the literals used in the program. The
rules to name an identifier are given below.

o The first character of the variable must be an alphabet or underscore ( _ ). o All the characters except
the first character may be an alphabet of lower-case(a-z), upper-case (A-Z), underscore, or digit (0-9).

2|Page
o Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &, *).
o Identifier name must not be similar to any keyword defined in the language. o Identifier names are case
sensitive; for example, my name, and MyName is not the same.
o Examples of valid identifiers: a123, _n, n_9, etc.
o Examples of invalid identifiers: 1a, n%4, n 9, etc.

Declaring Variable and Assigning Values

Python does not bind us to declare a variable before using it in the application. It allows us to create a
variable at the required time.

We don't need to declare explicitly variable in Python. When we assign any value to the variable, that
variable is declared automatically.

The equal (=) operator is used to assign value to a variable.

Instructions: N.A.

Program:
x = 20

print(x)

print(type(x))

x = 20.5 #float

print(x)

print(type(x))

x = 1j

print(x)

print(type(x))
Output

Program
K = input("Please enter a character: ")

print ("The ASCII value of '" + K + "' is ", ord(K))

Output:

Sample Viva Questions and Answers:

1. How would you declare a comment in Python?


Comments in Python begin with a hash mark ( # ) and whitespace character and continue to the end of the line

3|Page
2. What is the Python interpreter prompt?
A prompt is simply the location where instructions are typed in (at the shell command line). After typing in a
Python statement at the prompt, you must press the Enter key (also known as the Return key) on your
keyboard.
3. How would you define a block in Python?
A block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a
function body, and a class definition. Each command typed interactively is a block

4. What is indentation in python ?


Indentation refers to the spaces at the beginning of a code line. Where in other programming languages the
indentation in code is for readability only, the indentation in Python is very important. Python uses indentation
to indicate a block of code.

5. What is Python good for?


Python is commonly used for developing websites and software, task automation, data analysis, and data
visualization. Since it's relatively easy to learn, Python has been adopted by many non-programmers such as
accountants and scientists, for a variety of everyday tasks, like organizing finances.

Roll Name of Date of Date of Grade Sign Sign of


No. Student Performan Evaluation Student Faculty
ce

059 Sunny shekhar

4|Page
EXPERIMENT NO. 3

Aim / Title: To understand the Basic concept of Python

Problem Statement:

1) Write a program to find the GCD of two numbers.

2) To find the exponentiation of a number.

Objectives: Creating basic python Sketch

Outcomes: Students will have a better understanding of the basic concept of python.

Prerequisite: Basic knowledge of Python

Hardware requirements:
Processors: Intel Atom® processor or Intel® Core™ i3 processor. Disk space: 1
GB
Software requirements:
Operating systems: Windows* 7 or later, macOS, and Linux.
Python versions: 2.7.X, 3.6.X. ,Jupyter Notebook

Theory:

Python allows users to calculate the exponential value of a number in multiple ways. Let’s look at each of
them in detail!

1. ** operator

The double asterisk, ** operator is a shortcut to calculate the exponential value. Let’s take a look at how this
can be used in the following code:

1. base = 3
2. exponent = 4
3. print "Exponential Value is: ", base ** exponent

2. pow( )

In addition to the ** operator, Python has included a built-in pow() function which allows users to
calculate the exponential value.

The function takes as input the base and exponent and returns the corresponding value. The general
syntax of the function is:

pow(base, exponent)

1|Page
coding example:

1. base = 3
2. exponent = 4
3. print "Exponential Value is: ", pow(base, exponent)

3. exp( )

The exp() function in Python allows users to calculate the exponential value with the base set to e.

Note:

e is a Mathematical constant, with a value approximately equal to 2.71828. The math


library must be imported for this function to be executed.
The function takes as input the exponent value. The general syntax of the function is:

math.exp(exponent)
coding example:

1. import math

2. exponent = 4
3. print "Exponential Value is: ", math.exp(exponent)

Instructions: N.A.

Program:

import math
print("The gcd of 60 and 48 is : ", end="")
print(math.gcd(60, 48))

Output:
Program 2

num=int(input("Enter number: "))

exp=int(input("Enter exponential value: "))

result=1

for i in range(1,exp+1):

result=result*num
print("Result is:",result)

Output:

2|Page
Sample Viva Questions and Answers:

1. How do we execute Python?


Ans To run Python scripts with the python command, you need to open a command-line and type in the
word python , or python3 if you have both versions, followed by the path to your script, just like this: $
python3 hello.py Hello World!

2. How is a .pyc file different from a .py file?


Ans . py files contain the source code of a program. Whereas, . pyc file contains the bytecode of your
program.
3. What makes Python object-oriented?
Ans Object-Oriented Python, The heart of Python programming is a way of programming that focuses on
using objects and classes to design and build applications. Major pillars of Object Oriented Programming
(OOP) are Inheritance, Polymorphism, Data Abstraction, and Encapsulation.

4. Write syntax for if else?

if test expression:

Body of if

Else

Body of else

5. What is pep 8?
Ans PEP 8, sometimes spelled PEP8 or PEP-8, is a document that provides guidelines and best practices on
how to write Python code. It was written in 2001 by Guido van Rossum, Barry Warsaw, and Nick Coghlan.
The primary focus of PEP 8 is to improve the readability and consistency of Python code.

Roll Name of Date of Date of Grade Sign Sign of


No. Student Performan Evaluation Student Faculty
ce

059 Sunny shekhar


3|Page
EXPERIMENT NO. 4

Aim / Title: To understand the Basic concept of Python

Problem Statement:

1) Write a Python program that accepts a word from the user and reverse it.

2) Write a Python program to count the number of even and odd numbers from a series of numbers.

Objectives: Creating basic python Sketch

Outcomes: Students will be able to learn to create basic python sketch

Prerequisite: Basic knowledge of Python

Hardware requirements:
Processors: Intel Atom® processor or Intel® Core™ i3 processor. Disk space: 1
GB
Software requirements:
Operating systems: Windows* 7 or later, macOS, and Linux.
Python versions: 2.7.X, 3.6.X. , Jupyter Notebook

Theory:

Decision making is the most important aspect of almost all the programming languages. As the name
implies, decision making allows us to run a particular block of code for a particular decision. Here, the
decisions are made on the validity of the particular conditions. Condition checking is the backbone of
decision making. In python, decision making is performed by the following statements.

Indentation in Python

1|Page
For the ease of programming and to achieve simplicity, python doesn't allow the use of parentheses for
the block level code. In Python, indentation is used to declare a block. If two statements are at the same
indentation level, then they are the part of the same block.
Generally, four spaces are given to indent the statements which are a typical amount of
indentation in python.

Indentation is the most used part of the python language since it declares the block of code. All the
statements of one block are intended at the same level indentation. We will see how the actual indentation
takes place in decision making and other stuff in python.

The if statement

The if statement is used to test a particular condition and if the condition is true, it executes a block of
code known as if-block. The condition of if statement can be any valid logical expression which can be
either evaluated to true or false.

The syntax of the if-statement is given below.

1. if expression:
2. statement

The if-else statement:

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

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

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

1. if condition:
2. #block of statements
3. else:
4. #another block of statements (else-block)

The elif statement

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

2|Page
The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if statement.

The syntax of the elif statement is given below.


1. if expression 1:
2. # block of statements
3.
4. elif expression 2:
5. # block of statements
6.
7. elif expression 3:
8. # block of statements
9.
10. else:
11. # block of statements

Instructions: N.A.

Program:
word = input("Input a word to reverse: ")

for char in range(len(word) - 1, -1, -1):


print(word[char], end="")
print("\n")

Output:

Program 2:
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) # Declaring the tuple
count_odd = 0
count_even = 0
for x in numbers:
if not x % 2:
count_even+=1
else:
count_odd+=1
print("Number of even numbers :",count_even)
print("Number of odd numbers :",count_odd)

Output:

Sample Viva Questions and Answers:

1. What is dynamically typed language

Dynamically-typed languages are those (like JavaScript) where the interpreter assigns variables a type at
runtime based on the variable's value at the time

3|Page
2. What is pass in python
Python pass Statement
The pass statement is used as a placeholder for future code. When the pass statement is executed, nothing
happens, but you avoid getting an error when empty code is not allowed. Empty code is not allowed in
loops, function definitions, class definitions, or in if statements.
3. How is Python interpreted?
Python is an interpreted language, which means the source code of a Python program is converted into
bytecode that is then executed by the Python virtual machine. Python is different from major compiled
languages, such as C and C + +, as Python code is not required to be built and linked like code for these
languages.

4. Is Python case-sensitive?
Ans Yes, Python Is a Case-Sensitive Language

5. Explain the ternary operator in Python


Ternary operators are also known as conditional expressions are operators that evaluate something based on
a condition being true or false. It was added to Python in version 2.5. It simply allows testing a condition in
a single line replacing the multiline if-else making the code compact

Roll Name of Date of Date of Grade Sign Sign of


No. Student Performan Evaluation Student Faculty
ce

059 Sunny shekhar

4|Page
EXPERIMENT NO. 5

Aim / Title: To understand the Basic concept of Python

Problem Statement:

1) Write a Python program to get the Fibonacci series between 0 to 50

2) Write a Python program to sum of two given integers. However, if the sum is between 15 to 20 it will
return 20.

3) Write a Python program that accepts a string and calculates the number of digits and letters.

Objectives: Creating basic python Sketch

Outcomes: Students will be able to learn to create basic python sketch

Pre-requisite: Basic knowledge of Python

Hardware requirements:
Processors: Intel Atom® processor or Intel® Core™ i3 processor. Disk space: 1
GB
Software requirements:
Operating systems: Windows* 7 or later, macOS, and Linux.
Python versions: 2.7.X, 3.6.X. , Jupyter Notebook

Theory:
Python Loops

The flow of the programs written in any programming language is sequential by default. Sometimes we
may need to alter the flow of the program. The execution of a specific code may need to be repeated
several numbers of times.

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

Why we use loops in python?

The looping simplifies the complex problems into the easy ones. It enables us to alter the flow of the
program so that instead of writing the same code again and again, we can repeat the same code for a finite
number of times. For example, if we need to print the first 10 natural numbers then, instead of using the
print statement 10 times, we can print inside a loop which runs up to 10 iterations.

Advantages of loops

1|Page
There are the following advantages of loops in Python.
1. It provides code re-usability.
2. Using loops, we do not need to write the same code again and again. 3. Using loops, we can
traverse over the elements of data structures (array or linked lists).

There are the following loop statements in Python.

Instructions: N.A.

Program:
x,y=0,1

while y<50:
print(y)
x,y = y,x+y

Program :
Program 2:
def sum(x, y):
sum = x + y
if sum in range(15, 20):
return 20
else:
return sum

print(sum(10, 6))
print(sum(10, 2))
print(sum(10, 12))

Output :

Program 3

s = input("Input a string")
d=l=0
for c in s:
if c.isdigit():
d=d+1
elif c.isalpha():
l=l+1
else:
pass
print("Letters", l)
print("Digits", d)

Output:

Sample Viva Questions and Answers:

2|Page
1. What is the syntax of for loop in python?
The for loop uses the syntax: for item in object, where “object” is the iterable over which you want to iterate.
Loops allow you to repeat similar operations in your code. One of the most common types of loops in Python
is the for loop. This loop executes a block of code until the loop has iterated over an object.

2. What is the syntax of while loop in python?


Ans After one iteration, the test expression is checked again. This process continues until the test_expression
evaluates to False . In Python, the body of the while loop is determined through indentation. The body starts
with indentation and the first unindented line marks the end

3. What is the syntax of do while loop in python?


Ans Python while loops (which are often called do while loops in other languages) execute a block of code
while a statement evaluates to true. The syntax for a while loop is: while [your condition]. A while loop
should eventually evaluate to false otherwise it will not stop.
4. Which one is the post post-tested loop?
Ans This loop places the condition at the end of the loop and if the condition is true the keyword EXIT is
used to stop the looping. The traditional FORTRAN DO loop is used in the post-test loop and an IF statement
with an EXIT command is used to stop the looping

Roll Name of Date of Date of Grade Sign Sign of


No. Student Performan Evaluation Student Faculty
ce

059 Sunny shekhar

3|Page
EXPERIMENT NO. 6

Aim / Title: To understand the Basic concept of Lists and Tuples in python

Problem Statement:
Lists and Tuples
Write program to
1) Find second smallest and second largest number in a list
2) Find intersection of two lists and two nested list
3) Find the maximum from a list of numbers.
4) Add an item in a tuple
5) Convert a tuple to a string
6) Find the repeated items of a tuple

Objectives: Performing operations on lists and tuple

Outcomes: Students will be able to learn to implement lists and tuple Pre-requisite: Basic

knowledge of Python

Hardware requirements:
Processors: Intel Atom® processor or Intel® Core™ i3 processor. Disk space: 1
GB
Software requirements:
Operating systems: Windows* 7 or later, macOS, and Linux.
Python versions: 2.7.X, 3.6.X. , Jupyter Notebook

Theory:

LIST in python:

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 just like dynamic sized arrays, declared in other languages (vector in C++ and ArrayList in Java).
Lists need not be homogeneous always which makes it a most powerful tool in Python. Asingle list may
contain DataTypes like Integers, Strings, as well as Objects. Lists are mutable, andhence, they can be altered
even after their creation.
List in Python are ordered and have a definite count. The elements in a list are indexed accordingto a definite
sequence and the indexing of a list is done with 0 being the first index. Each element in the list has its definite
place in the list, which allows duplicating of elements in the list, witheach element having its own distinct
place and credibility.

1|Page
Example
Create a List:

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


print(thislist)

The list data type has some more methods. Here are all of the methods of list objects:

list.append(x)
Add an item to the end of the list. Equivalent to a[len(a):] = [x].

list.extend(iterable)
Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] = iterable.

list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to
insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to
a.append(x).

list.remove(x)
Remove the first item from the list whose value is equal to x. It raises a ValueError if there is no such
item.

list.pop([i])
Remove the item at the given position in the list, and return it. If no index is specified, a.pop()
removes and returns the last item in the list. (The square brackets around the i in the method signature
denote that the parameter is optional, not that you should type square brackets at that position. You
will see this notation frequently in the Python Library Reference.)

list.clear()
Remove all items from the list. Equivalent to del a[:].

list.index(x[, start[, end]])


Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if
there is no such item.

The optional arguments start and end are interpreted as in the slice notation and are used to limit the
search to a particular subsequence of the list. The returned index is computed relative to the
beginning of the full sequence rather than the start argument.

2|Page
list.count(x)
Return the number of times x appears in the list.

list.sort(*, key=None, reverse=False)


Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for
their explanation).

list.reverse()
Reverse the elements of the list in place.

list.copy()
Return a shallow copy of the list. Equivalent to a[:].

TUPLE in python:

A tuple in Python is similar to a list. The difference between the two is that we cannot change the elements
of a tuple once it is assigned whereas we can change the elements of a list.

Creating a Tuple

A tuple is created by placing all the items (elements) inside parentheses (), separated by commas. The
parentheses are optional, however, it is a good practice to use them.

A tuple can have any number of items and they may be of different types (integer, float, list, string,
etc.).

Advantages of Tuple over List:

Since tuples are quite similar to lists, both of them are used in similar situations. However, there are certain
advantages of implementing a tuple over a list. Below listed are some of the main advantages:

We generally use tuples for heterogeneous (different) data types and lists for homogeneous (similar)
data types.

Since tuples are immutable, iterating through a tuple is faster than with list. So there is a slight
performance boost.

Tuples that contain immutable elements can be used as a key for a dictionary. With lists, this is not
possible.

If you have data that doesn't change, implementing it as tuple will guarantee that it remains
write-protected.

3|Page
Instructions:
Program

def find_len(list1):
length = len(list1)
list1.sort()
print("Largest element is:", list1[length-1])
print("Smallest element is:", list1[0])
print("Second Largest element is:", list1[length-2])
print("Second Smallest element is:", list1[1])

list1=[12, 45, 2, 41, 31, 10, 8, 6, 4]


Largest = find_len(list1)

Output :

Program 2 :

test_list1 = [ [1, 2], [3, 4], [5, 6] ]


test_list2 = [ [3, 4], [5, 7], [1, 2] ]

print ("The original list 1 : " + str(test_list1))


print ("The original list 2 : " + str(test_list2))

res_list = []
for i in test_list1:
if i in test_list2:
res_list.append(i)

print ("The intersection of two lists is : " + str(res_list))

Output :

Program 3 :

list1 = [10, 20, 4, 45, 99]


list1.sort()
print("Largest element is:", list1[-1])

Output :
Program 4 :

tuplex = (4, 6, 2, 8, 3, 1)
print(tuplex)
tuplex = tuplex + (9,)
print(tuplex)
tuplex = tuplex[:5] + (15, 20, 25) + tuplex[:5]
print(tuplex)
listx = list(tuplex)
listx.append(30)
tuplex = tuple(listx)
print(tuplex)

Output :

Program 5 :

def convertTuple(tup):

str = ''
for item in tup:
str = str + item
return str

# Driver code
tuple = ('s', 'u', 'n', 'n', 'y')
str = convertTuple(tuple)
print(str)

Output :

Program 6:

tuplex = 2, 4, 5, 6, 2, 3, 4, 4, 7
print(tuplex)
#return the number of times it appears in the tuple.
count = tuplex.count(4)
print(count)

Output :

Sample Viva Questions and Answers:


1. How to create a List ?

# empty list

my_list = []

# list with mixed data types

my_list = [1, "Hello", 3.4]

2. How to know the size of a List ?


Ans Objects of any Python sequence data type including list
uses a built-in function len() which returns its size i.e.
number of elements in it. Built-in list class has a special
method called __len__() which also returns the size of the
list.

3. How to add an element to a List ?


● append(): append the object to the end of the list.
● insert(): inserts the object before the given index.
● extend(): extends the list by appending elements from the iterable.
● List Concatenation: We can use + operator to concatenate multiple lists and create a new list

4. How to create a Tuple ?


Ans A tuple in Python can be created by enclosing all the
comma-separated elements inside the parenthesis ().
Elements of the tuple are immutable and ordered. It allows
duplicate values and can have any number of elements. You
can even create an empty tuple.
5. How to delete a Tuple ?
Ans it means that we cannot delete or remove items from a
tuple. Deleting a tuple entirely, however, is possible using the
keyword del.

4|Page
Roll Name of Date of Date of Grade Sign Sign of
No. Student Performan Evaluation Student Faculty
ce

059 Sunny shekhar

5|Page
EXPERIMENT NO. 7

Aim / Title: To understand the basic concept of Sets and Dictionaries in python

Problem Statement:
Sets and Dictionaries
Write program
1) To remove an item from a set if it is present in the set
2) To create an intersection of sets.
3) To Add a key to a dictionary
4) To check whether a given key already exists in a dictionary.
5) To merge two Python dictionaries.

Objectives: To perform different operations on Sets and Dictionary in python Outcomes: Students

will be able to learn to Sets and Dictionary implementation Pre-requisite: Basic knowledge of Python

Hardware requirements:
Processors: Intel Atom® processor or Intel® Core™ i3 processor. Disk space: 1
GB
Software requirements:
Operating systems: Windows* 7 or later, macOS, and Linux.
Python versions: 2.7.X, 3.6.X. , Jupyter Notebook

Theory:
Python Dictionary is used to store the data in a key-value pair format. The dictionary is the data type in
Python, which can simulate the real-life data arrangement where some specific value exists for some
particular key. It is the mutable data-structure. The dictionary is defined into element Keys and values.
o Keys must be a single element
o Value can be any type such as list, tuple, integer, etc.

In other words, we can say that a dictionary is the collection of key-value pairs where the value can be any
Python object. In contrast, the keys are the immutable Python object, i.e., Numbers, string, or tuple.

Creating the dictionary

The dictionary can be created by using multiple key-value pairs enclosed with the curly brackets {}, and
each key is separated from its value by the colon (:).The syntax to define the dictionary is given below.

1|Page
Syntax:

1. Dict = {"Name": "Tom", "Age": 22}

In the above dictionary Dict, The keys Name and Age are the string that is an immutable object. Let's see an
example to create a dictionary and print its content.

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"} 2.


print(type(Employee))
3. print("printing Employee data .... ")
4. print(Employee)

Output

<class 'dict'>
Printing Employee data ....
{'Name': 'John', 'Age': 29, 'salary': 25000, 'Company': 'GOOGLE'} Instructions: N.A.

Program:
num_set = set([0, 1, 3, 4, 5])
print("Original set:")
print(num_set)
num_set.pop()
print("\nAfter removing the first element from the said set:")
print(num_set)

Output

Program :
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
n=int(input("Input a number to compute the factiorial : "))
print(factorial(n))

Output
Program
num_set = set([0, 1, 3, 4, 5])
print("Original set:")
print(num_set)
num_set.pop()
print("\nAfter removing the first element from the said set:")
print(num_set)

Output

Program
setx = set(["green", "blue"])
sety = set(["blue", "yellow"])
print("Original set elements:")
print(setx)
print(sety)
print("\nIntersection of two said sets:")
setz = setx & sety
print(setz)

Output
Program
class my_dictionary(dict):

def __init__(self):
self = dict()

def add(self, key, value):


self[key] = value

dict_obj = my_dictionary()

dict_obj.add(1, 'sunny')
dict_obj.add(2, 'shekhar')

print(dict_obj)

Output

Program

def Merge(dict1, dict2):


return(dict2.update(dict1))

# Driver code
dict1 = {'a': 10, 'b': 8}
dict2 = {'d': 6, 'c': 4}

# This return None


print(Merge(dict1, dict2))

# changes made in dict2


print(dict2)
Output

Sample Viva Questions and Answers:

1. Create an empty dictionary ?


To create an empty dictionary, first create a variable name which will be the name of the dictionary. Then,
assign the variable to an empty set of curly braces, {} . Another way of creating an empty dictionary is to use
the dict() function without passing any arguments.

2. How do you access dictionary values ?


Python | Accessing Key-value in Dictionary

Method #1 : Using in operator.

Method #2 : Using list comprehension.


Method #3 : Using dict.items()
Method #4 : Using enumerate()

2|Page
3. How do you add values in a dictionary ?
To add an item to a Python dictionary, you should assign a value to a new index key in your dictionary.
Unlike lists and tuples, there is no add() , insert() , or append() method that you can use to add items to your
data structure.
4. How to Delete elements using del keyword ?
Ans Delete a List Item - Using del , remove() or pop() If you want to remove any element from your List,
you can do so by using the del keyword, or pop() method or the remove() method. Try changing the code as
you like. Click the button, to Run the code again

5. Write down 5 Built-in Dictionary methods.


Ans 1 get This function returns the value for the given key
2 Keys This function returns a view object that displays a list of all the keys in the dictionary in order of
3 valuesThis function returns a list of all the values available in a given dictionary
4 items This function returns the list with all dictionary keys with values

Roll Name of Date of Date of Grade Sign of Sign of


No. Student Performan Evaluation Student Faculty
ce

059 Sunny shekhar

3|Page
EXPERIMENT NO. 8

Aim / Title: To implement Functions and learn to Pass arguments

Problem Statement:
Functions and Passing arguments:
1) To calculate the factorial of a number (a non-negative integer). The function accepts the number as an
argument.
2) That takes a list and returns a new list with unique elements of the first list. To check
whether a number is in a given range.

Objectives: Creating functions in python

Outcomes: Students will be able to learn to create functions in python

Prerequisite: Basic knowledge of Python

Hardware requirements:
Processors: Intel Atom® processor or Intel® Core™ i3 processor. Disk space: 1
GB
Software requirements:
Operating systems: Windows* 7 or later, macOS, and Linux.
Python versions: 2.7.X, 3.6.X. , Jupyter Notebook

Theory:
Python Functions:
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.

Creating a Function:
In Python a function is defined using the def keyword:

Example:
def my_function():
print("Hello from a function")

Calling a Function:
To call a function, use the function name followed by parenthesis:

Example:

1|Page
def my_function():
print("Hello from a function")
my_function()

Arguments
Information can be passed into functions as arguments.

Arguments are specified after the function name, inside the parentheses. You can add as many arguments
as you want, just separate them with a comma.

The following example has a function with one argument (fname). When the function is called, we pass
along a first name, which is used inside the function to print the full name:

Example:
def my_function(fname):
print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

Instructions: N.A.

Program:1 That takes a list and returns a new list with unique elements of the first list. To check whether a
number is in a given range.

def unique_list(l):
x = []
for a in l:
if a not in x:
x.append(a)
return x

print(unique_list([1,2,3,3,3,3,4,5]))
Output :
Program 2: To calculate the factorial of a number (a non-negative integer). The function accepts the number
as an argument.

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
n=int(input("Input a number to compute the factiorial : "))
print(factorial(n))

Output :

Sample Viva Questions and Answers:

1. What is a function
In computer programming, a function is a named section of a code that performs a specific task. This
typically involves taking some input, manipulating the input and returning an output

2|Page
2. Give an example of passing number of arguments in python

def no_of_argu(*args):

# using len() method in args to count


return(len(args))

a=1
b=3
# arguments passed
n = no_of_argu(1, 2, 4, a)

# result printed
print(" The number of arguments are: ", n)

3. How to pass a list as an argument ?


def my_function(food):
for x in food:
print(x)

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

my_function(fruits)

4. What is the lambda function to give an example?


Ans A Lambda Function in Python programming is an anonymous function or a function having no name. It
is a small and restricted function having no more than one line. Just like a normal function, a Lambda
function can have multiple arguments with one expression.

5. Why use the lambda function ?


Ans Why Use Lambda Functions? Lambda functions are used when you need a function for a short period of
time. This is commonly used when you want to pass a function as an argument to higher-order functions, that
is, functions that take other functions as their arguments

Roll Name of Date of Date of Grade Sign Sign of


No. Student Performan Evaluation Student Faculty
ce

059 Sunny shekhar

3|Page
EXPERIMENT NO. 9

Aim / Title: To implement array and File handling in python

Problem Statement:
Array and File Handling
Write program to
1) To remove a specified item using the index from an array.
2) To insert a new item before the second element in an existing array.
3) Display contents of given file
4) To read a file line by line, store it into an array.
5) To count the frequency of words in a file.

Objectives: Implementing array and working with file handling in python Outcomes: Students will be

able to learn to implement arrays and file handling in python Prerequisite: Basic knowledge of

Python

Hardware requirements:
Processors: Intel Atom® processor or Intel® Core™ i3 processor.
Disk space: 1 GB
Software requirements:
Operating systems: Windows* 7 or later, macOS, and Linux.
Python versions: 2.7.X, 3.6.X. , Jupyter Notebook

Theory:

An array is a collection of items stored at contiguous memory locations. The idealist store multiple items of the
same type together. This makes it easier to calculate the position of each element by simply adding an offset to
a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the
array).
Creating Python Arrays
To create an array of numeric values, we need to import the array module. For
example:

import array as arr


a = arr.array('d', [1.1, 3.5, 4.5])
print(a)

Output:
array('d', [1.1, 3.5, 4.5])

Here, we created an array of float type. The letter d is a type code. This determines the type of the array
during creation.

1|Page
Accessing Python Array Elements
We use indices to access elements of an array:
import array as arr
a = arr.array('i', [2, 4, 6, 8])
print("First element:", a[0])
print("Second element:", a[1])
print("Last element:", a[-1])

Output:

First element: 2
Second element: 4
Last element: 8

File Handling in python:

File handling is an important part of any web application.

Python has several functions for creating, reading, updating, and deleting files.

File Handling
The key function for working with files in Python is the open() function. The open()

function takes two parameters; filename, and mode. There are four different

methods (modes) for opening a file:

"r" - Read - Default value. Opens a file for reading, error if the file does not exist "a" - Append -

Opens a file for appending, creates the file if it does not exist "w" - Write - Opens a file for writing,

creates the file if it does not exist "x" - Create - Creates the specified file, returns an error if the file

exists In addition you can specify if the file should be handled as binary or text mode "t" - Text -

Default value. Text mode

"b" - Binary - Binary mode (e.g. images)

Syntax
To open a file for reading it is enough to specify the name of the file: f =

open("demofile.txt")

2|Page
The code above is the same as:

f = open("demofile.txt", "rt")
Because "r" for read, and "t" for text are the default values, you do not need to specify them.
Instructions:

Program1 To remove a specified item using the index from an array.

a=str(input("Enter the name of the file with .txt extension:"))


file2=open(a,'r')
line=file2.readline()
while(line!=""):
print(line)
line=file2.readline()
file2.close()

Output :

Program2 To insert a new item before the second element in an existing array.

from array import *


array_num = array('i', [1, 3, 5, 7, 9])
print("Original array: "+str(array_num))
print("Insert new value 4 before 3:")
array_num.insert(1, 4)
print("New array: "+str(array_num))

Output

Program 3 To read a file line by line, store it into an array.

def file_read(fname):
content_array = []
with open(fname) as f:
#Content_list is the list that contains the read lines.
for line in f:
content_array.append(line)
print(content_array)
file_read('test.txt')

Program 5 To count the frequency of words in a file.

text = open("sample.txt", "r")

d = dict()

for line in text


line = line.strip()

line = line.lower()
words = line.split(" ")
for word in words:
if word in d:
d[word] = d[word] + 1
else:

d[word] = 1

for key in list(d.keys())


print(key, ":", d[key])

Output:
Sample Viva Questions and Answers:

1 What is an array in python ?

A Python Array is a collection of common types of data structures having elements with the same data type. It
is used to store collections of data. In Python programming, arrays are handled by the “array” module. If you
create arrays using the array module, elements of the array must be of the same numeric type.

2. . How are Lists different from Array?


Data Types Storage: Array can store elements of only one data type but List can store the elements of different
data types too. Hence, Array stores homogeneous data values, and the list can store heterogeneous data values.

3. How do you display an array in python ?


To print an array in Python, use the print() function. The print() is a built-in Python function that takes the name
of the array containing the values and prints it. To create an array in Python, use numpy library and create an
array using np. array() function and then print that array in the console.

4. Why does python require file handling?


Python provides us with an important feature for reading data from the file and writing data into a file. Mostly,
in programming languages, all the values or data are stored in some variables which are volatile in nature

5. What is a negative index in Python?


Python programming language supports negative indexing of arrays, something which is not available in arrays
in most other programming languages. This means that the index value of -1 gives the last element, and -2 gives
the second last element of an array. The negative indexing starts from where the array ends

Roll Name of Date of Date of Grade Sign Sign of


No. Student Performan Evaluation Student Faculty
ce

059 Sunny shekhar

4|Page
EXPERIMENT NO. 10

Aim / Title: To implement searching algorithms in python

Problem Statement:
Implement Searching
1) To write a Python Program to perform Linear Search
2) To write a Python Program to perform binary search.

Objectives: To create basic searching algorithms

Outcomes: Students will be able to implement searching algorithms in python

Pre-requisite: Basic knowledge of Python and searching algorithms

Hardware requirements:
Processors: Intel Atom® processor or Intel® Core™ i3 processor. Disk space: 1
GB
Software requirements:
Operating systems: Windows* 7 or later, macOS, and Linux.
Python versions: 2.7.X, 3.6.X. , Jupyter Notebook

Theory:
Algorithm for Linear Search:
1. Start from the leftmost element of given arr[] and one by one compare element x with each
element of arr[]
2. If x matches with any of the element, return the index value.
3. If x doesn’t match with any of elements in arr[] , return -1 or element not found. Algorithm

for Binary Search:

1. Compare x with the middle element.


2. If x matches with middle element, we return the mid index.
3. Else If x is greater than the mid element, then x can only lie in right half subarray after the mid
element. So we recur for right half.
4. Else (x is smaller) recur for the left half.

Instructions: N.A.

1|Page
Program:1 To write a Python Program to perform binary search.

def binarySearchAppr (arr, start, end, x):


if end >= start:

mid = start + (end- start)//2


if arr[mid] == x:
return mid
elif arr[mid] > x:
return binarySearchAppr(arr, start, mid-1, x)
else:
return binarySearchAppr(arr, mid+1, end, x)

else:
return -1

arr = sorted(['t','u','t','o','r','i','a','l'])
x ='r'

result = binarySearchAppr(arr, 0, len(arr)-1, x)

if result != -1:
print ("Element is present at index "+str(result))
else:
print ("Element is not present in array")

Output

Program2 To write a Python Program to perform Linear Search

def linear_Search(list1, n, key):

# Searching list1 sequentially


for i in range(0, n):
if (list1[i] == key):
return i
return -1

list1 = [1 ,3, 5, 4, 7, 9]
key = 7
n = len(list1)
res = linear_Search(list1, n, key)
if(res == -1):
print("Element not found")
else:
print("Element found at index: ", res)

Output

Sample Viva Questions and Answers:

1. What is Linear search ?


Ans A linear search is the simplest method of searching a data set. Starting at the beginning of the data
set, each item of data is examined until a match is made. Once the item is found, the search ends

2. What is the time complexity of linear search?


Ans n O(n)
Linear search is also known as sequential search. It is named as linear
because its time complexity is of the order of n O(n).

3. What is binary search ?


Ans Binary search is an efficient algorithm for finding an item from a sorted
list of items. It works by repeatedly dividing in half the portion of the list that
could contain the item, until you've narrowed down the possible locations to
just one.

4. What is mid in Binary search ?

Ans mid = left + (right - left) / 2 and mid = (left + right) / 2. 0. 35. binary search middle value calculation
5. What is the difference between / and // in Python?
The and is a type of Logical AND that returns in a True form whenever both the operands are also true.
The &, on the other hand, is a bitwise operator used in the Python language. It basically acts on various
bits and performs operations bit by bit.

Roll Name of Date of Date of Grade Sign Sign of


No. Student Performan Evaluation Student Faculty
ce

059

2|Page

You might also like