[go: up one dir, main page]

0% found this document useful (0 votes)
48 views50 pages

PYTHON LAB MANUAL AIETM

The document is a lab manual for a Python lab course at Arya Institute of Engineering Technology & Management, detailing various programming exercises and concepts. It includes a syllabus with a list of programs to be implemented, along with their aims, descriptions, source codes, and outputs. Additionally, it contains viva questions covering key Python features, control flow statements, and common operations.
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)
48 views50 pages

PYTHON LAB MANUAL AIETM

The document is a lab manual for a Python lab course at Arya Institute of Engineering Technology & Management, detailing various programming exercises and concepts. It includes a syllabus with a list of programs to be implemented, along with their aims, descriptions, source codes, and outputs. Additionally, it contains viva questions covering key Python features, control flow statements, and common operations.
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/ 50

LAB MANUAL

Lab Name :PYTHON LAB


Lab Code :6CS4-23
Branch :Computer Science & Engineering
Year (B.Tech.) :III Year/VI Sem

ARYA Institute of Engineering Technology & Management


Department of Computer Science& Engineering
(Rajasthan Technical University, KOTA)
SYLLABUS
LIST OF PROGRAMS

S. NO. TITLE

1 Write a program to demonstrate basic data type in python..

2 A)Write a program to compute distance between two points taking input from the user

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

3 A)Write a Program for checking whether the given number is an even number or not.

B)Using a for loop, write a program that prints out the decimal equivalents of
1/2, 1/3, 1/4, . . . , 1/10
A) Write a Program to demonstrate list and tuple in python.
4 B Write a program using a for loop that loops over a sequence.
C) Write a program using a while loop that asks the user for a number, and prints a
countdown from that number to zero..
A)Find the sum of all the primes below two million.
5 B)By considering the terms in the Fibonacci sequence whose values do not
exceed four million, WAP to find the sum of the even-valued terms..
A)Write a program to count the numbers of characters in the string and store
6 them in a dictionary data structure.
B)Write a program to use split and join methods in the string and trace a
Birth day of a person with a dictionary data structure
Write a program to count frequency of characters in a given file. Can you use character
7 frequency to tell whether the given file is a Python program file, C program file or a
text file?
A)Write a program to print each line of a file in reverse order.
8 B)Write a program to compute the number of characters, words and lines in a file.

A)Write a function nearly equal to test whether two strings are nearly equal. Two
9 strings a and b are nearly equal when a can be generated by a single mutation on.
B)Write function to compute gcd, lcm of two numbers. Each function shouldn’t exceed
one line.
A)Write a program to implement Merge sort.
10 B)Write a program to implement Selection sort, Insertion sort.
Program No.1

Aim:-

Write a program to demonstrate basic data type in python.

Description:-

Data types in Python

Every value in Python has a data type. Since everything is an object in Python programming,
data types are actually classes and variables are instance (object) of these classes.

Source Code:-

a=5
print(a, "is of type", type(a))

a = 2.0
print(a, "is of type", type(a))

a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))

Output:-

5 is of type <class 'int'>


2.0 is of type <class 'float'>
(1+2j) is complex number? True
VIVA QUESTIONS

Q.1. What are the key features of Python?

If it makes for an introductory language to programming, Python must mean something. These
are its qualities:

• Interpreted
• Dynamically-typed
• Object-oriented
• Concise and simple
• Free
• Has a large community

Q.2. Differentiate between lists and tuples.

The major difference is that a list is mutable, but a tuple is immutable.

Q.3. Explain the ternary operator in Python.

Unlike C++, we don’t have ?: in Python, but we have this:

[on true] if [expression] else [on false]

If the expression is True, the statement under [on true] is executed. Else, that under [on false] is
executed.

Q.4. What are negative indices?

Let’s take a list for this.

1. >>> mylist=[0,1,2,3,4,5,6,7,8]

A negative index, unlike a positive one, begins searching from the right.

1. >>> mylist[-3]

This also helps with slicing from the back:

1. >>> mylist[-6:-1]

[3, 4, 5, 6, 7]

Q.5. Is Python case-sensitive?

A language is case-sensitive if it distinguishes between identifiers like myname and Myname. In


other words, it cares about case- lowercase or uppercase. Let’s try this with Python.

1. >>> myname='Ayushi'
2. >>> Myname

Traceback (most recent call last):

File “<pyshell#3>”, line 1, in <module>

Myname

NameError: name ‘Myname’ is not defined

As we can see, this raised a NameError. This means that Python is indeed case-sensitive.

Q.6. How long can an identifier be in Python?

According to the official Python documentation, an identifier can be of any length. However,
PEP 8 suggests that you should limit all lines to a maximum of 79 characters. Also, PEP 20 says
‘readability counts’. So, a very long identifier will violate PEP-8 and PEP-20.

Apart from that, there are certain rules we must follow to name one:

❖ It can only begin with an underscore or a character from A-Z or a-z.


❖ The rest of it can contain anything from the following: A-Z/a-z/_/0-9.
❖ Python is case-sensitive, as we discussed in the previous question.
❖ Keywords cannot be used as identifiers.

Q.7. How would you convert a string into lowercase?

We use the lower() method for this.

1. >>> 'AyuShi'.lower()

‘ayushi’

To convert it into uppercase, then, we use upper().

1. >>> 'AyuShi'.upper()

‘AYUSHI’

Also, to check if a string is in all uppercase or all lowercase, we use the methods isupper() and
islower().

1. >>> 'AyuShi'.isupper()

False

1. >>> 'AYUSHI'.isupper()
True

1. >>> 'ayushi'.islower()

True

1. >>> '@yu$hi'.islower()

True

1. >>> '@YU$HI'.isupper()

True

So, characters like @ and $ will suffice for both cases

Also, istitle() will tell us if a string is in title case.

1. >>> 'The Corpse Bride'.istitle()

True

Q.8. What is the pass statement in Python?

There may be times in our code when we haven’t decided what to do yet, but we must type
something for it to be syntactically correct. In such a case, we use the pass statement.

1. >>> def func(*args):


2. pass
3. >>>

Similarly, the break statement breaks out of a loop.

1. >>> for i in range(7):


2. if i==3: break
3. print(i)

Finally, the continue statement skips to the next iteration.

1. >>> for i in range(7):


2. if i==3: continue
3. print(i)

1
2

6
Program No.2

Aim:-

Write a program to compute distance between two points taking input from the user

Description:-

Basic Operators in Python

Arithmetic operators: Arithmetic operators are used to perform mathematical operations like
addition, subtraction, multiplication and division.

Relational Operators: Relational operators compares the values. It either returns True or False
according to the condition.

Logical operators: Logical operators perform Logical AND, Logical OR and Logical NOT
operations.
Source Code:

Bitwise operators: Bitwise operators acts on bits and performs bit by bit operation.

Assignment operators: Assignment operators are used to assign values to the variables.

Special operators: There are some special type of operators like-

• Identity operators-

is and is not are the identity operators both are used to check if two values are located on
the same part of the memory. Two variables that are equal does not imply that they are
identical.

• Membership operators-

in and not in are the membership operators; used to test whether a value or variable is in
a sequence.

Source Code:-

# Python3 program to calculate


# distance between two points

import math

# Function to calculate distance


def distance(x1 , y1 , x2 , y2):
# Calculating distance
return math.sqrt(math.pow(x2 - x1, 2) +
math.pow(y2 - y1, 2) * 1.0)

# Drivers Code
print("%.6f"%distance(3, 4, 4, 3))

Output:-

1.414214

Aim:-

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

Source Code:-

# Store input numbers


num1 = input('Enter first number: ')
num2 = input('Enter second number: ')
# Add two numbers
sum = float(num1) + float(num2)
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

Output:

Enter first number: 5


Enter second number: 88
The sum of 5 and 88 is 93.0
VIVA QUESTIONS

Q.1. Explain help() and dir() functions in Python.

The help() function displays the documentation string and help for its argument.

1. >>> import copy


2. >>> help(copy.copy)

Help on function copy in module copy:

copy(x)

Shallow copy operation on arbitrary Python objects.

The dir() function displays all the members of an object(any kind).

1. >>> dir(copy.copy)

Q.2. How do you get a list of all the keys in a dictionary?

we use the function keys().

1. >>> mydict={'a':1,'b':2,'c':3,'e':5}
2. >>> mydict.keys()

dict_keys([‘a’, ‘b’, ‘c’, ‘e’])

Q.3. What is slicing?

Slicing is a technique that allows us to retrieve only a part of a list, tuple, or string. For this, we
use the slicing operator [].

1. >>> (1,2,3,4,5)[2:4]

(3, 4)

1. >>> [7,6,8,5,9][2:]

[8, 5, 9]

1. >>> 'Hello'[:-1]

‘Hell’

Q.4. How would you declare a comment in Python?

Unlike languages like C++, Python does not have multiline comments. All it has is octothorpe
(#). Anything following a hash is considered a comment, and the interpreter ignores it.
1. >>> #line 1 of comment
2. >>> #line 2 of comment

In fact, you can place a comment anywhere in your code. You can use it to explain your code.

Q.5. How will you check if all characters in a string are alphanumeric?

For this, we use the method isalnum().

Q.6. How will you capitalize the first letter of a string?

Simply using the method capitalize().

1. >>> 'ayushi'.capitalize()

‘Ayushi’

1. >>> type(str.capitalize)

<class ‘method_descriptor’>

However, it will let other characters be.

1. >>> '@yushi'.capitalize()

‘@yushi’

1. >>> 'Ayushi123'.isalnum()

True

1. >>> 'Ayushi123!'.isalnum()

False

Other methods that we have include:

1. >>> '123.3'.isdigit()

False

1. >>> '123'.isnumeric()

True

1. >>> 'ayushi'.islower()

True
1. >>> 'Ayushi'.isupper()

False

1. >>> 'Ayushi'.istitle()

True

1. >>> ' '.isspace()

True

1. >>> '123F'.isdecimal()

False

Q.7. We know Python is all the rage these days. But to be truly accepting of a great
technology, you must know its pitfalls as well. Would you like to talk about this?
Of course. To be truly yourself, you must be accepting of your flaws. Only then can you move
forward to work on them. Python has its flaws too:

• Python’s interpreted nature imposes a speed penalty on it.


• While Python is great for a lot of things, it is weak in mobile computing, and in browsers.
• Being dynamically-typed, Python uses duck-typing (If it looks like a duck, it must be a
duck). This can raise runtime errors.
• Python has underdeveloped database access layers. This renders it a less-than-perfect
choice for huge database applications.
• And then, well, of course. Being easy makes it addictive. Once a Python-coder, always a
Python coder.

Q.8. With Python, how do you find out which directory you are currently in?
To find this, we use the function/method getcwd(). We import it from the module os.

1. >>> import os
2. >>> os.getcwd()
Program No.3
Aim

Write a Program for checking whether the given number is an even number or not.

Description:

Control Flow Statements


A program’s control flow is the order in which the program’s code executes. The control flow of
a Python program is regulated by conditional statements, loops, and function calls.

The if Statement
Often, you need to execute some statements only if some condition holds, or choose statements
to execute depending on several mutually exclusive conditions. The Python compound statement
if, which uses if, elif, and else clauses.

Here’s the syntax for the if statement:

if expression:
statement(s)
elif expression:
statement(s)
elif expression:
statement(s)
...
else:
statement(s)

The elif and else clauses are optional. Note that unlike some languages, Python does not have a
switch statement, so you must use if, elif, and else for all conditional processing.

Source Code:

# Python program to check if the input number is odd or even.


# A number is even if division by 2 gives a remainder of 0.
# If the remainder is 1, it is an odd number.
num = int(input("Enter a number: "))
if (num % 2) == 0:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))

Output:
Enter a number: 2
2 is Even
Aim:
Using a for loop, write a program that prints out the decimal equivalents of
1/2, 1/3, 1/4, . . . , 1/10

Description:

The for Statement


The for statement in Python supports repeated execution of a statement or block of statements
that is controlled by an iterable expression. Here’s the syntax for the for statement:
for target in iterable:
statement(s)
Note that the in keyword is part of the syntax of the for statement and is functionally unrelated to
the in operator used for membership testing. A for statement can also include an else clause and
break and continue statements

Source Code:

n=int(input("Enter the number of terms: "))


sum1=0
for i in range(2,n+1):
sum1=sum1+(1/i)
print("The sum of series is",round(sum1,2))

Output:
Enter the number of terms: 2
The sum of series is 0.5
VIVA QUESTIONS
Q.1. How do you insert an object at a given index in Python?

Let’s build a list first.

1. >>> a=[1,2,4]

Now, we use the method insert. The first argument is the index at which to insert, the second is
the value to insert.

1. >>> a.insert(2,3)
2. >>> a

[1, 2, 3, 4]

Q.2. And how do you reverse a list?

Using the reverse() method.

1. >>> a.reverse()
2. >>> a

[4, 3, 2, 1]

You can also do it via slicing from right to left:

1. >>> a[::-1]
2. >>> a

[1, 2, 3, 4]

This gives us the original list because we already reversed it once. However, this does not
modify the original list to reverse it.

Q.3. And how do you reverse a list?

Using the reverse() method.

1. >>> a.reverse()
2. >>> a

[4, 3, 2, 1]

You can also do it via slicing from right to left:

1. >>> a[::-1]
2. >>> a

[1, 2, 3, 4]
This gives us the original list because we already reversed it once. However, this does not
modify the original list to reverse it.

Q.4. What is the Python interpreter prompt?


This is the following sign for Python Interpreter:

1. >>>

If you have worked with the IDLE, you will see this prompt.

Q.5. How does a function return values?

A function uses the ‘return’ keyword to return a value. Take a look:

1. >>> def add(a,b):


2. return a+b

Q.6. How would you define a block in Python?

For any kind of statements, we possibly need to define a block of code under them. However,
Python does not support curly braces. This means we must end such statements with colons and
then indent the blocks under those with the same amount.

1. >>> if 3>1:
2. print("Hello")
3. print("Goodbye")

Hello

Goodbye

Q.7. Why do we need break and continue in Python?


Both break and continue are statements that control flow in Python loops. break stops the current
loop from executing further and transfers the control to the next block. continue jumps to the
next iteration of the loop without exhausting it.

Q.8. Will the do-while loop work if you don’t end it with a semicolon?
Python does not support an intrinsic do-while loop. Secondly, to terminate do-while loops is a
necessity for languages like C++.

Q.9. In one line, show us how you’ll get the max alphabetical character from a string.

For this, we’ll simply use the max function.

1. >>> max('flyiNg')

‘y’
The following are the ASCII values for all the letters of this string-

f- 102

l- 108

y- 121

i- 105

N- 78

g- 103

By this logic, try to explain the following line of code-

1. >>> max('fly{}iNg')

‘}’

(Bonus: } – 125)
Experiment-4
Aim:
Write a Program to demonstrate list and tuple in python.

Description:

Lists are one of the most powerful tools in python. They are just like the arrays declared in other
languages. But the most powerful thing is that list need not be always homogenous. A single list
can contain strings, integers, as well as objects. Lists can also be used for implementing stacks
and queues. Lists are mutable, i.e., they can be altered once declared.

A tuple is a sequence of immutable Python objects. Tuples are just like lists with the exception
that tuples cannot be changed once declared. Tuples are usually faster than lists.

Source Code:
L = [1, "a" , "string" , 1+2]
print L
L.append(6)
print L
L.pop()
print L
print L[1]

The output is :

[1, 'a', 'string', 3]


[1, 'a', 'string', 3, 6]
[1, 'a', 'string', 3]
a

tup = (1, "a", "string", 1+2)


print tup
print tup[1]

The output is :

(1, 'a', 'string', 3)


a

Aim:
Write a program using a for loop that loops over a sequence.

Source Code:
str="i am python developer"
for i in str:
print(i)

Output:
i
a
m

p
y
t
h
o
n

d
e
v
e
l
o
p
e
r

Aim:
Write a program using a while loop that asks the user for a number, and prints a countdown from
that number to zero.

Source Code:
n = int(input("Enter A Number--->"));
while n >=0:
print (n);
n = n - 1;
Output:

Enter A Number--->3
3
2
1
0
VIVA QUESTIONS
Q.1. What is Python good for?

Python is a jack of many trades, check out Applications of Python to find out more.

Meanwhile, we’ll say we can use it for:

• Web and Internet Development


• Desktop GUI
• Scientific and Numeric Applications
• Software Development Applications
• Applications in Education
• Applications in Business
• Database Access
• Network Programming
• Games, 3D Graphics
• Other Python Applications

Q.2. Can you name ten built-in functions in Python and explain each in brief?
Ten Built-in Functions,
complex()- Creates a complex number.

1. >>> complex(3.5,4)

(3.5+4j)

eval()- Parses a string as an expression.

1. >>> eval('print(max(22,22.0)-min(2,3))')

20

filter()- Filters in items for which the condition is true.

1. >>> list(filter(lambda x:x%2==0,[1,2,0,False]))

[2, 0, False]

ormat()- Lets us format a string.

1. >>> print("a={0} but b={1}".format(a,b))

a=2 but b=3

hash()- Returns the hash value of an object.

1. >>> hash(3.7)
644245917

hex()- Converts an integer to a hexadecimal.

1. >>> hex(14)

‘0xe’

input()- Reads and returns a line of string.

1. >>> input('Enter a number')

Enter a number7

1. ‘7’

len()- Returns the length of an object.

1. >>> len('Ayushi')

locals()- Returns a dictionary of the current local symbol table.

1. >>> locals()

open()- Opens a file.

1. >>> file=open('tabs.txt')

Q.3. What will the following code output?

1. >>> word=’abcdefghij’
2. >>> word[:3]+word[3:]

The output is ‘abcdefghij’. The first slice gives us ‘abc’, the next gives us ‘defghij’.

Q.4. How will you convert a list into a string?

We will use the join() method for this.

1. >>> nums=['one','two','three','four','five','six','seven']
2. >>> s=' '.join(nums)
3. >>> s

‘one two three four five six seven’

Q.5. How will you remove a duplicate element from a list?


We can turn it into a set to do that.

1. >>> list=[1,2,1,3,4,2]
2. >>> set(list)

{1, 2, 3, 4}

Q.6. Can you explain the life cycle of a thread?

• To create a thread, we create a class that we make override the run method of the thread
class. Then, we instantiate it.
• A thread that we just created is in the new state. When we make a call to start() on it, it
forwards the threads for scheduling. These are in the ready state.
• When execution begins, the thread is in the running state.
• Calls to methods like sleep() and join() make a thread wait. Such a thread is in the
waiting/blocked state.
• When a thread is done waiting or executing, other waiting threads are sent for scheduling.
• A running thread that is done executing terminates and is in the dead state.

Q.7. What is a dictionary in Python?


A python dictionary is something I have never seen in other languages like C++ or Java
programming. It holds key-value pairs.

1. >>> roots={25:5,16:4,9:3,4:2,1:1}
2. >>> type(roots)

<class ‘dict’>

1. >>> roots[9]

A dictionary is mutable, and we can also use a comprehension to create it.

1. >>> roots={x**2 for x in range(5,0,-1)}


2. >>> roots

{25: 5, 16: 4, 9: 3, 4: 2, 1: 1}

Q.8. Explain the //, %, and ** operators in Python.

The // operator performs floor division. It will return the integer part of the result on division.

1. >>> 7//2

Normal division would return 3.5 here.


Similarly, ** performs exponentiation. a**b returns the value of a raised to the power b.

1. >>> 2**10

1024

Finally, % is for modulus. This gives us the value left after the highest achievable division.

1. >>> 13%7

1. >>> 3.5%1.5

0.5
Experiment-5
Aim:

Find the sum of all the primes below two million.

Source Code:

a, b = 1, 2
total = 0
print(a,end=" ")
while (a <=2000000-1):
if a % 2 != 0:
total += a
a, b = b, a+b
print(a,end=" ")
print("\n sum of prime numbers term below two million: ",total)

Aim:

By considering the terms in the Fibonacci sequence whose values do not exceed four million,
WAP to find the sum of the even-valued terms.

Source Code:

a, b = 1, 2
total = 0
print(a,end=" ")
while (a <=4000000-1):
if a % 2 == 0:
total += a
a=b
b =a+b
print(a,end=" ")
print("\n sum of prime numbers term in fibonacci series: ",total)

1 4194304
sum of prime numbers term in fibonacci series: 4194302
VIVA QUESTIONS
Q.1. What do you know about relational operators in Python.
PYTHON RELATIONAL OPERATORS
< Less Than
> Greater Than
<= Less than or equal to
>= Greater than or equal to
= Equal to
!= Not equal to

Q.2. What are assignment operators in Python?


Python assignment operator
Operator Description
= assign
+= Add and assign
-= Subtract and assign
*= Multiply and assign
/= Divide and assign
%= Modulus and assign
**= Exponent and assign
//= Floor-divide and assign

Q.3. Explain logical operators in Python.


We have three logical operators- and, or, not.

1. >>> False and True

False

1. >>> 7<7 or True

True

1. >>> not 2==2

False
Q.4. What are membership operators?
With the operators ‘in’ and ‘not in’, we can confirm if a value is a member in another.

1. >>> 'me' in 'disappointment'

True

1. >>> 'us' not in 'disappointment'

True
Q.5. Explain identity operators in Python.
The operators ‘is’ and ‘is not’ tell us if two values have the same identity.
1. >>> 10 is '10'

False

1. >>> True is not False

True

Q.6. Finally, tell us about bitwise operators in Python.


Python bitwise operators
Operator Description
& Binary AND
| BINARY OR
^ BINARY XOR
~ BINARY ONE’S COMPLEMENT
<< BINARY LEFT SHIFT
>> BINARY RIGHT SHIFT

Q.7. What data types does Python support?


Python provides us with five kinds of data types:
Numbers – Numbers use to hold numerical values.

1. >>> a=7.0
2. >>>

Strings – A string is a sequence of characters. We declare it using single or double quotes.

1. >>> title="Ayushi's Book"

Lists – A list is an ordered collection of values, and we declare it using square brackets.

1. >>> colors=['red','green','blue']
2. >>> type(colors)

<class ‘list’>
Tuples – A tuple, like a list, is an ordered collection of values. The difference. However, is that a
tuple is immutable. This means that we cannot change a value in it.

1. >>> name=('Ayushi','Sharma')
2. >>> name[0]='Avery'

Traceback (most recent call last):


File “<pyshell#129>”, line 1, in <module>
name[0]=’Avery’
TypeError: ‘tuple’ object does not support item assignment
Dictionary – A dictionary is a data structure that holds key-value pairs. We declare it using curly
braces.
1. >>> squares={1:1,2:4,3:9,4:16,5:25}
2. >>> type(squares)

<class ‘dict’>

1. >>> type({})

<class ‘dict’>
We can also use a dictionary comprehension:

1. >>> squares={x:x**2 for x in range(1,6)}


2. >>> squares

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}


Q.8. What is a docstring?
A docstring is a documentation string that we use to explain what a construct does. We place it
as the first thing under a function, class, or a method, to describe what it does. We declare a
docstring using three sets of single or double-quotes.

1. >>> def sayhi():


2. """
3. The function prints Hi
4. """
5. print("Hi")
6. >>> sayhi()

Hi
To get a function’s docstring, we use its __doc__ attribute.

1. >>> sayhi.__doc__

‘\n\tThis function prints Hi\n\t’


A docstring, unlike a comment, is retained at runtime.
Experiment-6
Aim:

Write a program to count the numbers of characters in the string and store
them in a dictionary data structure

Source Code:

str=input("Enter a String:")
dict = {}
for n in str:
keys = dict.keys()
if n in keys:
dict[n] += 1
else:
dict[n] = 1
print (dict)

OR
str=input("Enter a String")
dict = {}
for i in str:
dict[i] = str.count(i)
print (dict)

OR
str=input("Enter a String")
dist={}
L=len(str);
d={str:L};
print(d)

Aim:
Write a program to use split and join methods in the string and trace a
birthday of a person with a dictionary data structure

Source Code:
a="hi i am python programmer"
b=a.split()
print (b)
c=" ".join(b)
print(c)
VIVA QUESTIONS

Q.1. How would you convert a string into an int in Python?

If a string contains only numerical characters, you can convert it into an integer using the int()
function.

1. >>> int('227')

227

Let’s check the types:

1. >>> type('227')

<class ‘str’>

1. >>> type(int('227'))

<class ‘int’>

Q.2. How do you take input in Python?

For taking input from the user, we have the function input(). In Python 2, we had another
function raw_input().

The input() function takes, as an argument, the text to be displayed for the task:

1. >>> a=input('Enter a number')

Enter a number7

But if you have paid attention, you know that it takes input in the form of a string.

1. >>> type(a)

<class ‘str’>

Multiplying this by 2 gives us this:

1. >>> a*=2
2. >>> a

’77’

So, what if we need to work on an integer instead?

We use the int() function for this.


1. >>> a=int(input('Enter a number'))

Enter a number7

Now when we multiply it by 2, we get this:

1. >>> a*=2
2. >>> a

14

Q.3. What is a function?

When we want to execute a sequence of statements, we can give it a name. Let’s define a
function to take two numbers and return the greater number.

1. >>> def greater(a,b):


2. return a is a>b else b
3. >>> greater(3,3.5)

3.5

Q.4. What is recursion?


When a function makes a call to itself, it is termed recursion. But then, in order for it to avoid
forming an infinite loop, we must have a base condition.
Let’s take an example.

1. >>> def facto(n):


2. if n==1: return 1
3. return n*facto(n-1)
4. >>> facto(4)

24

Q.5. What does the function zip() do?

One of the less common functions with beginners, zip() returns an iterator of tuples.

1. >>> list(zip(['a','b','c'],[1,2,3])

[(‘a’, 1), (‘b’, 2), (‘c’, 3)]

Here, it pairs items from the two lists and creates tuples with those. But it doesn’t have to be
lists.

1. >>> list(zip(('a','b','c'),(1,2,3)))

[(‘a’, 1), (‘b’, 2), (‘c’, 3)]


Q.6. How do you calculate the length of a string?

This is simple. We call the function len() on the string we want to calculate the length of.

1. >>> len('Ayushi Sharma')

13

Q.7. Explain Python List Comprehension.


The list comprehension in python is a way to declare a list in one line of code. Let’s take a look
at one such example.

1. >>> [i for i in range(1,11,2)]

[1, 3, 5, 7, 9]

1. >>> [i*2 for i in range(1,11,2)]

[2, 6, 10, 14, 18]

Q.8. How do you get all values from a Python dictionary?

We saw previously, to get all keys from a dictionary, we make a call to the keys() method.
Similarly, for values, we use the method values().

1. >>> 'd' in {'a':1,'b':2,'c':3,'d':4}.values()

False

1. >>> 4 in {'a':1,'b':2,'c':3,'d':4}.values()

True
Experiment-7

Aim:
Write a program to count frequency of characters in a given file. Can you use
character frequency to tell whether the given file is a Python program file, C
program file or a text file?

Source Code:

import os
count =0
file=open("D:/a.txt")
for line in file:
for l in range(0,len(line)):
count+=1;
print("count:",count)
filename,file_extension=os.path.splitext("D:/a.txt");
print("file_extension==",file_extension);
if(file_extension=='.py'):
print("its python program file");
elif(file_extension==".txt"):
print("its a txt file");
elif(file_==extension==".c"):
print("its a c program file");
VIVA QUESTIONS

Q.1. What if you want to toggle case for a Python string?

We have the swapcase() method from the str class to do just that.

1. >>> 'AyuShi'.swapcase()

‘aYUsHI’

Questions 50 through 52 assume the string ‘I love Python’. You need to do the needful.
Q.2. Write code to print only upto the letter t.

1. >>> i=0
2. >>> while s[i]!='t':
3. print(s[i],end=’’)
4. i+=1

I love Py

Q.3. Write code to print everything in the string except the spaces.

1. >>> for i in s:
2. if i==' ': continue
3. print(i,end='')

IlovePython

Q.4. Now, print this string five times in a row.

1. >>> for i in range(6):


2. print(s)

I love Python
I love Python
I love Python
I love Python
I love Python
I love Python

Q.5. What is the purpose of bytes() in Python?


bytes() is a built-in function in Python that returns an immutable bytes object. Let’s take an
example.

1. >>> bytes([2,4,8])

b’\x02\x04\x08′
1. >>> bytes(5)

b’\x00\x00\x00\x00\x00′

1. >>> bytes('world','utf-8')

b’world’

Q.6. What is a control flow statement?


A Python program usually starts to execute from the first line. From there, it moves through each
statement just once and as soon as it’s done with the last statement, it transactions the program.
However, sometimes, we may want to take a more twisted path through the code. Control flow
statements let us disturb the normal execution flow of a program and bend it to our will

Q.7. Create a new list to convert the following list of number strings to a list of numbers.
nums=[‘22’,’68’,’110’,’89’,’31’,’12’]
We will use the int() function with a list comprehension to convert these strings into integers and
put them in a list.

1. >>> [int(i) for i in nums]

[22, 68, 110, 89, 31, 12]

Q.8. Given the first and last names of all employees in your firm, what data type will you
use to store it?
I can use a dictionary to store that. It would be something like this-
{‘first_name’:’Ayushi’,’second_name’:’Sharma’
Experiment-8
Aim:

Write a program to print each line of a file in reverse order.

Source Code:

input_file=open('D:/a.txt','r')
for line in input_file:
l=len(line)
s=' '
while(l>=1):
s=s+line[l-1]
l=l-1
print(s)
input_file.close()

Aim:

Write a program to compute the number of characters, words and lines in a


file.

Source Code:

k=open('D:/a.txt','r')
char,wc,lc=0,0,0
for line in k:
for k in range(0,len(line)):
char +=1
if(line[k]==' '):
wc+=1
if(line[k]=='\n'):
wc,lc=wc+1,lc+1
print("The no.of chars is %d\n The no.of words is %d\n The
no.of lines is %d"%(char,wc,lc))
VIVA QUESTIONS
Q.1. How would you work with numbers other than those in the decimal number system?
With Python, it is possible to type numbers in binary, octal, and hexadecimal.
Binary numbers are made of 0 and 1. To type in binary, we use the prefix 0b or 0B.

1. >>> int(0b1010)

10
To convert a number into its binary form, we use bin().

1. >>> bin(0xf)

‘0b1111’
Octal numbers may have digits from 0 to 7. We use the prefix 0o or 0O.

1. >>> oct(8)

‘0o10’
Hexadecimal numbers may have digits from 0 to 15. We use the prefix 0x or 0X.

1. >>> hex(16)

‘0x10’

1. >>> hex(15)

‘0xf’
Q.2. What does the following code output?

1. >>> def extendList(val, list=[]):


2. list.append(val)
3. return list
4. >>> list1 = extendList(10)
5. >>> list2 = extendList(123,[])
6. >>> list3 = extendList('a')
7. >>> list1,list2,list3

([10, ‘a’], [123], [10, ‘a’])

You’d expect the output to be something like this:


([10],[123],[‘a’])
Well, this is because the list argument does not initialize to its default value ([]) every time we
make a call to the function. Once we define the function, it creates a new list. Then, whenever we
call it again without a list argument, it uses the same list. This is because it calculates the
expressions in the default arguments when we define the function, not when we call it.

Q.3. How many arguments can the range() function take?


The range() function in Python can take up to 3 arguments. Let’s see this one by one.

a. One argument

When we pass only one argument, it takes it as the stop value. Here, the start value is 0, and the
step value is +1.

1. >>> list(range(5))

[0, 1, 2, 3, 4]

1. >>> list(range(-5))

[]

1. >>> list(range(0))

[]

b. Two arguments

When we pass two arguments, the first one is the start value, and the second is the stop value.

1. >>> list(range(2,7))

[2, 3, 4, 5, 6]

1. >>> list(range(7,2))

[]

1. >>> list(range(-3,4))

[-3, -2, -1, 0, 1, 2, 3]

c. Three arguments

Here, the first argument is the start value, the second is the stop value, and the third is the step
value.

1. >>> list(range(2,9,2))

[2, 4, 6, 8]

1. >>> list(range(9,2,-1))

[9, 8, 7, 6, 5, 4, 3]

Q.4. What is PEP 8?


PEP 8 is a coding convention that lets us write more readable code. In other words, it is a set of
recommendations.

Q.5. How is Python different from Java

Q.6. What is the best code you can write to swap two numbers?

I can perform the swapping in one statement.

1. >>> a,b=b,a

Here’s the entire code, though-

1. >>> a,b=2,3
2. >>> a,b=b,a
3. >>> a,b

(3, 2)

Q.7. How can you declare multiple assignments in one statement?

There are two ways to do this:

First –

1. >>> a,b,c=3,4,5 #This assigns 3, 4, and 5 to a, b, and c respectively

Second –

1. >>> a=b=c=3 #This assigns 3 to a, b, and c


Q.8. If you are ever stuck in an infinite loop, how will you break out of it?

For this, we press Ctrl+C. This interrupts the execution. Let’s create an infinite loop to
demonstrate this.

1. >>> def counterfunc(n):


2. while(n==7):print(n)
3. >>> counterfunc(7)

Traceback (most recent call last):

File “<pyshell#332>”, line 1, in <module>


counterfunc(7)

File “<pyshell#331>”, line 2, in counterfunc

while(n==7):print(n)

KeyboardInterrupt
Experiment-9
Aim:

Write a function nearly equal to test whether two strings are nearly equal. Two strings a and b
are nearly equal when a can be generated by a single mutation.

Source Code:

from difflib import SequenceMatcher


def Nearly_Equal(a,b):
return SequenceMatcher(None,a,b).ratio();
a="khit"
b="khitc"
c=Nearly_Equal(a,b)
if(c*100>80):
print("Both Strings are similar")
print("a is mutation on b")
else:
print("Both Strings are Different")

Output:
Both Strings are similar
a is mutation on b

Aim:

Write function to compute gcd, lcm of two numbers. Each function shouldn’t exceed one line.

Source Code:

import fractions
n1 = int(input("Enter n1 value:"))
n2 = int(input("Enter n2 value:"))
gcd = fractions.gcd(n1, n2)
print("GCD value is:",gcd)
def lcm(n, m):
return n * m / gcd
print("LCM value is:",int(lcm(n1,n2)))

Output:
Enter n1 value:6
Enter n2 value:12
GCD value is: 6
LCM value is: 12
VIVA QUESTIONS

Q.1. How do we execute Python?

Python files first compile to bytecode. Then, the host executes them.

Q.2. Explain Python’s parameter-passing mechanism.

To pass its parameters to a function, Python uses pass-by-reference. If you change a parameter
within a function, the change reflects in the calling function. This is its default behavior.
However, when we pass literal arguments like strings, numbers, or tuples, they pass by value.
This is because they are immutable.

Q.3. What is the with statement in Python?

The with statement in Python ensures that cleanup code is executed when working with
unmanaged resources by encapsulating common preparation and cleanup tasks. It may be used to
open a file, do something, and then automatically close the file at the end. It may be used to open
a database connection, do some processing, then automatically close the connection to ensure
resources are closed and available for others. with will cleanup the resources even if an exception
is thrown. This statement is like the using statement in C#.
Consider you put some code in a try block, then in the finally block, you close any resources
used. The with statement is like syntactic sugar for that.

The syntax of this control-flow structure is:

with expression [as variable]:


….with-block

1. >>> with open('data.txt') as data:


2. #processing statements

Q.4. How is a .pyc file different from a .py file?

While both files hold bytecode, .pyc is the compiled version of a Python file. It has platform-
independent bytecode. Hence, we can execute it on any platform that supports the .pyc format.
Python automatically generates it to improve performance(in terms of load time, not speed).

Q.5. What makes Python object-oriented?

Python is object-oriented because it follows the Object-Oriented programming paradigm. This is


a paradigm that revolves around classes and their instances (objects). With this kind of
programming, we have the following features:

• Encapsulation
• Abstraction
• Inheritance
• Polymorphism
• Data hiding

Q.6. How many types of objects does Python support?

Objects in Python are mutable and immutable.

Immutable objects- Those which do not let us modify their contents. Examples of these will be
tuples, booleans, strings, integers, floats, and complexes. Iterations on such objects are faster.

1. >>> tuple=(1,2,4)
2. >>> tuple

(1, 2, 4)

1. >>> 2+4j

(2+4j)

Mutable objects – Those that let you modify their contents. Examples of these are lists, sets, and
dicts. Iterations on such objects are slower.

1. >>> [2,4,9]

[2, 4, 9]

1. >>> dict1={1:1,2:2}
2. >>> dict1

{1: 1, 2: 2}

While two equal immutable objects’ reference variables share the same address, it is possible to
create two mutable objects with the same content.
Experiment-10
Aim:

Write a program to implement Merge sort.

Source Code:

# Python program for implementation of MergeSort


def mergeSort(arr):
if len(arr) >1:
mid = len(arr)//2 #Finding the mid of the array
L = arr[:mid] # Dividing the array elements
R = arr[mid:] # into 2 halves

mergeSort(L) # Sorting the first half


mergeSort(R) # Sorting the second half

i=j=k=0

# Copy data to temp arrays L[] and R[]


while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i+=1
else:
arr[k] = R[j]
j+=1
k+=1

# Checking if any element was left


while i < len(L):
arr[k] = L[i]
i+=1
k+=1

while j < len(R):


arr[k] = R[j]
j+=1
k+=1

# Code to print the list


def printList(arr):
for i in range(len(arr)):
print(arr[i],end=" ")
print()

# driver code to test the above code


if __name__ == '__main__':
arr = [12, 11, 13, 5, 6, 7]
print ("Given array is", end="\n")
printList(arr)
mergeSort(arr)
print("Sorted array is: ", end="\n")
printList(arr)

Output:

Given array is
12 11 13 5 6 7
Sorted array is:
5 6 7 11 12 13

Aim:

Write a program to implement Selection sort, Insertion sort.Selection Sort

Source Code:
# Python program for implementation of Selection
# Sort
import sys
A = [64, 25, 12, 22, 11]

# Traverse through all array elements


for i in range(len(A)):

# Find the minimum element in remaining


# unsorted array
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j

# Swap the found minimum element with


# the first element
A[i], A[min_idx] = A[min_idx], A[i]

# Driver code to test above


print ("Sorted array")
for i in range(len(A)):
print("%d" %A[i]),

Output:

Sorted array
11
12
22
25
64

Source Code:

# Python program for implementation of Insertion Sort

# Function to do insertion sort


def insertionSort(arr):

# Traverse through 1 to len(arr)


for i in range(1, len(arr)):

key = arr[i]

# Move elements of arr[0..i-1], that are


# greater than key, to one position ahead
# of their current position
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key

# Driver code to test above


arr = [12, 11, 13, 5, 6]
insertionSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
print ("%d" %arr[i])

Output:

Sorted array is:


5
6
11
12
13
VIVA QUESTIONS
Q.1.Why is it called Python?
Ans: When he began implementing Python, Guido van Rossum was also reading the published
scripts from “Monty Python‘s Flying Circus”, a BBC comedy series from the 1970s. Van
Rossum thought he needed a name that was short, unique, and slightly mysterious, so he decided
to call the language Python.

Q.2.What is the interpreter in Python?


Ans: An interpreter is a program that reads and executes code. This includes source code, pre-
compiled code, and scripts. Common interpreters include Perl, Python, and Ruby interpreters,
which execute Perl, Python, and Ruby code respectivel

Q.3.What does a python do?


Ans: Python is a general-purpose programming language typically used for web development.
… SQLite is one free lightweight database commonly used by Python programmers to store
data. Many highly trafficked websites, such as YouTube, are created using Python.

Q.4.What is the purpose of PYTHONHOME environment variable?


Ans: PYTHONHOME − It is an alternative module search path. It is usually embedded in the
PYTHONSTARTUP or PYTHONPATH directories to make switching module libraries easy.

Q.5.What is the purpose of PYTHONCASEOK environment variable?


Ans: PYTHONCASEOK − It is used in Windows to instruct Python to find the first case-
insensitive match in an import statement. Set this variable to any value to activate it.

Q.6.What is the purpose of PYTHONSTARTUP environment variable?


Ans: PYTHONSTARTUP – It contains the path of an initialization file containing Python source
code. It is executed every time you start the interpreter. It is named as .pythonrc.py in Unix and it
contains commands that load utilities or modify PYTHONPATH.

Q.7.What is the purpose of PYTHONPATH environment variable?


Ans: PYTHONPATH – It has a role similar to PATH. This variable tells the Python interpreter
where to locate the module files imported into a program. It should include the Python source
library directory and the directories containing Python source code. PYTHONPATH is
sometimes preset by the Python installer.

Q.8.If given the first and last names of bunch of employees how would you store it and
what datatype?

Ans: best stored in a list of dictionaries..


dictionary format: {‘first_name’:’Ayush’,’last_name’:’Goel’}

You might also like