Professional Documents
Culture Documents
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
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:
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.
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. 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.
2|Page
Python provides the input() function which is used to take input from the user. Let's understand the
following example.
Example -
Output:
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.
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.
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
Output
4|Page
Roll Name of Date of Date of Grade Sign Sign of
No. Student Performan Evaluation Student Faculty
ce
5|Page
EXPERIMENT NO. 2
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.
Outcomes: Students will have understanding of variables, data-types, printing on console and taking input
from the user.
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:
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.
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.
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.
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: ")
Output:
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|Page
EXPERIMENT NO. 3
Problem Statement:
Outcomes: Students will have a better understanding of the basic concept 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:
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
result=1
for i in range(1,exp+1):
result=result*num
print("Result is:",result)
Output:
2|Page
Sample Viva Questions and Answers:
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.
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.
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.
1. if expression:
2. 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.
1. if condition:
2. #block of statements
3. else:
4. #another block of statements (else-block)
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.
Instructions: N.A.
Program:
word = input("Input a word to reverse: ")
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:
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
4|Page
EXPERIMENT NO. 5
Problem Statement:
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.
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.
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).
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:
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.
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
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:
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[:].
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.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.).
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])
Output :
Program 2 :
res_list = []
for i in test_list1:
if i in test_list2:
res_list.append(i)
Output :
Program 3 :
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 :
# empty list
my_list = []
4|Page
Roll Name of Date of Date of Grade Sign Sign of
No. Student Performan Evaluation Student Faculty
ce
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.
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:
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.
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()
dict_obj = my_dictionary()
dict_obj.add(1, 'sunny')
dict_obj.add(2, 'shekhar')
print(dict_obj)
Output
Program
# Driver code
dict1 = {'a': 10, 'b': 8}
dict2 = {'d': 6, 'c': 4}
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
3|Page
EXPERIMENT NO. 8
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.
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 :
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):
a=1
b=3
# arguments passed
n = no_of_argu(1, 2, 4, a)
# result printed
print(" The number of arguments are: ", n)
my_function(fruits)
3|Page
EXPERIMENT NO. 9
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:
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
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
"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 -
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:
Output :
Program2 To insert a new item before the second element in an existing array.
Output
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')
d = dict()
line = line.lower()
words = line.split(" ")
for word in words:
if word in d:
d[word] = d[word] + 1
else:
d[word] = 1
Output:
Sample Viva Questions and Answers:
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.
4|Page
EXPERIMENT NO. 10
Problem Statement:
Implement Searching
1) To write a Python Program to perform Linear Search
2) To write a Python Program to perform binary search.
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
Instructions: N.A.
1|Page
Program:1 To write a Python Program to perform binary search.
else:
return -1
arr = sorted(['t','u','t','o','r','i','a','l'])
x ='r'
if result != -1:
print ("Element is present at index "+str(result))
else:
print ("Element is not present in array")
Output
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
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.
059
2|Page