0% found this document useful (0 votes)
13 views120 pages

Python Lab Manual 2025

The Python Lab Manual for the Department of Civil Engineering outlines practical work for B. Tech students during the 2024-2025 academic year, emphasizing basic Python programming skills applicable to engineering. It includes a variety of programming exercises, safety precautions, general instructions, and institutional missions aimed at fostering innovation and ethical engineering practices. The manual serves as a comprehensive resource for students to develop scientific reasoning and technical proficiency in Python programming.
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)
13 views120 pages

Python Lab Manual 2025

The Python Lab Manual for the Department of Civil Engineering outlines practical work for B. Tech students during the 2024-2025 academic year, emphasizing basic Python programming skills applicable to engineering. It includes a variety of programming exercises, safety precautions, general instructions, and institutional missions aimed at fostering innovation and ethical engineering practices. The manual serves as a comprehensive resource for students to develop scientific reasoning and technical proficiency in Python programming.
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/ 120

PYTHON LAB

MANUAL

DEPARTMENT OF CIVIL ENGINEERING

2024-2025
CERTIFICATE

This is to certify that this manual is a bonafide record of practical work in the

Python Lab in Second Semester of Second Year B. Tech (Civil) programme

during the academic year 2024-25. The book is prepared by Ms. Nanditha

Mandava, Associate Professor Department of Civil Engineering.

Signature of HOD Signature of Dean Academics Signature of Principal


INDEX

S. No CONTENT PAGE NO
1 PREFACE i
2 ACKNOWLEDGEMENT ii
3 GENERAL INSTRUCTIONS iii
4 SAFETY PRECAUTIONS iv
5 INSTITUTE VISION AND MISSION v
6 DEPARTMENT VISION AND MISSION v

7 PROGRAMME EDUCATIONAL OBJECTIVES vi


8 PROGRAM SPECIFIC OUTCOMES vi
9 PROGRAMME OUTCOMES vii - viii
10 COURSE STRUCTURE, OBJECTIVES AND OUTCOMES ix – xi

11 PYTHON NUMBERS 1

a) WRITE A PROGRAM TO DETERMINE WHETHER A GIVEN YEAR


IS A LEAP YEAR, USING THE FOLLOWING FORMULA: A LEAP
YEAR IS ONE THAT IS DIVISIBLE BY FOUR, BUT NOT BY ONE
12 HUNDRED, UNLESS IT IS ALSO DIVISIBLE BY FOUR HUNDRED. 1
FOR EXAMPLE, 1992, 1996, AND 2000 ARE LEAP YEARS, BUT
1967 AND 1900 ARE NOT. THE NEXT LEAP YEAR FALLING ON A
CENTURY IS 2400.

b) WRITE A PROGRAM TO DETERMINE THE GREATEST COMMON


13 DIVISOR AND LEAST COMMON MULTIPLE OF A PAIR OF 2–3
INTEGERS.

c) CREATE A CALCULATOR APPLICATION. WRITE CODE THAT


WILL TAKE TWO NUMBERS AND AN OPERATOR IN THE
FORMAT: N1 OP N2, WHERE N1 AND N2 ARE FLOATING POINT
OR INTEGER VALUES, AND OP IS ONE OF THE FOLLOWING: +, -,
14 4 – 10
*, /, %, **, REPRESENTING ADDITION, SUBTRACTION,
MULTIPLICATION, DIVISION, MODULUS/REMAINDER, AND
EXPONENTIATION, RESPECTIVELY, AND DISPLAYS THE
RESULT OF CARRYING OUT THAT OPERATION ON THE INPUT
INDEX
OPERANDS.

15 CONTROL FLOW 11

16 a) WRITE A PROGRAM FOR CHECKING WHETHER THE GIVEN 11 – 12


NUMBER IS A PRIME NUMBER OR NOT.

17 b) WRITE A PROGRAM TO PRINT FIBONACCI SERIES UPTO 13


GIVEN N VALUE.

18 c) WRITE A PROGRAM TO CALCULATE FACTORIAL OF GIVEN 14 – 23


INTEGER NUMBER.
19 CONTROL FLOW - CONTINUED 24

a) WRITE A PROGRAM TO CALCULATE VALUE OF THE


20 24
FOLLOWING SERIES 1+x-x2+x3-x4+…………….xn.

21 b) WRITE A PROGRAM TO PRINT PASCAL TRIANGLE. 25 – 32

22 PYTHON - SEQUENCES 33

a) WRITE A PROGRAM TO SORT THE NUMBERS IN


23 ASCENDING ORDER AND STRINGS IN REVERSE 33 – 34
ALPHABETICAL ORDER.

b) GIVEN AN INTEGER VALUE, RETURN A STRING WITH THE


EQUIVALENT ENGLISH TEXT OF EACH DIGIT. FOR
24 35 – 39
EXAMPLE, AN INPUT OF 89 RESULTS IN "EIGHT-NINE"
BEING RETURNED. WRITE A PROGRAM TO IMPLEMENT IT.

25 PYTHON - SEQUENCES 40

a) WRITE A PROGRAM TO CREATE A FUNCTION THAT WILL


RETURN ANOTHER STRING SIMILAR TO THE INPUT
26 STRING, BUT WITH ITS CASE INVERTED. FOR EXAMPLE, 40
INPUT OF "Mr. Ed" WILL RESULT IN "mR.eD" AS THE
OUTPUT STRING.
b) WRITE A PROGRAM TO TAKE A STRING AND APPEND A
27 BACKWARD COPY OF THAT STRING, MAKING A 41 – 44
PALINDROME.
INDEX
28 PYTHON DICTIONARIES 45

29 a) WRITE A PROGRAM TO CREATE A DICTIONARY AND 45


DISPLAY ITS KEYS ALPHABETICALLY.

b) WRITE A PROGRAM TO TAKE A DICTIONARY AS INPUT


30 AND RETURN ONE AS OUTPUT, BUT THE VALUES ARE NOW 46 – 50
THE KEYS AND VICE VERSA.

31 FILES 51

a) WRITE A PROGRAM TO COMPARE TWO TEXT FILES. IF


THEY ARE DIFFERENT, GIVE THE LINE AND COLUMN
32 51 – 52
NUMBERS IN THE FILES WHERE THE FIRST DIFFERENCE
OCCURS.

b) WRITE A PROGRAM TO COMPUTE THE NUMBER OF


33 53 – 58
CHARACTERS, WORDS AND LINES IN A FILE

34 FUNCTIONS 59

a) WRITE A FUNCTION BALL COLLIDE THAT TAKES TWO


BALLS AS PARAMETERS AND COMPUTES IF THEY ARE
COLLIDING. YOUR FUNCTION SHOULD RETURN A
35 BOOLEAN REPRESENTING WHETHER OR NOT THE BALLS 59 – 61
ARE COLLIDING.
HINT: REPRESENT A BALL ON A PLANE AS A TUPLE OF (x, y,
r), r BEING THE RADIUS

b) IF (DISTANCE BETWEEN TWO BALLS CENTERS) <= (SUM OF


36 59 – 61
THEIR RADII) THEN (THEY ARE COLLIDING)

c) FIND MEAN, MEDIAN, MODE FOR THE GIVEN SET OF


37 62 – 63
NUMBERS IN A LIST.

d) WRITE SIMPLE FUNCTIONS MAX2() AND MIN2() THAT TAKE


TWO ITEMS AND RETURN THE LARGER AND SMALLER
ITEM, RESPECTIVELY. THEY SHOULD WORK ON
38 64 – 70
ARBITRARY PYTHON OBJECTS. FOR EXAMPLE, MAX2(4, 8)
AND MIN2(4, 8) WOULD EACH RETURN 8 AND 4,
RESPECTIVELY.
INDEX
39 FUNCTIONS - CONTINUED 71

a) WRITE A FUNCTION NEARLY EQUAL TO TEST WHETHER


TWO STRINGS ARE NEARLY EQUAL. TWO STRINGS a AND
40 71 – 73
b ARE NEARLY EQUAL WHEN A CAN BE GENERATED BY A
SINGLE MUTATION ON b.

b) WRITE A FUNCTION DUPS TO FIND ALL DUPLICATES IN


41 74
THE LIST.

42 c) WRITE A FUNCTION UNIQUE TO FIND ALL THE UNIQUE 75 – 79


ELEMENTS OF A LIST.
43 FUNCTIONS – PROBLEM SOLVING 80

a) WRITE A FUNCTION CUMULATIVE_ PRODUCT TO


44 COMPUTE CUMULATIVE PRODUCT OF A LIST OF 80
NUMBERS.

b) WRITE A FUNCTION REVERSE TO REVERSE A LIST.


45 81
WITHOUT USING THE REVERSE FUNCTION

c) WRITE FUNCTION TO COMPUTE GCD, LCM OF TWO


46 NUMBERS. EACH FUNCTION SHOULDN’T EXCEED ONE 82 – 86
LINE.

47 GUI, GRAPHICS 87

a) WRITE A GUI FOR AN EXPRESSION CALCULATOR USING


47 87 – 91
TK

48 92 – 98

b) WRITE A PROGRAM TO IMPLEMENT THE FOLLOWING


FIGURES USING TURTLE
49 DATA BASES 99

a) DEVELOP A PYTHON APPLICATION TO CREATE A TABLE,


INSERT ROWS INTO THE TABLE, UPDATES ROWS IN THE
50 99 – 103
TABLE, DELETE ROWS FROM THE TABLE AND DROPS THE
TABLE. [ Use MySql ]
PREFACE
This book entitled “Python Programming Lab Manual” is intended for the use of fourth

semester (i.e., II - II) B. Tech (civil) students of Marri laxman Reddy Institute of Technology

and Management, Dundigal, Hyderabad. The main objective of the Python Programming Lab

Manual is to teach the student basic python fundamentals in various engineering applications.

This book lays foundation of certain basic concepts and skills that can be repeatedly employed

by the students in their future endeavours. The main aim of this book is to develop the habit of

scientific reasoning and providing answers to all the doubts that arise during the course of

conducting experiments. The book was written as per the new syllabus prescribed by the

JNTUH university in a simple language. Some of the additional experiments apart from the

syllabus also included in the book. These experiments will help the students to expertise in the

analysis and reporting the water quality for drinking purpose. Hence, we hope this book serve

for better understanding by the student community with all details of experiments

By,
Ms. Nanditha Mandava
Assoc Professor,
Department of civil engineering

i
ACKNOWLEDGEMENT

It was really a good experience, working at Python Programming Lab. First, I would like to
thank Dr. M. Saravanan, Head of the Department of Civil Engineering, Marri Laxman Reddy
Institute of technology & Management for giving the technical support in preparing the
document.

I express my sincere thanks to Dr. R. Murali Prasad, Principal, Marri Laxman Reddy Institute
of technology & Management, for his concern towards me and gave me opportunity to prepare
Python Programming laboratory manual.

I express my hearty thanks to Dr. P. Sridhar, Director, Marri Laxman Reddy Institute of
technology & Management, for giving me this wonderful opportunity for preparing the Python
Programming laboratory manual.

At last, but not the least I would like to thank the entire Civil Department faculties those who
had inspired and helped me to achieve my goal.

By,
Ms. Nanditha Mandava
Assoc Professor,
Department of civil engineering

ii
GENERAL INSTRUCTIONS
1. Students are instructed to come to Python Programming laboratory on time. Late comers
are not entertained in the lab.

2. Students should be punctual to the lab. If not, conducted experiments will not be repeated.

3. Students are expected to come prepared at home with the experiments which are going to
performed.

4. Students are instructed to display their identity cards and apron before entering into the
lab.

5. Students are instructed not to bring mobile phones to the lab.

6. The equipment’s and other accessories used in Python Programming lab should be
handled with care and responsibility.

7. Any damage to the equipment’s during the lab session is student’s responsibility and
penalty or fine will be collected from the student.

8. Students should update the records and lab observation books session wise. Before
leaving the lab, the student should get his lab observation book signed by the faculty.

9. Students should submit the lab records 2/3 days in advance to the concerned faculty
members in the staffroom for their correction and return.

10. Students should not move around the lab during the lab session.

11. If any emergency arises, the student should take the permission from faculty member
concerned in written format.

12. The faculty members may suspend any student from the lab session on disciplinary
grounds.

iii
SAFETY PRECAUTIONS

1. While working in the laboratory suitable precautions should be observed to


prevent accidents.

2. Always follow the experimental instructions strictly.

3. Use the first aid box in case of any accident/mishap.

4. Never work in the laboratory unless a demonstrator or teaching assistant in present.

5. When the experiment is completed, students should disconnect the setup made by
them, and should return all the components/instruments taken for the purpose.

iv
INSTITUTION VISION AND MISSION

VISION
To be a globally recognized institution that fosters innovation, excellence, and leadership in
education, research, and technology development, empowering students to create sustainable
solutions for the advancement of society.

MISSION
 To foster a transformative learning environment that empowers students to excel in
engineering, innovation, and leadership.
 To produce skilled, ethical, and socially responsible engineers who contribute to
sustainable technological advancements and address global challenges.
 To shape future leaders through cutting-edge research, industry collaboration, and
community engagement.

DEPARTMENT VISION, MISSION, PROGRAMME EDUCATIONAL OBJECTIVES

AND SPECIFIC OUTCOMES

VISION

To empower students to be skilled, competitive, and dedicated Civil Engineers by imparting


advanced technical knowledge and ethical values, equipping them to play a key role in the
planning and execution of the nation's infrastructure and development activities.

MISSION

M1: Provide exceptional education in civil engineering through a combination of excellent


teaching, advanced facilities, and continuous mentorship.
M2: Produce civil engineering graduates who demonstrate exceptional skills and expertise.
M3: Encourage professional development to address complex technical challenges and
engage in innovation with creativity, leadership, ethics, and social awareness.

v
PROGRAMME EDUCATIONAL OBJECTIVES

PEO-I: Professional Excellence

Analyze, design, build, maintain, or improve civil engineering-based systems, considering


environmental, economic, and societal requirements.

PEO-II: Multidisciplinary Approach

Develop a strong educational foundation to design and conduct experiments, meeting needs
within multidisciplinary constraints such as economic, environmental, social, political, ethical,
health and safety, manufacturability, and sustainability, while analyzing and interpreting data.
PEO-III: Continued Self-Learning

Identify, formulate, and solve engineering problems, and engage in lifelong learning in
advanced areas of civil engineering and related fields.

PEO-IV: Effective Contribution to Society

Utilize modern engineering techniques, skills, and tools necessary for civil engineering
practice, serving the community as ethical and responsible professionals.

PROGRAM SPECIFIC OUUTCOMES

PSO1:

Demonstrate the ability to plan, design, implement, and supervise civil engineering systems in
various sectors

PSO2:

Focus on safety, serviceability, and eco-friendly technologies while operating, maintaining,


and rehabilitating civil engineering systems.

PSO3:

Utilize advanced civil engineering technologies to continue education, achieve entrepreneurial


success, and explore various career options.

vi
PROGRAMME OUT COMES
1. PO1: Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering
problems.
2. PO2: Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
3. PO3: Design/development of solutions: Design solutions for complex engineering problems
and design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
4. PO4: Conduct investigations of complex problems: Use research-based knowledge and
research methods including design of experiments, analysis and interpretation of data, and
synthesis of the information to provide valid conclusions.
5. PO5: Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex engineering
activities with an understanding of the limitations
6. PO6: The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
7. PO7: Environment and sustainability: Understand the impact of the professional
engineering solutions in societal and environmental contexts, and demonstrate the knowledge
of, and need for sustainable development.
8. PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
9. PO9: Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
10. PO10: Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.
11. PO11: Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.

vii
12. PO12: Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological change.

viii
COURSE STRUCTURE, OBJECTIVES & OUTCOMES

COURSE STRUCTURE

Python Programming lab will have a continuous evaluation during 4th semester for 40 sessional
marks and 60 end semester examination marks.

Out of the 40 marks for internal evaluation, day-to-day work in the laboratory shall be evaluated
for 20 marks and internal practical examination shall be evaluated for 20 marks conducted by
the laboratory teacher concerned.

The end semester examination shall be conducted with an external examiner and internal
examiner. The external examiner shall be appointed by the principal / Chief Controller of
examinations
COURSE OBJECTIVE

The objective of this lab is to teach the student basic python fundamentals in various
engineering applications.
COURSE OUTCOMES

At the end of the course, the student will be able to:


1. Examine Python syntax and semantics and be fluent in the use of Python flow control and
functions.
2. Create, run and manipulate Python Programs using core data structures like Lists,
Dictionaries.
3. Demonstrate proficiency in handling Exceptions, Functions and Modules.
4. Develop programs using graphical user interface.
5. Learn about Database Programming and Web development.

LIST OF EXPERIMENTS
Exercise 1 –Python Numbers
a) Write a program to determine whether a given year is a leap year, using the following
formula: a leap year is one that is divisible by four, but not by one hundred, unless it is also
divisible by four hundred. For example, 1992, 1996, and 2000 are leap years, but 1967 and
1900 are not. The next leap year falling on a century is 2400.
b) Write a program to determine the greatest common divisor and least common multiple of a
pair of integers.

ix
c) Create a calculator application. Write code that will take two numbers and an operator in
the format: N1 OP N2, where N1 and N2 are floating point or integer values, and OP is one
of the following: +, -, *, /, %, **, representing addition, subtraction, multiplication, division,
modulus/remainder, and exponentiation, respectively, and displays the result of carrying out
that operation on the input operands.
Hint: You may use the string split() method, but you cannot use the exal () built-in function.

Exercise –2 Control Flow


a) Write a Program for checking whether the given number is a prime number or not.
b) Write a program to print Fibonacci series upto given n value.
c) Write a program to calculate factorial of given integer number.

Exercise 3 Control Flow -Continued


a) Write a program to calculate value of the following series 1+x-x2+x3-x4+……..xn.
b) Write a program to print Pascal triangle.

Exercise 4 – Python Sequences


a) Write a program to sort the numbers in ascending order and strings in reverse
alphabetical order.
b) Given an integer value, return a string with the equivalent English text of each digit. For
example, an input of 89 results in "eight-nine" being returned. Write a program to
implement it.

Exercise 5– Python Sequences


a) Write a program to create a function that will return another string similar to the input string,
but with its case inverted. For example, input of "Mr. Ed" will result in "mR.eD" as the
output string.
b) Write a program to take a string and append a backward copy of that string, making a
palindrome.

Exercise 6– Python Dictionaries


a) Write a program to create a dictionary and display its keys alphabetically.
b) Write a program to take a dictionary as input and return one as output, but the values are
now the keys and vice versa.

Exercise - 7 Files
a) Write a program to compare two text files. If they are different, give the line and column
numbers in the files where the first difference occurs.
b) Write a program to compute the number of characters, words and lines in a file.

x
Exercise - 8 Functions
a) Write a function ball collide that takes two balls as parameters and computes if they are
colliding. Your function should return a Boolean representing whether or not the balls are
colliding.
Hint: Represent a ball on a plane as a tuple of (x, y, r), r being the radius
b) If (distance between two balls centers) <= (sum of their radii) then (they are colliding)
c) Find mean, median, mode for the given set of numbers in a list.
d) Write simple functions max2() and min2() that take two items and return the larger and
smaller item, respectively. They should work on arbitrary Python objects. For example,
max2(4, 8) and min2(4, 8) would each return 8 and 4, respectively.

Exercise - 9 Functions - Continued


a) 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 on b.
b) Write a function dups to find all duplicates in the list.
c) Write a function unique to find all the unique elements of a list.

Exercise - 10 - Functions - Problem Solving


a) Write a function cumulative_ product to compute cumulative product of a list of
numbers.
b) Write a function reverse to reverse a list. Without using the reverse function.
c) Write function to compute GCD, LCM of two numbers. Each function shouldn’t
exceed one line.

Exercise - 11 GUI, Graphics


a) Write a GUI for an Expression Calculator using tk
b) Write a program to implement the following figures using turtle

Exercise- 12 Data Bases


a) Develop a Python application to create a table, Insert rows into the table, Updates rows in
the table, Delete rows from the table and Drops the table. [ Use MySql ]

xi
EXPERIMENT 1
PYTHON NUMBERS
a) Write a program to determine whether a given year is a leap year, using the following
formula: a leap year is one that is divisible by four, but not by one hundred, unless it is
also divisible by four hundred. For example, 1992, 1996, and 2000 are leap years, but 1967
and 1900 are not. The next leap year falling on a century is 2400.

EXPLANATION:
1. First condition: The year must be divisible by 4.
2. Second condition: If divisible by 4, it must not be divisible by 100 unless it is also
divisible by 400.
3. The function returns True if the year is a leap year, and False if it's not.
For example:
 Inputting 2000 will output: 2000 is a leap year.
 Inputting 1900 will output: 1900 is not a leap year.

PROCEDURE:
def is_leap_year(year):
# Check if the year is divisible by 4
if year % 4 == 0:
# Check if the year is divisible by 100
if year % 100 == 0:
# Check if the year is divisible by 400
if year % 400 == 0:
return True
else:
return False
else:
return True
else:
return False

# Directly provide the year here (instead of asking for user input)
year = 2024 # You can change this to any year you want to test

if is_leap_year(year):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")

OUTPUT:
2024 is a leap year

1
b) Write a program to determine the greatest common divisor and least common multiple of
a pair of integers.
AIM:
Write a program to determine the greatest common divisor and least common multiple of a pair
of integers.
EXPLANATION:
The Euclidean algorithm is a method for finding the Greatest Common Divisor (GCD) of
two integers. It works on the principle that the GCD of two numbers also divides their
difference. Here's how it works step by step:

Steps to Calculate GCD using Euclidean Algorithm


1. Start with two numbers, a and b.
2. Replace ‘a’ with ‘b’ and ‘b’ with a % b (the remain nder when a is divided by b).
3. Repeat the process until b becomes 0.
4. When b becomes 0, the value of a is the GCD of the original two numbers.

Example

Let’s calculate the GCD of 48 and 18 using the Euclidean algorithm:

1. Start with a = 48 and b = 18.

 First, divide 48 by 18, the remainder is 48 % 18 = 12.


 Now, replace a = 18 and b = 12.

2. Now, a = 18 and b = 12.

 Divide 18 by 12, the remainder is 18 % 12 = 6.


 Now, replace a = 12 and b = 6.

3. Now, a = 12 and b = 6.

 Divide 12 by 6, the remainder is 12 % 6 = 0.


 Now, replace a = 6 and b = 0.

4. Since b is now 0, the GCD is the current value of a, which is 6.

Thus, the GCD of 48 and 18 is 6.

Example for LCM


Let’s say a = -4 and b = 6:

 The product a * b = -4 * 6 = -24.


 Using abs(-24) will give you 24, which is the positive value of the product.

2
In the context of the LCM formula:

PROCEDURE:
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
# Function to calculate LCM
def lcm(a, b):
return abs(a * b) // gcd(a, b)
# Get user input for two integers
a = 48
b = 18
# Calculate GCD and LCM
gcd_value = gcd(a, b)
lcm_value = lcm(a, b)

# Print the results


print(f"The Greatest Common Divisor (GCD) of {a} and {b} is:
{gcd_value}")
print(f"The Least Common Multiple (LCM) of {a} and {b} is:
{lcm_value}")

OUTPUT:
The Greatest Common Divisor (GCD) of 48 and 18 is:6
The Least Common Multiple (LCM) of 48 and 18 is:144

3
c) Create a calculator application. Write code that will take two numbers and an operator
in the format: N1 OP N2, where N1 and N2 are floating point or integer values, and OP is
one of the following: +, -, *, /, %, **, representing addition, subtraction, multiplication,
division, modulus/remainder, and exponentiation, respectively, and displays the result of
carrying out that operation on the input operands.
Hint: You may use the string split() method, but you cannot use the exal () built-in function.

AIM:

Create a calculator application. Write code that will take two numbers and an operator in the
format: N1 OP N2, where N1 and N2 are floating point or integer values, and OP is one of the
following: +, -, *, /, %, **, representing addition, subtraction, multiplication, division,
modulus/remainder, and exponentiation, respectively, and displays the result of carrying out
that operation on the input operands.

PROCEDURE:
# Step 1: Define the expression
expression = "5 + 3" # The input should be a string

# Step 2: Split the input into three parts


parts = expression.split() # This splits the input into a list like
["5", "+", "3"]

# Step 3: Check if the input has exactly 3 parts


if len(parts) != 3:
print("Invalid input format.")
else:
# Step 4: Extract the numbers and operator
try:
n1 = float(parts[0]) # First number (e.g., 5)
op = parts[1] # Operator (e.g., +)
n2 = float(parts[2]) # Second number (e.g., 3)

# Step 5: Perform the calculation based on the operator


if op == '+':
result = n1 + n2
elif op == '-':
result = n1 - n2
elif op == '*':
result = n1 * n2
elif op == '/':
if n2 == 0:
result = "Error: Division by zero!"
else:
result = n1 / n2

4
elif op == '%':
result = n1 % n2
elif op == '**':
result = n1 ** n2
else:
result = "Error: Invalid operator!"

# Step 6: Display the result


print("Result:", result)
except ValueError:
print("Invalid input: numbers must be numeric.")

OUTPUT:
8.0

EXPLANATION

1. Input Format: You will enter the numbers and operator as a single string (e.g., "5 + 3").
2. String Splitting: We will use the split() method to break the input into parts (numbers and
operator).
3. Operations: Based on the operator, the corresponding arithmetic operation will be
performed.
4. Result: The program will display the result of the operation.

STEP-BY-STEP BREAKDOWN

1. Input: The program asks the user to input the calculation (e.g., "5 + 3").
2. String Split: split() method divides the input string into three parts:

 parts[0]: First number (N1)


 parts[1]: Operator (OP)
 parts[2]: Second number (N2)

3. Convert to Floats: Both N1 and N2 are converted to floats using float(). This ensures we can
handle both integers and floating-point numbers.
4. Check Operator: The program checks which operator is used and performs the
corresponding operation.

 If operator is +, it adds the two numbers.


 If operator is -, it subtracts.
 If operator is *, it multiplies.
 If operator is /, it divides (but checks if the second number is not zero).
5
 If operator is %, it calculates the remainder (modulus).
 If operator is **, it calculates the exponentiation (power).

5. Result: Finally, the program outputs the result in a readable format.

6
VIVA QUESTIONS:

1) What is Python? What are the benefits of using Python?


Python is a programming language with objects, modules, threads, exceptions and
automatic memory management. The benefits of pythons are that it is simple and easy,
portable, extensible, build-in data structure and it is an open source.

2) What is PEP 8?
PEP 8 is a coding convention, a set of recommendation, about how to write your Python code
more readable.

3) What is pickling and unpickling?


Pickle module accepts any Python object and converts it into a string representation and
dumps it into a file by using dump function, this process is called pickling. While the
process of retrieving original Python objects from the stored string representation is called
unpickling.

4) How Python is interpreted?


Python language is an interpreted language. Python program runs directly from the source
code. It converts the source code that is written by the programmer into an intermediate
language, which is again translated into machine language that has to be executed.

5) How memory is managed in Python?


 Python memory is managed by Python private heap space. All Python objects and data

structures are located in a private heap. The programmer does not have an access to this
private heap and interpreter takes care of this Python private heap.
 The allocation of Python heap space for Python objects is done by Python memory

manager. The core API gives access to some tools for the programmer to code.
 Python also have an inbuilt garbage collector, which recycle all the unused memory

and frees the memory and makes it available to the heap space.

6) What are the tools that help to find bugs or perform static analysis?
PyChecker is a static analysis tool that detects the bugs in Python source code and warns
about the style and complexity of the bug. Pylint is another tool that verifies whether the
module meets the coding standard.

7
7) What are Python decorators?
A Python decorator is a specific change that we make in Python syntax to alter functions easily.

8) What is the difference between list and tuple?


The difference between list and tuple is that list is mutable while tuple is not. Tuple can
be hashed for e.g as a key for dictionaries.

9) How are arguments passed by value or by reference?


Everything in Python is an object and all variables hold references to the objects. The
references values are according to the functions; as a result you cannot change the value
of the references. However, you can change the objects if it is mutable.

10) What is Dict and List comprehensions are?


They are syntax constructions to ease the creation of a Dictionary or List based on existing
iterable.

11) What are the built-in type does python provides?


There are mutable and Immutable types of Pythons built in types Mutable built-in types
 List

 Sets

 Dictionaries Immutable built-in types

 Strings

 Tuples

12) What is namespace in Python?


In Python, every name introduced has a place where it lives and can be hooked for. This
is known as namespace. It is like a box where a variable name is mapped to the object
placed. Whenever the variable is searched out, this box will be searched, to get
corresponding object.
13) What is lambda in Python?
It is a single expression anonymous function often used as inline function.

14) Why lambda forms in python does not have statements?


A lambda form in python does not have statements as it is used to make new function
object and then return them at runtime.

8
15) What is pass in Python?
Pass means, no-operation Python statement, or in other words it is a place holder in
compound statement, where there should be a blank left and nothing has to be written
there.

16) In Python what are iterators?


In Python, iterators are used to iterate a group of elements, containers like list.

17) What is unittest in Python?


A unit testing framework in Python is known as unittest. It supports sharing of setups,
automation testing, shutdown code for tests, aggregation of tests into collections etc.

18) In Python what is slicing?


A mechanism to select a range of items from sequence types like list, tuple, strings etc. is known
as slicing.

19) What are generators in Python?


The way of implementing iterators are known as generators. It is a normal function except
that it yields expression in the function.

20) What is docstring in Python?


A Python documentation string is known as docstring, it is a way of documenting Python
functions, modules and classes.

21) How can you copy an object in Python?


To copy an object in Python, you can try copy.copy () or copy.deepcopy() for the general
case. You cannot copy all objects but most of them.

22) What is negative index in Python?


Python sequences can be index in positive and negative numbers. For positive index, 0 is
the first index, 1 is the second index and so forth. For negative index, (-1) is the last index
and (-2) is the second last index and so forth.

23) How you can convert a number to a string?


In order to convert a number into a string, use the inbuilt function str(). If you want a octal

9
or hexadecimal representation, use the inbuilt function oct() or hex().
24) What is the difference between Xrange and range?
Xrange returns the xrange object while range returns the list, and uses the same memory
and no matter what the range size is.

25) What is module and package in Python?


In Python, module is the way to structure program. Each Python program file is a module,
which imports other modules like objects and attributes.
The folder of Python program is a package of modules. A package can have modules or
subfolders.

26) Mention what are the rules for local and global variables in Python?
Local variables: If a variable is assigned a new value anywhere within the function's body,
it's assumed to be local.
Global variables: Those variables that are only referenced inside a function are implicitly
global.

27) How can you share global variables across modules?


To share global variables across modules within a single program, create a special module.
Import the config module in all modules of your application. The module will be available
as a global variable across modules.

28) Explain how can you make a Python Script executable on Unix?
To make a Python Script executable on Unix, you need to do two things,
 Script file's mode must be executable and

 the first line must begin with # ( #!/usr/local/bin/python)

29) Explain how to delete a file in Python?

By using a command os.remove (filename) or os.unlink(filename)

30) Explain how can you generate random numbers in Python?


To generate random numbers in Python, you need to
import command as import random
random.random()
This returns a random floating point number in the range [0,1)

10
EXPERIMENT 2
CONTROL FLOW

a) Write a Program for checking whether the given number is a prime number or not.

AIM:
Write a Program for checking whether the given number is a prime number or not.

EXPLANATION:

What is a Prime Number?

A prime number is a number greater than 1 that has no positive divisors other than 1 and
itself. In other words, it cannot be divided evenly by any other number except for 1 and itself.

For example:

 2, 3, 5, 7, and 11 are prime numbers.


 4, 6, 8, and 9 are not prime numbers because they can be divided evenly by numbers other
than 1 and themselves.

PROCEDURE:

# Function to check if a number is prime


def is_prime(n):
# Check if n is less than or equal to 1
if n <= 1:
return False # Numbers less than or equal to 1 are not prime
# Check for factors from 2 to sqrt(n)
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0: # If n is divisible by i, it's not a prime
return False
return True # If no divisors were found, it's prime
# Get input from the user
number = 5
# Check if the number is prime and print the result
if is_prime(number):
print(f"{number} is a prime number.")
else:
print(f"{number} is not a prime number.")

OUTPUT:
5 is a prime number

11
EXPLANATION OF THE CODE

1. is_prime(n) function:

 The function first checks if n is less than or equal to 1. If so, the function returns False
because numbers less than or equal to 1 are not prime.
 It then loops through numbers from 2 to the square root of n (using int(n ** 0.5) + 1),
checking if any number divides n evenly (i.e., n % i == 0). If it finds such a number, it
returns False because n is not prime.
 If no such divisor is found, the function returns True, indicating that n is prime.

2. Input: The program asks the user to input a number using input().
3. Result: The program then calls the is_prime() function to check if the number is prime and
prints the result.

12
b) Write a program to print Fibonacci series upto given n value.

AIM:

Write a program to print Fibonacci series

EXPLANATION:

The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding
ones, starting from 0 and 1. The sequence looks like this:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

EXPLANATION OF THE CODE

1. fibonacci(n) function:
 This function generates the Fibonacci series up to n terms.
 We initialize two variables a and b to 0 and 1, which are the first two numbers in the
Fibonacci sequence.
 We then use a for loop to iterate n times. In each iteration, we print the current value of a
and update a and b to the next two numbers in the series.
2. Input: The user is asked to input the number n, which determines how many terms of the
Fibonacci series will be printed.
3. Output: The program prints the Fibonacci sequence up to the specified number of terms.

PROCEDURE:

# Function to print Fibonacci series up to n terms


def fibonacci(n):
# Starting values for the Fibonacci series
a, b = 0, 1
# Print the Fibonacci series up to n terms
print("Fibonacci series up to", n, "terms:")

for _ in range(n):
print(a, end=" ") # Print the current number in the series
a, b = b, a + b # Update a and b to the next two numbers in
the series

# Hardcoding the input for testing (e.g., 5 terms)


n = 5 # Change this value to test different numbers

# Call the function to print Fibonacci series


fibonacci(n)

OUTPUT:
Fibonacci series up to 5 terms:
01123
13
c) Write a program to calculate factorial of given integer number.

AIM:

Write a program to calculate factorial of given integer number.

EXPLANATION:

The factorial of a number is the product of all positive integers from 1 to that number. It is
denoted as n!. For example:

 5! = 5 * 4 * 3 * 2 * 1 = 120
 3! = 3 * 2 * 1 = 6
The factorial of 0 is 1 by definition: 0! = 1.

PROCEDURE:
# Function to calculate factorial
def factorial(n):
# Check for non-negative integers
if n < 0:
return "Factorial is not defined for negative numbers"
# Initialize result
result = 1
# Calculate factorial using a loop
for i in range(1, n + 1):
result *= i
return result

# Get input from the user


n = 15

# Call the factorial function and print the result


print(f"The factorial of {n} is: {factorial(n)}")

OUTPUT:

The factorial of 15 is: 1307674368000

14
EXPLANATION OF THE CODE

1. factorial(n) function:

 The function first checks if the number n is negative, and if it is, it returns a message
saying that the factorial is not defined for negative numbers.
 Otherwise, it initializes the result to 1.
 It then calculates the factorial by multiplying all numbers from 1 to n using a for loop.
 Finally, it returns the result of the factorial.

2. Input: The program prompts the user to input a number using input(). It converts the input to
an integer using int().
3. Result: The program calls the factorial() function with the input number and prints the result.

15
VIVA QUESTIONS:
1. Which of these in not a core data type?
a) Lists
b) Dictionary
c) Tuples
d) Class
Answer: d

2. Given a function that does not return any value, What value is thrown by default when
executed in shell.
a) int
b) bool
c) void
d) None
Answer: d

3. Following set of commands are executed in shell, what will be the output?
1. >>>str="hello"
2. >>>str[:2]
3. >>>
a) he
b) lo
c) olleh
d) hello
Answer: a

4. Which of the following will run without errors ?


a) round(45.8)
b) round(6352.898,2,5)
c) round()
d) round(7463.123,2,1)
Answer: a
Explanation: Execute help(round) in the shell to get details of the parameters that are passed

16
into the round function.
5. What is the return type of function id?
a) int
b) float
c) bool
d) dict
Answer: a
Explanation: Execute help(id) to find out details in python shell.id returns a integer value that
is unique.

6. In python we do not specify types,it is directly interpreted by the compiler, so


consider the following operation to be performed.
1. >>>x =13?2
objective is to make sure x has a integer value, select all that apply (python 3.xx)
a) x = 13 // 2
b) x = int(13 / 2)
c) x = 13 % 2
d) All of the mentioned
Answer: d
Explanation: // is integer operation in python 3.0 and int(..) is a type cast operator.

7. What error occurs when you execute? apple = mango


a) SyntaxError
b) NameError
c) ValueError
d) TypeError
Answer: b
Explanation: Mango is not defined hence name error.

8. Carefully observe the code and give the answer.


1. def example(a):

2. a = a +'2'

3. a = a*2

4. return a

17
5. >>>example("hello")

a) indentation Error
b) cannot perform mathematical operation on strings
c) hello2
d) hello2hello2
Answer: a
Explanation: Python codes have to be indented properly.

9. What data type is the object below ? L = [1, 23, ‘hello’, 1].
a) list
b) dictionary
c) array
d) tuple
Answer: a
Explanation: List data type can store any values within it.

10. In order to store values in terms of key and value we use what core data type.
a) list
b) tuple
c) class
d) dictionary
Answer: d
Explanation: Dictionary stores values in terms of keys and values.

11. Which of the following results in a SyntaxError ?


a) ‘”Once upon a time…”, she said.’
b) “He said, ‘Yes!'”
c) ‘3\’
d) ”’That’s okay”’
Answer: c
Explanation: Carefully look at the colons. Advertisement

12. Select all of the function calls that result in this output
a) print(”’tom\ndick\nharry”’)
18
b) print(”’tomdickharry”’)
c) print(‘tom\ndick\nharry’)
d) print(‘tom dick harry’)
Answer: c
Explanation: The \n adds a new line.

13. What is the average value of the code that is executed below ?

1. >>>grade1 =80
2. >>>grade2 =90
3. >>>average =(grade1 + grade2)/2

a) 85.0
b) 85.1
c) 95.0
d) 95.1
Answer: a
Explanation: Cause a decimal value of 0 to appear as output.

14. Select all options that print hello-how-are-you


a) print(‘hello’, ‘how’, ‘are’, ‘you’)
b) print(‘hello’, ‘how’, ‘are’, ‘you’ + ‘-‘ * 4)
c) print(‘hello-‘ + ‘how-are-you’)
d) print(‘hello’ + ‘-‘ + ‘how’ + ‘-‘ + ‘are’ + ‘you’)
Answer: c
Explanation: Execute in the shell.

15. What is the return value of trunc() ?


a) int
b) bool
c) float
d) None
Answer: a
Explanation: Execute help(math.trunc) to get details.

19
16. What is the output of print 0.1 + 0.2 == 0.3?
a) True
b) False
c) Machine dependent
d) Error
Answer: b
Explanation: Neither of 0.1, 0.2 and 0.3 can be represented accurately in binary. The round
off errors from 0.1 and 0.2 accumulate and hence there is a difference of 5.5511e-17 between
(0.1 + 0.2) and 0.3.

17. Which of the following is not a complex number?


a) k = 2 + 3j
b) k = complex(2, 3)
c) k = 2 + 3l
d) k = 2 + 3J
Answer: c

18. What is the type of inf?


a) Boolean
b) Integer
c) Float
d) Complex
Answer: c
Explanation: Infinity is a special case of floating point numbers. It can be obtained by
float(‘inf’).

19. What does ~4 evaluate to?


a) -5
b) -4
c) -3
d) +3
Answer: a
Explanation: ~x is equivalent to -(x+1).
20
20. What does ~~~~~~5 evaluate to?
a) +5
b) -11
c) +11
d) -5
Answer: a
Explanation: ~x is equivalent to -(x+1).

21. Which of the following is incorrect?


a) x = 0b101
b) x = 0x4f5
c) x = 19023
d) x = 03964
Answer: d
Explanation: Numbers starting with a 0 are octal numbers but 9 isn’t allowed in octal numbers.

22. What is the result of cmp(3, 1)?


a) 1
b) 0
c) True
d) False
Answer: a
Explanation: cmp(x, y) returns 1 if x > y, 0 if x == y and -1 if x < y.

23. Which of the following is incorrect?


a) float(‘inf’)
b) float(‘nan’)
c) float(’56’+’78’)
d) float(’12+34′)
Answer: d
Explanation: ‘+’ cannot be converted to a float.

21
24. What is the result of round(0.5) – round(-0.5)?
a) 1.0
b) 2.0
c) 0.0
d) None of the mentioned
Answer: b
Explanation: Python rounds off numbers away from 0 when the number to be rounded off
is exactly halfway through. round(0.5) is 1 and round(-0.5) is -1.

25. What does 3 ^ 4 evaluate to?


a) 81
b) 12
c) 0.75
d) 7
Answer: d
Explanation: ^ is the Binary XOR operator.

26) Explain how can you access a module written in Python from C? You can access a
module written in Python from C by following method,
Module = =PyImport_ImportModule("<modulename>");

27) Mention the use of // operator in Python?


It is a Floor Divisionoperator , which is used for dividing two operands with the result
as quotient showing only digits before the decimal point. For instance, 10//5 = 2 and
10.0//5.0 = 2.0.

28) Mention five benefits of using Python?


 Python comprises of a huge standard library for most Internet platforms like Email, HTML,
etc.
 Python does not require explicit memory management as the interpreter itself
allocates the memory to new variables and free them automatically
 Provide easy readability due to use of square brackets
 Easy-to-learn for beginners
 Having the built-in data types saves programming time and effort from declaring variables

22
29) Mention the use of the split functionin Python?
The use of the split function in Python is that it breaks a string into shorter strings using
the defined separator. It gives a list of all words present in the string.

30) Explain what is Flask & its benefits?


Flask is a web micro framework for Python based on "Werkzeug, Jinja 2 and good intentions"
BSD licensed. Werkzeug and jingja are two of its dependencies. Flask is part of the micro-
framework. Which means it will have little to no dependencies on external libraries. It makes
the framework light while there is little dependency to update and less security bugs.

23
EXPERIMENT 3
CONTROL FLOW - CONTINUED

a) Write a program to calculate value of the following series 1+x-x2+x3-x4+xn

AIM:
Write a program to calculate value of the following series 1+x-x2+x3-x4+xn

PROCEDURE:

def calculate_series(x, n):


result = 1 # Start with the first term which is 1
for i in range(1, n + 1):
if i % 2 == 0:
result -= x ** i # Subtract if the power is even
else:
result += x ** i # Add if the power is odd
return result

# Input values for x and n


x = float(3)
n = int(3)

# Calculate the series


series_value = calculate_series(x, n)

# Output the result


print(f"The value of the series is: {series_value}")

OUTPUT:

The value of the series is: 22.0

EXPLANATION:
 The series starts with 1, so we initialize result with 1.
 We then loop from 1 to n (inclusive).
 If the current power i is even, we subtract xixi from the result.
 If the current power i is odd, we add xixi to the result.

 Finally, the program returns the computed value of the series.

EXAMPLE:

If you input x = 2 and n = 4, the series would be:

1+2−22+23−24=1+2−4+8−16=−91+2−22+23−24=1+2−4+8−16=−9

24
b) Write a program to print Pascal triangle.

AIM:

Write a program to print Pascal triangle.

PROCEDURE:

def print_pascals_triangle(n):
# Create a 2D list to hold the values of the triangle
triangle = []

for i in range(n):
# Start with a list containing one element
row = [1] * (i + 1)

# Fill in the values of the row


for j in range(1, i):
row[j] = triangle[i - 1][j - 1] + triangle[i - 1][j]

# Append the row to the triangle


triangle.append(row)

# Print the triangle


for row in triangle:
print(" ".join(map(str, row)).center(n * 2))

# Input: number of rows for Pascal's Triangle


n = int(4)

print_pascals_triangle(n)

OUTPUT:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

PROCEDURE:

def print_pascals_triangle(n):
# Create a 2D list to hold the values of the triangle
triangle = []

for i in range(n):
# Start with a list containing one element
row = [1] * (i + 1)

# Fill in the values of the row


for j in range(1, i):
row[j] = triangle[i - 1][j - 1] + triangle[i - 1][j]

25
# Append the row to the triangle
triangle.append(row)

# Print the triangle


for row in triangle:
print(*row) # This prints the elements of the row separated by
spaces

# Input: number of rows for Pascal's Triangle


n = int(4)

print_pascals_triangle(n)

OUTPUT:

1
11
121
1331
14641

EXPLANATION:
Pascal's Triangle is a triangular array of numbers named after the French mathematician Blaise
Pascal. It has many interesting properties and applications in mathematics, particularly in
combinatorics, algebra, and probability.

STRUCTURE OF PASCAL'S TRIANGLE:


 Each number in the triangle is the sum of the two numbers directly above it (except for the
edges, which are always 1).
 The triangle starts with a single 1 at the top (row 0).
 Each subsequent row has one more number than the previous row.

Row 0: 1
Row 1: 1 1
Row 2: 1 2 1
Row 3: 1 3 3 1
Row 4: 1 4 6 4 1

26
VIVA QUESTIONS:

1. What is the maximum possible length of an identifier?


a) 31 characters
b) 63 characters
c) 79 characters
d) none of the mentioned
Answer: d
Explanation: Identifiers can be of any length.

2. Which of the following is invalid?


a) _a = 1
b) a = 1
c) str =1
d) none of the mentioned
Answer: d
Explanation: All the statements will execute successfully but at the cost of reduced readability.

3. Which of the following is an invalid variable?


a) my_string_1
b) 1st_string
c) foo
d) _
Answer: b
Explanation: Variable names should not start with a number.

4. Why are local variable names beginning with an underscore discouraged?


a) they are used to indicate a private variables of a class
b) they confuse the interpreter
c) they are used to indicate global variables
d) they slow down execution
Answer: a
Explanation: As Python has no concept of private variables, leading underscores are used
to indicate variables that must not be accessed from outside the class.

5. Which of the following is not a keyword?


a) eval
27
b) assert
c) nonlocal
d) pass
Answer: a
Explanation: eval can be used as a variable.

6. All keywords in Python are in


a) lower case
b) UPPER CASE
c) Capitalized
d) None of the mentioned
Answer: d
Explanation: True, False and None are capitalized while the others are in lower case.

7. Which of the following is true for variable names in Python?


a) unlimited length
b) all private members must have leading and trailing underscores
c) underscore and ampersand are the only two special characters allowed
d) none of the mentioned
Answer: a
Explanation: Variable names can be of any length.

8. Which of the following is an invalid statement?


a) abc = 1,000,000
b) a b c = 1000 2000 3000
c) a,b,c = 1000, 2000, 3000
d) a_b_c = 1,000,000
Answer: b
Explanation: Spaces are not allowed in variable names.

9. Which of the following cannot be a variable?


a) init
b) in
c) it
d) on
Answer: b
28
Explanation: in is a keyword.

10. Is Python case sensitive when dealing with identifiers?


a) yes
b) no
c) machine dependent
d) none of the mentioned
Answer: a
Explanation: Case is always significant.

11. The value of the expressions 4/(3*(2-1)) and 4/3*(2-1) is the same. State whether true or
false.
a) True
b) False
Answer: a
Explanation: Although the presence of parenthesis does affect the order of precedence, in the
case shown above, it is not making a difference. The result of both of these expressions is
1.333333333. Hence the statement is true.

12. The value of the expression:

4+3%5
Explanation: The order of precedence is: %, +. Hence the expression above, on simplification
results in 4 + 3 = Hence the result is 7.

13. Evaluate the expression given below if A= 16 and B = 15.


A % B // A
Answer: b
Explanation: The above expression is evaluated as: 16%15//16, which is equal to 1//16, which
results in 0.

14. Which of the following operators has its associativity from right to left?
a) +
b) //
c) %
d) **
Answer: d
Explanation: All of the operators shown above have associativity from left to right, except

29
exponentiation operator (**) which has its associativity from right to left.

15. What is the value of x if:


x = int(43.55+2/2)
Explanation: The expression shown above is an example of explicit conversion. It is evaluated
as int(43.55+1) = int(44.55) = 44. Hence the result of this expression is 44.

16. What is the value of the following expression?


2+4.00, 2**4.0
Explanation: The result of the expression shown above is (6.0, 16.0). This is because the
result is automatically rounded off to one decimal place.

17. Which of the following is the truncation division operator?


a) /
b) %
c) //
d) |
Answer: c
Explanation: // is the operator for truncation division. It it called so because it returns only the
integer part of the quotient, truncating the decimal part. For example: 20//3 = 6.

18. What are the values of the following expressions:


2**(3**2)
(2**3)**2
2**3**2
Answer: d
Explanation: Expression 1 is evaluated as: 2**9, which is equal to 512.Expression 2 is
evaluated as 8**2, which is equal to 64. The last expression is evaluated as 2**(3**2). This
is because the associativity of ** operator is from right to left. Hence the result of the third
expression is 512.
Advertisement

19. What is the value of the following expression:


8/4/2, 8/(4/2)
Answer: a
Explanation: The above expressions are evaluated as: 2/2, 8/2, which is equal to (1.0, 4.0).
30
20. What is the value of the following expression:
float(22//3+3/3)
Answer: b
Explanation: The expression shown above is evaluated as: float( 7+1) = float(8) = 8.0. Hence
the result of this expression is 8.0.

21. What is the result of the snippet of code shown below if x=1?
x<<2
Explanation: The binary form of 1 is 0001. The expression x<<2 implies we are performing
bitwise left shift on
x. This shift yields the value: 0100, which is the binary form of the number 4.

22. The output of the expression is:


bin(29)
a) ‘0b10111’
b) ‘0b11101’
c) ‘0b11111’
d) ‘0b11011’
Answer: b
Explanation: The binary form of the number 29 is 11101. Hence the output of this expression
is ‘0b11101’.

23. What is the value of x if:


x>>2=2
Explanation: When the value of x is equal to 8 (1000), then x>>2 (bitwise right shift) yields
the value 0010, which is equal to 2. Hence the value of x is 8.

24. What is the result of the expression:


int(1011)?
Explanation: The result of the expression shown will be 1011. This is because we have not
specified the base in this expression. Hence it automatical

25. To find the decimal value of 1111, that is 15, we can use the function:

31
Explanation: The expression int(‘1111’,2) gives the result 15. The expression int(‘1111’, 10)
will give the result 1111.

26. What is the result of the expression if x=15 and y=12:


x&y
Explanation: The symbol ‘&’ represents bitwise AND. This gives 1 if both the bits are equal
to 1, else it gives 0. The binary form of 15 is 1111 and that of 12 is 1100. Hence on
performing the bitwise AND operation, we get 1100, which is equal to 12.

27. Which of the following expressions results in an error?


a) int(1011)
b) int(‘1011’,23)
c) int(1011,2)
d) int(‘1011’)
Answer: c
Explanation: The expression int(1011,2) results in an error. Had we written this expression as
int(‘1011’,2), then there would not be an error.
Advertisement

28. Which of the following represents the bitwise XOR operator?

a) &

b) ^
c) |

d) !
Answer: b
Explanation: The ^ operator represent bitwise XOR operation. &: bitwise AND, | : bitwise
OR and ! represents bitwise NOT.

29. What is the value of this expression?


bin(0x8)
Explanation: The prefix 0x specifies that the value is hexadecimal in nature. When we convert
this hexadecimal value to binary form, we get the result as: ‘0b1000’.

30. What is the result of the expression:


0x35 | 0x75
Explanation: The binary value of 0x35 is 110101 and that of 0x75 is 1110101. On OR-ing
these two values we get the output as: 1110101, which is equal to 117. Hence the result of
the above expression is 117.
32
EXPERIMENT 4
PYTHON SEQUENCES

a) Write a program to sort the numbers in ascending order and strings in reverse
alphabetical order.

AIM:

Write a program to sort the numbers in ascending order and strings in reverse
alphabetical order.

PROCEDURE:

def sort_numbers_and_strings(input_list):
# Separate numbers and strings
numbers = []
strings = []

for item in input_list:


if isinstance(item, (int, float)):
numbers.append(item)
elif isinstance(item, str):
strings.append(item)

# Sort numbers in ascending order


numbers.sort()

# Sort strings in reverse alphabetical order


strings.sort(reverse=True)

# Combine the sorted numbers and strings


return numbers + strings

# Input list
input_list = [12, 'apple', 3, 'banana', 7, 'orange', 10, 'grape']

# Sort and print the result


sorted_list = sort_numbers_and_strings(input_list)
print("Sorted list:", sorted_list)

OUTPUT:

Sorted list: [3, 7, 10, 12, 'orange', 'grape', 'banana', 'apple']

EXPLANATION:

1. Separation of numbers and strings:

 The input_list contains both numbers and strings.

33
 We separate them into two different lists: numbers and strings.

 For numbers, we check if the item is an instance of int or float using isinstance(x, (int,
float)).
 For strings, we check if the item is an instance of str.

2. Sorting:

 The sorted(numbers) function sorts the list of numbers in ascending order.


 The sorted(strings, reverse=True) function sorts the list of strings in reverse alphabetical
order.
3. Combining the sorted lists:
 The program then combines the two sorted lists (sorted_numbers and sorted_strings) into one
list and returns it.

34
b) Given an integer value, return a string with the equivalent English text of each digit. For
example, an input of 89 results in "eight-nine" being returned. Write a program to
implement it.

AIM:
Given an integer value, return a string with the equivalent English text of each digit. For
example, an input of 89 results in "eight-nine" being returned. Write a program to implement
it.
PROCEDURE:
def number_to_words(num):
# Dictionary to map digits to their English words
digit_to_word = {
0: "zero",
1: "one",
2: "two",
3: "three",
4: "four",
5: "five",
6: "six",
7: "seven",
8: "eight",
9: "nine"
}

# Convert the number to a string to iterate through each digit


num_str = str(num)

# List to store the English words for each digit


words = []

# Iterate through each digit and get its corresponding word


for digit in num_str:
words.append(digit_to_word[int(digit)])

# Join the words with a hyphen and return the result


return "-".join(words)

# Input: integer value


num = int(input("Enter an integer: "))

# Convert the number to English text


result = number_to_words(num)

# Output the result


print(result)
OUTPUT:
Enter an integer: 89
eight-nine
35
VIVA QUESTIONS

1. What is Python?
Python is a high-level, interpreted, interactive and object-oriented scripting language.
Python is designed to be highly readable. It uses English keywords frequently where as
other languages use punctuation, and it has fewer syntactical constructions than other
languages.

2. What is the purpose of PYTHONPATH environment variable?

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.

3. What is the purpose of PYTHONSTARTUP environment variable?


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.

4. What is the purpose of PYTHONCASEOK environment variable?


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.

5. What is the purpose of PYTHONHOME environment variable?


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

6. Is python a case sensitive language?


Yes! Python is a case sensitive programming language.

7. What are the supported data types in Python?


Python has five standard data types
−Numbers String List Tuple
Dictionary
36
8. What is the output of print str if str = 'Hello World!'?
It will print complete string. Output would be Hello World!.

9. What is the output of print str[0] if str = 'Hello World!'?


It will print first character of the string. Output would be H.

10. What is the output of print str[2:5] if str = 'Hello World!'?


It will print characters starting from 3rd to 5th. Output would be llo.

11. What is the output of print str[2:] if str = 'Hello World!'?


It will print characters starting from 3rd character. Output would be lloWorld!.

12. What is the output of print str * 2 if str = 'Hello World!'?


It will print string two times. Output would be Hello World!Hello World!.

13. What is the output of print str + "TEST" if str = 'Hello World!'?
It will print concatenated string. Output would be Hello World!TEST.

14. What is the output of print list if list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]?
It will print complete list. Output would be ['abcd', 786, 2.23, 'john', 70.200000000000003].

15. What is the output of print list[0] if list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]?
It will print first element of the list. Output would be abcd.

16. What is the output of print list[1:3] if list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]?
It will print elements starting from 2nd till 3rd. Output would be [786, 2.23].

17. What is the output of print list[2:] if list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]?

It will print elements starting from 3rd element. Output would be [2.23, 'john',
70.200000000000003].

18. What is the output of print tinylist * 2 if tinylist = [123, 'john']?


It will print list two times. Output would be [123, 'john', 123, 'john'].

37
19. What is the output of print list1 + list2, if list1 = [ 'abcd', 786 , 2.23, 'john', 70.2 ] and ist2
= [123, 'john']?
It will print concatenated lists. Output would be ['abcd', 786, 2.23, 'john', 70.2, 123, 'john']

20. What are tuples in Python?


A tuple is another sequence data type that is similar to the list. A tuple consists of a number of
values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.

21. What is the difference between tuples and lists in Python?


The main differences between lists and tuples are − Lists are enclosed in brackets ( [ ] ) and
their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and
cannot be updated. Tuples can be thought of as read-only lists.

22. What is the output of print tuple if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )?
It will print complete tuple. Output would be ('abcd', 786, 2.23, 'john', 70.200000000000003).

23. What is the output of print tuple[0] if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )?
It will print first element of the tuple. Output would be abcd.

24. What is the output of print tuple[1:3] if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )?
It will print elements starting from 2nd till 3rd. Output would be (786, 2.23).

25. What is the output of print tuple[2:] if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )?
It will print elements starting from 3rd element. Output would be (2.23, 'john',
70.200000000000003).

26. What is the output of print tinytuple * 2 if tinytuple = (123, 'john')?


It will print tuple two times. Output would be (123, 'john', 123, 'john').

27. What is the output of print tuple + tinytuple if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
and tinytuple = (123, 'john')?
It will print concatenated tuples. Output would be ('abcd',
786, 2.23, 'john', 70.200000000000003, 123, 'john').

38
28. What are Python's dictionaries?
Python's dictionaries are kind of hash table type. They work like associative arrays or hashes
found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type,
but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.

29. How will you get all the keys from the dictionary?
Using dictionary.keys() function, we can get all the keys from the dictionary object.
printdict.keys()# Prints all the keys

30. How will you get all the values from the dictionary?
Using dictionary.values() function, we can get all the values from the dictionary object.
printdict.values()# Prints all the values

39
EXPERIMENT 5
PYTHON SEQUENCES

a) Write a program to create a function that will return another string similar to the input
string, but with its case inverted. For example, input of "Mr. Ed" will result in "mR.eD"
as the output string.
AIM:
Write a program to create a function that will return another string similar to the input string,
but with its case inverted. For example, input of "Mr. Ed" will result in "mR.eD" as the output
string.
PROCEDURE:
def invert_case(input_string):
# Use the swapcase() method to invert the case
return input_string.swapcase()

# Example usage
input_str = "Mr. Ed"
output_str = invert_case(input_str)
print("Input String:", input_str)
print("Output String:", output_str)

OUTPUT:
Input String: Mr. Ed
Output String: mR. eD

EXPLANATION:
1. The swapcase() method is a built-in Python function that automatically inverts the case of each
character in a string:
 Lowercase letters become uppercase.
 Uppercase letters become lowercase.
 Non-alphabetic characters (like ., ) remain unchanged.

2. The function invert_case takes a string as input, applies swapcase(), and returns the result.

40
b) Write a program to take a string and append a backward copy of that string, making
a palindrome.

AIM:
Write a program to take a string and append a backward copy of that string, making a
palindrome.
PROCEDURE:
def make_palindrome(input_string):
# Append the reverse of the string to itself
palindrome = input_string + input_string[::-1]
return palindrome

# Example usage
input_str = "This is Python Lab " # Take input from the user
output_str = make_palindrome(input_str)
print("Palindrome:", output_str)

OUTPUT:
Palindrome: This is Python Lab baL nohtyP si sihT

EXPLANATION:
1. The slicing operation [::-1] reverses the string.
2. The reversed string is appended to the original string using the + operator.
3. The result is a palindrome.

41
VIVA QUESTIONS

1. How will you convert a string to an int in python?


int(x [,base]) - Converts x to an integer. base specifies the base if x is a string.

2. How will you convert a string to a long in python?

long(x [,base] ) - Converts x to a long integer. base specifies the base if x is a string.

3. How will you convert a string to a float in python?


float(x) − Converts x to a floating-point number.

4. How will you convert a object to a string in python?


str(x) − Converts object x to a string representation.

5. How will you convert a object to a regular expression in


python? repr(x) − Converts object x to an expression string.

6. How will you convert a String to an object in python?


eval(str) − Evaluates a string and returns an object.

7. How will you convert a string to a tuple in


python? tuple(s) − Converts s to a tuple.

8. How will you convert a string to a list in python?


list(s) − Converts s to a list.

9. How will you convert a string to a set in


python? set(s) − Converts s to a set.

10. How will you create a dictionary using tuples in python?


dict(d) − Creates a dictionary. d must be a sequence of (key,value) tuples.

11. How will you convert a string to a frozen set in


python? frozenset(s) − Converts s to a frozen set.

42
12. How will you convert an integer to a character in python?
chr(x) − Converts an integer to a character.

13. How will you convert an integer to an unicode character in


python? unichr(x) − Converts an integer to a Unicode
character.

14. How will you convert a single character to its integer value in python?
ord(x) − Converts a single character to its integer value.

15. How will you convert an integer to hexadecimal string in


python? hex(x) − Converts an integer to a hexadecimal
string.

16. How will you convert an integer to octal string in python?


oct(x) − Converts an integer to an octal string.

17. What is the purpose of ** operator?


** Exponent − Performs exponential (power) calculation on operators. a**b = 10 to
the power 20 if a = 10 and b = 20.

18. What is the purpose of // operator?


// Floor Division − The division of operands where the result is the quotient in which
the digits after the decimal point are removed.

19. What is the purpose of is operator?


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

20. What is the purpose of not in operator?


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

21. What is the purpose break statement in python?


break statement − Terminates the loop statement and transfers execution to the statement
43
immediately following the loop.

22. What is the purpose continue statement in python?


continue statement − Causes the loop to skip the remainder of its body and immediately
retest its condition prior to reiterating.

23. What is the purpose pass statement in python?


pass statement − The pass statement in Python is used when a statement is required
syntactically but you do not want any command or code to execute.

24. How can you pick a random item from a list or tuple?
choice(seq) − Returns a random item from a list, tuple, or string.

25. How can you pick a random item from a range?


randrange ([start,] stop [,step]) − returns a randomly selected element from range(start,
stop, step).

26. How can you get a random number in python?


random() − returns a random float r, such that 0 is less than or equal to r and r is less than 1.

27. How will you set the starting value in generating random numbers?
seed([x]) − Sets the integer starting value used in generating random numbers. Call this
function before calling any other random module function. Returns None.

28. How will you randomizes the items of a list in place?


shuffle(lst) − Randomizes the items of a list in place. Returns None.

29. How will you capitalizes first letter of string?


capitalize() − Capitalizes first letter of string.

30. How will you check in a string that all characters are alphanumeric?
isalnum() − Returns true if string has at least 1 character and all characters are
alphanumeric and false otherwise.

44
EXPERIMENT 6
PYTHON DICTIONARIES

a) Write a program to create a dictionary and display its keys alphabetically.

AIM:
Write a program to create a dictionary and display its keys alphabetically.

PROCEDURE:

# Create a dictionary
my_dict = {
'banana': 3,
'apple': 5,
'orange': 2,
'grape': 7,
'pear': 1
}

# Display the keys alphabetically


sorted_keys = sorted(my_dict.keys())

print("Keys in alphabetical order:")


for key in sorted_keys:
print(key)

OUTPUT:
Keys in alphabetical order:
apple
banana
grape
orange
pear

EXPLANATION:
1. Creating the Dictionary: We create a dictionary my_dict with some key-value pairs.
2. Sorting the Keys: We use the sorted() function to sort the keys of the dictionary
alphabetically. The sorted() function returns a list of sorted keys.
3. Displaying the Keys: We then iterate over the sorted list of keys and print each key.

45
b) Write a program to take a dictionary as input and return one as output, but the values
are now the keys and vice versa.
AIM:
Write a program to take a dictionary as input and return one as output, but the values are
now the keys and vice versa.
PROCEDURE:
# Take input dictionary from the user
input_dict = {}
n = int(input("Enter the number of key-value pairs: "))

for i in range(n):
key = input(f"Enter key {i+1}: ")
value = input(f"Enter value {i+1}: ")
input_dict[key] = value

# Create a new dictionary to store swapped keys and values


swapped_dict = {}

# Swap keys and values


for key, value in input_dict.items():
swapped_dict[value] = key

# Display the original and swapped dictionaries


print("\nOriginal Dictionary:")
print(input_dict)

print("\nSwapped Dictionary:")
print(swapped_dict)

OUTPUT:
Enter the number of key-value pairs: 3
Enter key 1: a
Enter value 1: 1
Enter key 2: b
Enter value 2: 2
Enter key 3: c
Enter value 3: 3

Original Dictionary:
{'a': '1', 'b': '2', 'c': '3'}

Swapped Dictionary:
{'1': 'a', '2': 'b', '3': 'c'}
EXPLANATION:
1. Input Dictionary: The program asks the user to enter the number of key-value pairs and then
takes input for each key and value.

46
2. Swapping Keys and Values: A new dictionary swapped_dict is created. Using a for loop, the
program iterates through the original dictionary and swaps the keys and values, storing them
in the new dictionary.
3. Output: The program prints both the original dictionary and the swapped dictionary.

47
VIVA QUESTIONS

1. How will you check in a string that all characters are digits?
isdigit() − Returns true if string contains only digits and false otherwise.

2. How will you check in a string that all characters are in lowercase?

islower() − Returns true if string has at least 1 cased character and all cased characters are in
lowercase and false otherwise.

3. How will you check in a string that all characters are numerics?
isnumeric() − Returns true if a unicode string contains only numeric characters and false
otherwise.

4. How will you check in a string that all characters are whitespaces?
isspace() − Returns true if string contains only whitespace characters and false otherwise.

5. How will you check in a string that it is properly titlecased?


istitle() − Returns true if string is properly "titlecased" and false otherwise.

6. How will you check in a string that all characters are in uppercase?
isupper() − Returns true if string has at least one cased character and all cased characters
are in uppercase and false otherwise.

7. How will you merge elements in a sequence?


join(seq) − Merges (concatenates) the string representations of elements in sequence seq
into a string, with separator string.

8. How will you get the length of the string?


len(string) − Returns the length of the string.

9. How will you get a space-padded string with the original string left-justified to a total
of width columns?
ljust(width[, fillchar]) − Returns a space-padded string with the original string left-
justified to a total of width columns.

48
10. How will you convert a string to all lowercase?
lower() − Converts all uppercase letters in string to lowercase.

11. How will you remove all leading whitespace in string?


lstrip() − Removes all leading whitespace in string.

12. How will you get the max alphabetical character from the string?
max(str) − Returns the max alphabetical character from the string str.

13. How will you get the min alphabetical character from the string?
min(str) − Returns the min alphabetical character from the string str.

14. How will you replaces all occurrences of old substring in string with new string?
replace(old, new [, max]) − Replaces all occurrences of old in string with new or at most max
occurrences if max given.

15. How will you remove all leading and trailing whitespace in string?
strip([chars]) − Performs both lstrip() and rstrip() on string.

16. How will you change case for all letters in string?
swapcase() − Inverts case for all letters in string.

17. How will you get titlecased version of string?


title() − Returns "titlecased" version of string, that is, all words begin with uppercase and
the rest are lowercase.

18. How will you convert a string to all uppercase?


upper() − Converts all lowercase letters in string to uppercase.

19. How will you check in a string that all characters are
decimal?
isdecimal() − Returns true if a unicode string contains only decimal characters and false
otherwise.

49
20. What is the difference between del() and remove() methods of list?
To remove a list element, you can use either the del statement if you know exactly which
element(s) you are deleting or the remove() method if you do not know.

21. What is the output of len([1, 2, 3])?


3.

22. What is the output of [1, 2, 3] + [4, 5, 6]?


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

23. What is the output of


['Hi!'] * 4? ['Hi!', 'Hi!',
'Hi!', 'Hi!']

24. What is the output of 3 in [1, 2, 3]?


True

25. What is the output of for x in [1, 2, 3]: print x?


1
2
3

26. What is the output of L[2] if L =


[1,2,3]? 3, Offsets start at zero.

27. What is the output of L[-2] if L = [1,2,3]?


1, Negative: count from the right.

28. What is the output of L[1:]


if L = [1,2,3]? 2, 3, Slicing fetches sections.

29. How will you compare two lists?


cmp(list1, list2) − Compares elements of both lists.

30. How will you get the length of a list?


len(list) − Gives the total length of the list.

50
EXPERIMENT 7
FILES

a) Write a program to compare two text files. If they are different, give the line and column
numbers in the files where the first difference occurs.

AIM:
Write a program to compare two text files. If they are different, give the line and column
numbers in the files where the first difference occurs.

PROCEDURE:
# reading files
f1 = open("/content/Hello.txt","r")
f2 = open("/content/Python.txt","r")
f1_data = f1.readlines()
f2_data = f2.readlines()
i = 0
for line1 in f1_data:
i += 1
for line2 in f2_data:
# matching line1 from both files
if line1 == line2:
# print IDENTICAL if similar
print("Line ", i, ": IDENTICAL")
else:
print("Line ", i, ":")
# else print that line from both files
print("\tFile 1:", line1, end='')
print("\tFile 2:", line2, end='')
break
# closing files
f1.close()
f2.close()

OUTPUT:
Line 1 : IDENTICAL
File 1: Exercise - 7 Files
File 2: Exercise - 7 Files
Line 2 :
File 1: a) Write a program to compare two text files. If they are
different, give the line and column numbers in the files where the
first difference occurs.
File 2: Exercise - 7 Files
Line 3 :
File 1: b) Write a program to compute the number of characters,
words and lines in a file.
File 2: Exercise - 7 Files

51
EXPLANATION:
1. Open Files: The program opens both files using open().
2. Read Lines: It reads one line at a time from each file using readline().
3. Check for End of File:

 If both files end at the same time, they are identical.


 If one file ends before the other, it reports the difference.

4. Compare Characters:

 It compares each character in the lines using a for loop and zip().
 If a mismatch is found, it prints the line and column numbers and stops.

5. Check Line Length:

 If one line is longer than the other, it reports the difference at the end of the shorter line.

6. Close Files: The program closes both files after the comparison is done.

52
b) Write a program to compute the number of characters, words and lines in a file.

AIM:
Write a program to compute the number of characters, words and lines in a file.

PROCEDURE:
def count_file_stats(filename):
"""
Compute the number of characters, words, and lines in a file.

Parameters:
filename (str): The name of the file to analyze.

Returns:
tuple: A tuple containing (num_characters, num_words, num_lines).
"""
num_characters = 0
num_words = 0
num_lines = 0

try:
with open(filename, 'r') as file:
for line in file:
num_lines += 1 # Count lines
num_characters += len(line) # Count characters
(including spaces and newlines)
num_words += len(line.split()) # Count words
except FileNotFoundError:
print(f"Error: The file '{filename}' does not exist.")
return None

return num_characters, num_words, num_lines

# Input file name


filename = "/content/Hello.txt"

# Compute statistics
result = count_file_stats(filename)

if result:
num_characters, num_words, num_lines = result
print(f"Number of characters: {num_characters}")
print(f"Number of words: {num_words}")
print(f"Number of lines: {num_lines}")

OUTPUT:
Number of characters: 252
Number of words: 47
Number of lines: 3

53
EXPLANATION:

1. Open the File:


 The program opens the file using with open(filename, 'r') to ensure the file is properly
closed after reading.

2. Count Lines:

 Each iteration of the for line in file loop counts one line.

3. Count Characters:
 len(line) gives the number of characters in the current line, including spaces and newline
characters.

4. Count Words:
 line.split() splits the line into words (using whitespace as the delimiter),
and len(line.split()) gives the number of words in the line.

5. Error Handling:
 If the file does not exist, the program catches the FileNotFoundError and prints an error
message.

6. Return Results:

 The function returns a tuple (num_characters, num_words, num_lines).

54
VIVA QUESTIONS

1. How will you get the max valued item of a list?


max(list) − Returns item from the list with max value.

2. How will you get the min valued item of a list?

min(list) − Returns item from the list with min value.

3. How will you get the index of an object in a list?


list.index(obj) − Returns the lowest index in list that obj appears.

4. How will you insert an object at given index in a list?


list.insert(index, obj) − Inserts object obj into list at offset index.

5. How will you remove last object from a list?


list.pop(obj=list[-1]) − Removes and returns last object or obj from list.

6. How will you remove an object from a list?


list.remove(obj) − Removes object obj from list.

7. How will you reverse a list?


list.reverse() − Reverses objects of list in place.

8. How will you sort a list?


list.sort([func]) − Sorts objects of list, use compare func if given.

9. Is Python platform independent? No


There are some modules and functions in python that can only run on certain platforms.

10. Do you think Python has a complier?


Yes it has a complier which works automatically so we don’t notice the compiler of python.

11. Which programming Language is an implementation of Python programming language


designed to run on Java Platform?Is there any double data type in Python?

55
No
12. Is String in Python are immutable? (Yes/No)
Yes.

13. Can True = False be possible in Python?


No.

14. Which module of python is used to apply the methods related to OS.?
OS.

15. When does a new block begin in python?


A block begins when the line is intended by 4 spaces.

16. Name the python Library used for Machine learning.


Scikit-learn python Library used for Machine learning

17. What does pass operation do?


Pass indicates that nothing is to be done i.e. it signifies a no operation.

18. Name the tools which python uses to find bugs (if any).
Pylint and pychecker.

19. Does python support multiple inheritance?


Ans: Multiple inheritance means that a class can be derived from more than one parent
classes. Python does support multiple inheritance, unlike Java.

20. What is Polymorphism in Python?


Ans: Polymorphism means the ability to take multiple forms. So, for instance, if the parent
class has a method named ABC then the child class also can have a method with the same
name ABC having its own parameters and variables. Python allows polymorphism.

21. Define encapsulation in Python?


Ans: Encapsulation means binding the code and the data together. A Python class in an
example of encapsulation.

56
22. How do you do data abstraction in Python?
Ans: Data Abstraction is providing only the required details and hiding the implementation
from the world. It can be achieved in Python by using interfaces and abstract classes.

23. Does python make use of access specifiers?

Ans: Python does not deprive access to an instance variable or function. Python lays down
the concept of prefixing the name of the variable, function or method with a single or
double underscore to imitate the behavior of protected and private access specifiers.

24. What is map function in Python?


Ans: map function executes the function given as the first argument on all the elements of
the iterable given as the second argument. If the function given takes in more than 1
arguments, then many iterables are given. #Follow the link to know more similar
functions.

25. Mention what are the rules for local and global variables in Python?
Local variables: If a variable is assigned a new value anywhere within the function's
body, it's assumed to be local.
Global variables: Those variables that are only referenced inside a function are implicitly global.

26. How can you share global variables across modules?


To share global variables across modules within a single program, create a special module.
Import the config module in all modules of your application. The module will be available as
a global variable across modules.

27. Explain how can you make a Python Script executable on Unix?
To make a Python Script executable on Unix, you need to do two things,
Script file's mode must be executable and
the first line must begin with # ( #!/usr/local/bin/python)

28. Explain how to delete a file in Python?


By using a command os.remove (filename) or os.unlink(filename)

57
29. What is unittest in Python?
A unit testing framework in Python is known as unittest. It supports sharing of setups,
automation testing, shutdown code for tests, aggregation of tests into collections etc.

30. In Python what is slicing?


A mechanism to select a range of items from sequence types like list, tuple, strings etc. is known
as slicing.

58
EXPERIMENT 8
FUNCTIONS
a) Write a function ball collide that takes two balls as parameters and computes if they
are colliding. Your function should return a Boolean representing whether or not the
balls are colliding.
b) If (distance between two balls centers) <= (sum of their radii) then (they are colliding)

Hint: Represent a ball on a plane as a tuple of (x, y, r), r being the radius

AIM:
Write a function ball collide that takes two balls as parameters and computes if they are
colliding. Your function should return a Boolean representing whether or not the balls are
colliding.

PROCEDURE:
def ball_collide(ball1, ball2):
"""
Check if two balls are colliding.

Parameters:
ball1 (tuple): A tuple (x1, y1, r1) representing the first ball.
ball2 (tuple): A tuple (x2, y2, r2) representing the second ball.

Returns:
bool: True if the balls are colliding, False otherwise.
"""
# Extract coordinates and radii of the balls
x1, y1, r1 = ball1
x2, y2, r2 = ball2

# Calculate the squared distance between the centers of the two


balls
dx = x2 - x1 # Difference in x-coordinates
dy = y2 - y1 # Difference in y-coordinates
squared_distance = dx * dx + dy * dy # Squared distance (no need
for square root)

# Calculate the squared sum of the radii


sum_of_radii = r1 + r2
squared_sum_of_radii = sum_of_radii * sum_of_radii

# Check if the squared distance is less than or equal to the


squared sum of radii
if squared_distance <= squared_sum_of_radii:
return True # Collision detected
else:
59
return False # No collision

# Example usage
ball1 = (0, 0, 5) # Ball 1 at (0, 0) with radius 5
ball2 = (8, 0, 4) # Ball 2 at (8, 0) with radius 4

if ball_collide(ball1, ball2):
print("The balls are colliding!")
else:
print("The balls are not colliding.")

OUTPUT:
The balls are colliding!
EXPLANATION:
1. Input Representation:
 Each ball is represented as a tuple (x, y, r), where:
 (x, y) is the center of the ball.
 r is the radius of the ball.

2. Squared Distance Calculation:


 Instead of calculating the actual distance using math.sqrt, we calculate the squared distance:

squared_distance=(x2−x1)2+(y2−y1)2

 This avoids the need for the square root operation, making the code simpler and faster.

3. Squared Sum of Radii:


 We calculate the squared sum of the radii:

squared_sum_of_radii=(r1+r2)2squared_sum_of_radii=(r1+r2)2

4. Collision Condition:
 If the squared distance is less than or equal to the squared sum of the radii, the balls are
colliding.

5. Return Value:
 The function returns True if the balls are colliding, otherwise False.

SQUARED DISTANCE

The squared distance between two points is the sum of the squares of the differences between
their corresponding coordinates. It is commonly used in geometry, machine learning, and
optimization because it avoids computing square roots, making calculations faster.

FORMULA (EUCLIDEAN SQUARED DISTANCE)

For two points P(x₁, y₁) and Q(x₂, y₂) in 2D space:

60
D2 = (x2 – x1)2+(y2 – y1)2

For 3D space (P(x₁,

y₁, z₁) and Q(x₂, y₂, z₂)):

D2 = (x2 – x1)2 + (y2 – y1)2 + (z2 – z1)2


EXAMPLE 1:
 Squared distance: (8−0)2 + (0−0)2 = 64
 Squared sum of radii: (5+4)2 = 81
 Since 64 ≤ 81, the balls are colliding.

EXAMPLE 2:
 Squared distance: (10−0)2 + (0−0)2 = 100
 Squared sum of radii: (5+4)2 = 81
 Since 100 > 81, the balls are not colliding.

61
c) Find mean, median, mode for the given set of numbers in a list.

AIM:
Find mean, median, mode for the given set of numbers in a list.

PROCEDURE:
from statistics import mean, median, mode

# Input list of numbers


numbers = [4, 2, 8, 6, 4, 1, 8, 4]

# Calculate mean
mean_value = mean(numbers)

# Calculate median
median_value = median(numbers)

# Calculate mode
try:
mode_value = mode(numbers)
except StatisticsError:
mode_value = "No mode (all numbers appear the same number of
times)"

# Print results
print(f"Mean: {mean_value}")
print(f"Median: {median_value}")
print(f"Mode: {mode_value}")

OUTPUT:
Mean: 4.625
Median: 4.0
Mode: 4

EXAMPLE:

Given the list: [4, 2, 8, 6, 4, 1, 8, 4]

1. Mean:

Sum = 4 + 2 + 8 + 6 + 4 + 1 + 8 + 4 = 37

Number of elements = 8

37
Mean = = 4.625
8

2. Median:
 Sorted list: [1, 2, 4, 4, 4, 6, 8, 8]

 Number of elements: 8 (even)

 Middle numbers: 4 and 4

62
4+4
 Median = =4
2
 Mode:
 Frequency of numbers:
 1 appears 1 time
 2 appears 1 time
 4 appears 3 times
 6 appears 1 time
 8 appears 2 times

 The number with the highest frequency is 4.

Mode = 4

63
d) Write simple functions max2() and min2() that take two items and return the larger
and smaller item, respectively. They should work on arbitrary Python objects. For
example, max2(4, 8) and min2(4, 8) would each return 8 and 4, respectively.

AIM:
Write simple functions max2() and min2() that take two items and return the larger and
smaller item, respectively. They should work on arbitrary Python objects. For example,
max2(4, 8) and min2(4, 8) would each return 8 and 4, respectively.

PROCEDURE:
def max2(a, b):
"""Return the larger of two items."""
return a if a > b else b

def min2(a, b):


"""Return the smaller of two items."""
return a if a < b else b
print(max2(4, 8)) # Output: 8
print(min2(4, 8)) # Output: 4

print(max2("apple", "banana")) # Output: "banana"


print(min2("apple", "banana")) # Output: "apple"

OUTPUT:
8
4
banana
apple

EXPLANATION:
1. max2(a, b):
 Compares ‘a’ and ‘b’ using the > operator.
 Returns ‘a’ if ‘a’ is greater than ‘b’, otherwise returns ‘b’.

2. min2(a, b):
 Compares ‘a’ and ‘b’ using the < operator.
 Returns ‘a’ if ‘a’ is less than ‘b’, otherwise returns ‘b’ .

64
VIVA QUESTIONS:

1. What Are The Different Methods To Copy An Object In Python?


There are two ways to copy objects in Python.
 copy.copy() function

It makes a copy of the file from source to destination.


It’ll return a shallow copy of the parameter.
 copy.deepcopy() function
It also produces the copy of an object from the source to destination.
It’ll return a deep copy of the parameter that you can pass to the function.

2. What Is The Purpose Of Docstrings In Python?


In Python, the docstring is what we call as the docstrings. It sets a process of recording
Python functions, modules, and classes.

3. Which Python Function Will You Use To Convert A Number To A String?


For converting a number into a string, you can use the built-in function str(). If you want
an octal or hexadecimal representation, use the inbuilt function oct() or hex().

4. What’s The Process To Get The Home Directory Using ‘~’ In Python? You need to
import the os module, and then just a single line would do the rest.

import os

print (os.path.expanduser('~'))
OUTPUT:

/home/runner

5. What Are The Built-In Types Available In Python?


Here is the list of most commonly used built-in types that Python supports:
 Immutable built-in datatypes of Python
Numbers
Strings
Tuples
 Mutable built-in datatypes of Python
List

65
Dictionaries & Sets
6. How To Find Bugs Or Perform Static Analysis In A Python Application?
 You can use PyChecker, which is a static analyzer. It identifies the bugs in Python project
and also reveals the style and complexity related bugs.
 Another tool is Pylint, which checks whether the Python module satisfies the coding
standard.

7. When Is The Python Decorator Used?


Python decorator is a relative change that you do in Python syntax to adjust the functions
quickly.

8. What Is The Principal Difference Between A List And The


Tuple?
List Vs. Tuple.
The principal difference between a list and the tuple is that the former is mutable while the tuple
is not. A tuple is allowed to be hashed, for example, using it as a key for dictionaries.

9. How Does Python Handle Memory Management?


 Python uses private heaps to maintain its memory. So the heap holds all the Python objects
and the data structures. This area is only accessible to the Python interpreter; programmers
can’t use it.
 And it’s the Python memory manager that handles the Private heap. It does the required
allocation of the memory for Python objects.
 Python employs a built-in garbage collector, which salvages all the unused memory and
offloads it to the heap space.

10. What Are The Principal Differences Between The Lambda And Def? Lambda Vs. Def.
 Def can hold multiple expressions while lambda is a uni-expression function.
 Def generates a function and designates a name to call it later. Lambda forms a function
object and returns it.
 Def can have a return statement. Lambda can’t have return statements.
 Lambda supports to get used inside a list and dictionary.

11. Write A Reg Expression That Confirms An Email Id Using The Python Reg
Expression Module “Re”? Python has a regular expression module “re.”
Check out the “re” expression that can check the email id for .com and .co.in subdomain.
66
import re
print(re.search(r"[0-9a-zA-Z.]+@[a-zA-Z]+\.(com|co\.in)$","[email protected]"))

12. What Do You Think Is The Output Of The Following Code Fragment? Is There Any
Error In The Code?

list = ['a', 'b', 'c', 'd', 'e']


print (list[10:])
The result of the above lines of code is []. There won’t be any error like an IndexError.
You should know that trying to fetch a member from the list using an index that exceeds the
member count (for example, attempting to access list[10] as given in the question) would yield
an IndexError. By the way, retrieving only a slice at the starting index that surpasses the no. of
items in the list won’t result in an IndexError. It will just return an empty list.

13. Is There A Switch Or Case Statement In Python? If Not Then What Is The Reason For
The Same?
No, Python does not have a Switch statement, but you can write a Switch function and then use
it.
14. What Is A Built-In Function That Python Uses To Iterate Over A Number Sequence?
Range() generates a list of numbers, which is used to iterate over for loops.
for i in range(5):
print(i)
The range() function accompanies two sets of parameters.
 range(stop)
 stop: It is the no. of integers to generate and starts from zero. eg.range(3) == [0, 1, 2].
 range([start], stop[, step])
 Start: It is the starting no. of the sequence.
 Stop: It specifies the upper limit of the sequence.
 Step: It is the incrementing factor for generating the sequence.
 Points to note:
 Only integer arguments are allowed.
 Parameters can be positive or negative.
 The range() function in Python starts from the zeroth index.

15. What Are The Optional Statements Possible Inside A Try-Except Block In Python?
There are two optional clauses you can use in the try-except block.
 The “else” clause
67
 It is useful if you want to run a piece of code when the try block doesn’t create an
exception.
 The “finally” clause
 It is useful when you want to execute some steps which run, irrespective of
whether there occurs an exception or not.

16. What Is A String In Python?


A string in Python is a sequence of alpha-numeric characters. They are immutable
objects. It means that they don’t allow modification once they get assigned a value.
Python provides several methods, such as join(), replace(), or split() to alter strings. But
none of these change the original object.

17. What Is Slicing In Python?


Slicing is a string operation for extracting a part of the string, or some part of a list. In
Python, a string (say text) begins at index 0, and the nth character stores at position text[n-
1]. Python can also perform reverse indexing, i.e., in the backward direction, with the help
of negative numbers. In Python, the slice() is also a constructor function which generates
a slice object. The result is a set of indices mentioned by range(start, stop, step). The
slice() method allows three parameters. 1. start – starting number for the slicing to begin.
2. stop – the number which indicates the end of slicing. 3. step – the value to increment
after each index (default = 1).

18. What Is %S In Python?


Python has support for formatting any value into a string. It may contain quite complex
expressions.
One of the common usages is to push values into a string with the %s format
specifier. The formatting operation in Python has the comparable syntax as the C
function printf() has.

19. Is A String Immutable Or Mutable In Python?


Python strings are indeed immutable.
Let’s take an example. We have an “str” variable holding a string value. We can’t mutate
the container, i.e., the string, but can modify what it contains that means the value of the
variable.

20. What Is The Index In Python?


68
An index is an integer data type which denotes a position within an ordered list or a string.
In Python, strings are also lists of characters. We can access them using the index which
begins from zero and goes to the length minus one.
For example, in the string “Program,” the indexing happens like this:
Program 0 1 2 3 4 5

21. What Is Docstring In Python?


A docstring is a unique text that happens to be the first statement in the following Python
constructs: Module, Function, Class, or Method definition.
A docstring gets added to the doc attribute of the string object. Now, read some of the Python
interview questions on functions.

22. What Is A Function In Python Programming?


A function is an object which represents a block of code and is a reusable entity. It brings
modularity to a program and a higher degree of code reusability.
Python has given us many built-in functions such as print() and provides the ability
to create user-defined functions.

23. How Many Basic Types Of Functions Are Available In Python?


Python gives us two basic types of functions.
1. Built-in, and

2. User-defined.

The built-in functions happen to be part of the Python language. Some of these are print(),
dir(), len(), and abs() etc.

24. How Do We Write A Function In Python?


We can create a Python function in the following manner.
Step-1: to begin the function, start writing with the keyword def and then mention the function
name.
Step-2: We can now pass the arguments and enclose them using the parentheses. A colon, in the
end, marks the end of the function header.
Step-3: After pressing an enter, we can add the desired Python statements for execution.

25. What Is A Function Call Or A Callable Object In Python?


A function in Python gets treated as a callable object. It can allow some arguments and
also return a value or multiple values in the form of a tuple. Apart from the function,
Python has other constructs, such as classes or the class instances which fits in the same
69
category.

26. What Is The Return Keyword Used For In Python?


The purpose of a function is to receive the inputs and return some output.
The return is a Python statement which we can use in a function for
sending a value back to its caller.

27. What Is “Call By Value” In Python?


In call-by-value, the argument whether an expression or a value gets bound to the
respective variable in the function. Python will treat that variable as local in the function-
level scope. Any changes made to that variable will remain local and will not reflect
outside the function.

28. What Is “Call By Reference” In Python?


We use both “call-by-reference” and “pass-by-reference” interchangeably. When we pass
an argument by reference, then it is available as an implicit reference to the function,
rather than a simple copy. In such a case, any modification to the argument will also be
visible to the caller.
This scheme also has the advantage of bringing more time and space efficiency because
it leaves the need for creating local copies.
On the contrary, the disadvantage could be that a variable can get changed accidentally during
a function call. Hence, the programmers need to handle in the code to avoid such uncertainty.

29. What Is The Return Value Of The Trunc() Function?


The Python trunc() function performs a mathematical operation to remove the decimal
values from a particular expression and provides an integer value as its output.

30. Is It Mandatory For A Python Function To Return A Value?


It is not at all necessary for a function to return any value. However, if needed, we can use None
as a return value.

70
EXPERIMENT 9
FUNCTIONS – CONTINUED
a) 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 on b.

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 on b.

PROCEDURE:
To determine if two strings are nearly equal, we need to check if one string can be generated
by performing a single mutation on the other. A single mutation can be one of the following
operations:
1. Insertion: Adding one character to the string.
2. Deletion: Removing one character from the string.
3. Substitution: Replacing one character in the string with another.
Here’s the implementation of the nearly_equal function:
def nearly_equal(a, b):
"""Check if two strings are nearly equal by allowing one
mutation."""
len_a, len_b = len(a), len(b)

# If lengths differ by more than 1, they can't be nearly equal


if abs(len_a - len_b) > 1:
return False

# Count the number of differences


differences = 0
i, j = 0, 0

while i < len_a and j < len_b:


if a[i] != b[j]:
differences += 1
if differences > 1:
return False
# Move the pointer of the longer string ahead
if len_a > len_b:
i += 1
elif len_b > len_a:
j += 1
else:
i += 1
j += 1
71
else:
i += 1
j += 1

# Account for any remaining characters in the longer string


if i < len_a or j < len_b:
differences += 1

return differences <= 1


print(nearly_equal("hello", "helo")) # True (deletion of 'l')
print(nearly_equal("hello", "helloo")) # True (insertion of 'o')
print(nearly_equal("hello", "helpo")) # True (substitution of 'l' with 'p')
print(nearly_equal("hello", "heppo")) # False (two substitutions)
print(nearly_equal("hello", "hel")) # False (length difference > 1)

OUTPUT:
True
True
True
False
False

OR
def nearly_equal(a, b):
# If the strings are exactly equal, they are not nearly equal
if a == b:
return False

# Check if they are off by exactly one character in length


if abs(len(a) - len(b)) > 1:
return False

# If lengths are the same, check for one substitution


if len(a) == len(b):
differences = sum(1 for x, y in zip(a, b) if x != y)
return differences == 1

# If lengths differ by one, check for one insertion/deletion


# Make sure a is the shorter string
if len(a) > len(b):
a, b = b, a

# Check for one insertion or deletion


for i in range(len(b)):
if a == b[:i] + b[i+1:]:
return True

return False

# Example usage:
print(nearly_equal("cat", "bat")) # Output: True (one substitution)

72
print(nearly_equal("cat", "cats")) # Output: True (one insertion)
print(nearly_equal("cat", "at")) # Output: True (one deletion)
print(nearly_equal("cat", "dog")) # Output: False
OUTPUT:
True
True
True
False

EXPLANATION:
1. Length Check:
 If the lengths of the two strings differ by more than 1, they cannot be nearly equal, so we
return False.
2. Difference Counting:
 We iterate through both strings using two pointers (i for a and j for b).
 If characters at the current positions differ, we increment the differences counter.
 If the number of differences exceeds 1, we return False.
3. Handling Unequal Lengths:
 If one string is longer than the other, we move the pointer of the longer string ahead to
account for an insertion or deletion.
4. Final Check:
 After the loop, if there are remaining characters in either string, we increment
the differences counter.
 If the total number of differences is 1 or less, the strings are nearly equal, so we
return True.

73
b) Write a function dups to find all duplicates in the list.

AIM:
Write a function dups to find all duplicates in the list.

PROCEDURE:
def dups(lst):
duplicates = []
seen = set()
for item in lst:
if item in seen and item not in duplicates:
duplicates.append(item)
seen.add(item)
return duplicates

# Example usage:
my_list = [1, 2, 3, 2, 4, 5, 6, 4, 4, 7]
print(dups(my_list)) # Output: [2, 4]

OUTPUT:
[2, 4]

EXPLANATION:
1. Using a set seen to keep track of items that have already been encountered.
2. Checking if an item is in seen and not already in the duplicates list.
3. Adding the duplicate item to duplicates if the conditions are met.
4. Returning the list of duplicates.

74
c) Write a function unique to find all the unique elements of a list.

AIM:
Write a function unique to find all the unique elements of a list.

PROCEDURE:

def unique(lst):
unique_elements = []
for item in lst:
if lst.count(item) == 1:
unique_elements.append(item)
return unique_elements

# Example usage:
my_list = [1, 2, 3, 2, 4, 5, 6, 4, 4, 7]
print(unique(my_list)) # Output: [1, 3, 5, 6, 7]
OR
def unique(lst):
return list(set(lst))

# Example usage:
numbers = [1, 2, 2, 3, 4, 4, 5, 6, 6]
print(unique(numbers)) # Output: [1, 2, 3, 4, 5, 6]

OUTPUT:
[1, 3, 5, 6, 7]
[1, 2, 3, 4, 5, 6]

EXPLANATION:
 set(lst): Converts the list into a set, automatically removing duplicates.
 list(set(lst)): Converts the set back to a list.

75
VIVA QUESTIONS

1. What Does The Continue Do In Python?


The continue is a jump statement in Python which moves the control to execute the next
iteration in a loop leaving all the remaining instructions in the block unexecuted.
The continue statement is applicable for both the “while” and “for” loops.

2. What Is The Purpose Of Id() Function In Python?

The id() is one of the built-in functions in Python.

3. What Does The *Args Do In Python?


We use *args as a parameter in the function header. It gives us the ability to pass N (variable)
number of arguments.

4. What Does The **Kwargs Do In Python?


We can also use the **kwargs syntax in a Python function declaration. It let us

5. What Does The Name Do In Python?


The name is a unique variable. Since Python doesn’t expose the main() function, so when
its interpreter gets to run the script, it first executes the code which is at level 0 indentation.

6. What Is The Purpose Of “End” In Python?


Python’s print() function always prints a newline in the end. The print() function accepts an
optional parameter known as the ‘end.’ Its value is ‘\n’ by default. We can change the end
character in a print statement with the value of our choice using this parameter.

7. When Should You Use The “Break” In Python?


Python provides a break statement to exit from a loop. Whenever the break hits in the code, the
control of the program immediately exits from the body of the loop.
The break statement in a nested loop causes the control to exit from the inner iterative block.

8. What Is The Difference Between Pass And Continue In Python?


The continue statement makes the loop to resume from the next iteration.
On the contrary, the pass statement instructs to do nothing, and the remainder of the code
executes as usual.

76
9. What Does The Len() Function Do In Python?
In Python, the len() is a primary string function. It determines the length of an input string.

10. What Does The Chr() Function Do In Python?


The chr() function got re-added in Python 3.2. In version 3.0, it got removed.

11. What Does The Ord() Function Do In Python?


The ord(char) in Python takes a string of size one and returns an integer denoting the Unicode
code format of the character in case of a Unicode type object, or the value of the byte if the
argument is of 8-bit string type.

12. What Is Rstrip() In Python?


Python provides the rstrip() method which duplicates the string but leaves out the whitespace
characters from the end.

13. What Is Whitespace In Python?


Whitespace represents the characters that we use for spacing and separation. They possess an
“empty” representation. In Python, it could be a tab or space.

14. What Is Isalpha() In Python?


Python provides this built-in isalpha() function for the string handling purpose.
It returns True if all characters in the string are of alphabet type, else it returns False.

15. How Do You Use The Split() Function In Python?


Python’s split() function works on strings to cut a large piece into smaller chunks, or sub-strings.
We can specify a separator to start splitting, or it uses the space as one by default.

16. What Does The Join Method Do In Python?


Python provides the join() method which works on strings, lists, and tuples. It combines them
and returns a united value.

17. What Does The Title() Method Do In Python?


Python provides the title() method to convert the first letter in each word to capital format while
the rest turns to Lowercase.

77
18. What Makes TheCPython Different From Python?
CPython has its core developed in C. The prefix ‘C’ represents this fact. It runs an interpreter
loop used for translating the Python-ish code to C language.

19. Which Package Is The Fastest Form Of Python?


PyPy provides maximum compatibility while utilizing CPython implementation for improving
its performance. The tests confirmed that PyPy is nearly five times faster than the CPython. It
currently supports Python 2.7.

20. What Is GIL In Python Language?


Python supports GIL (the global interpreter lock) which is a mutex used to secure access to
Python objects, synchronizing multiple threads from running the Python bytecodes at the same
time.

21. How Is Python Thread Safe?


Python ensures safe access to threads. It uses the GIL mutex to set synchronization. If a
thread loses the GIL lock at any time, then you have to make the code thread-safe.

22. How Does Python Manage The Memory?


Python implements a heap manager internally which holds all of its objects and data structures.

23. What Is A Tuple In Python?


A tuple is a collection type data structure in Python which is immutable.
They are similar to sequences, just like the lists. However, There are some differences between
a tuple and list; the former doesn’t allow modifications whereas the list does.

24. What Is A Dictionary In Python Programming?


A dictionary is a data structure known as an associative array in Python which stores a
collection of objects. The collection is a set of keys having a single associated value. We can
call it a hash, a map, or a hashmap as it gets called in other programming languages.

25. What Is The Set Object In Python?


Sets are unordered collection objects in Python. They store unique and immutable objects.
Python has its implementation derived from mathematics.

78
26. What Is The Use Of The Dictionary In Python?
A dictionary has a group of objects (the keys) map to another group of objects (the values). A
Python dictionary represents a mapping of unique Keys to Values.
They are mutable and hence will not change. The values associated with the keys can be of any
Python types.

27. Is Python List A Linked List?


A Python list is a variable-length array which is different from C-style linked lists.
Internally, it has a contiguous array for referencing to other objects and stores a pointer to the
array variable and its length in the list head structure.
Here are some Python interview questions on classes and objects.

28. What Does The “Self” Keyword Do?


The self is a Python keyword which represents a variable that holds the instance of an object.
In almost, all the object-oriented languages, it is passed to the methods as a hidden parameter.

29. What is the Syntax for Dictionary Comprehension in Python?

A dictionary has the same syntax as was for the list comprehension but the difference is that it
uses curly braces:

30. What Is The Syntax For List Comprehension In Python?


The signature for the list comprehension is as follows:
[ expression(var)forvariniterable]

79
EXPERIMENT 10
FUNCTIONS – PROBLEM SOLVING
a) Write a function cumulative_ product to compute cumulative product of a list of
numbers.

AIM:
Write a function cumulative_ product to compute cumulative product of a list of
numbers.

PROCEDURE:
def cumulative_product(lst):
result = []
product = 1
for num in lst:
product *= num
result.append(product)
return result

# Example usage:
my_list = [1, 2, 3, 4]
print(cumulative_product(my_list)) # Output: [1, 2, 6, 24]

OUTPUT:
[1, 2, 6, 24]

EXPLANATION:
1. It initializes an empty list result to store the cumulative products.
2. It uses a variable product initialized to 1 to keep track of the running product.
3. It loops through each number in the input list, multiplying product by the current number.
4. It appends the current cumulative product to result.
5. It returns the list of cumulative products.

80
b) Write a function reverse to reverse a list. Without using the reverse function.

AIM:
Write a function reverse to reverse a list. Without using the reverse function.

PROCEDURE:
def reverse(lst):
reversed_list = []
for i in range(len(lst)-1, -1, -1):
reversed_list.append(lst[i])
return reversed_list

# Example usage:
my_list = [1, 2, 3, 4, 5]
print(reverse(my_list)) # Output: [5, 4, 3, 2, 1]

OR
def reverse(lst):
return lst[::-1]

# Example usage:
my_list = [1, 2, 3, 4, 5]
print(reverse(my_list)) # Output: [5, 4, 3, 2, 1]

OUTPUT:
[5, 4, 3, 2, 1]

EXPLANATION:
1. It initializes an empty list reversed_list.
2. It loops through the input list in reverse order using a range() that starts from the last index
(len(lst)-1) and goes down to 0.
3. It appends each element to reversed_list.
4. It returns the reversed list.

81
c) Write function to compute GCD, LCM of two numbers. Each function shouldn’t
exceed one line.
AIM:
Write function to compute GCD, LCM of two numbers. Each function shouldn’t
exceed one line.
PROCEDURE:
from math import gcd

# GCD Function
gcd_two_numbers = lambda a, b: gcd(a, b)

# LCM Function
lcm_two_numbers = lambda a, b: (a * b) // gcd(a, b)
print(gcd(12, 18)) # Output: 6
print(lcm(12, 18)) # Output: 36
OR
gcd = lambda a, b: a if b == 0 else gcd(b, a % b)
lcm = lambda a, b: abs(a * b) // gcd(a, b)
print(gcd(12, 18)) # Output: 6
print(lcm(12, 18)) # Output: 36

OUTPUT:
6
36
EXPLANATION:
 gcd() is a built-in function from the math module that computes the Greatest Common Divisor.

82
VIVA QUESTIONS:

1. What Is The Syntax For Dictionary Comprehension In Python?


A dictionary has the same syntax as was for the list comprehension but the difference is that it
uses curly braces
{aKey,itsValueforaKeyiniterable}

2. How Do You Check The Presence Of A Key In A Dictionary?

We can use Python’s “in” operator to test the presence of a key inside a dict object.

3. How Do You Delete Elements Of A Dictionary In Python?

We can delete a key in a dictionary by using the del() method.

4. How Do You Add Elements To A Dictionary In Python?

We can add elements by modifying the dictionary with a fresh key and then set the value to it.

5. How Do You Traverse Through A Dictionary Object In Python?

We can use the “for” and “in” loop for traversing the dictionary object.

6. How Do You Read From A Dictionary In Python?

To fetch data from a dictionary, we can directly access using the keys. We can enclose a “key”
using brackets […] after mentioning the variable name corresponding to the dictionary.

7. How Do You Create A Dictionary In Python?

Let’s take the example of building site statistics. For this, we first need to break up the key-
value pairs using a colon(“:”). The keys should be of an immutable type, i.e., so we’ll use the
data-types which don’t allow changes at runtime. We’ll choose from an int, string, or tuple.

8. What Are Decorators In Python?

Python decorator gives us the ability to add new behavior to the given objects dynamically.

9. What Is Class In Python?


Python supports object-oriented programming and provides almost all OOP features to use in
programs. A Python class is a blueprint for creating the objects. It defines member variables
and gets their behavior associated with them.

83
We can make it by using the keyword “class.” An object gets created from the constructor. This
object represents the instance of the class.

10. What Are Attributes And Methods In A Python Class?


A class is useless if it has not defined any functionality. We can do so by adding attributes.
They work as containers for data and functions. We can add an attribute directly specifying
inside the class body.

11. How To Assign Values For The Class Attributes At Runtime?


We can specify the values for the attributes at runtime. We need to add an init method and pass
input to object constructor. See the following example demonstrating this.

12. What Is Inheritance In Python Programming?


Inheritance is an OOP mechanism which allows an object to access its parent class features. It
carries forward the base class functionality to the child.

13. What Is Composition In Python?


The composition is also a type of inheritance in Python. It intends to inherit from the base class
but a little differently, i.e., by using an instance variable of the base class acting as a member
of the derived class.

14. What Are Errors And Exceptions In Python Programs?


Errors are coding issues in a program which may cause it to exit abnormally.

On the contrary, exceptions happen due to the occurrence of an external event which interrupts
the normal flow of the program.

15. How Do You Handle Exceptions With Try/Except/Finally In Python?


Python lay down Try, Except, Finally constructs to handle errors as well as Exceptions. We
enclose the unsafe code indented under the try block. And we can keep our fall-back code inside
the except block. Any instructions intended for execution last should come under the finally
block.

16. How Do You Raise Exceptions For A Predefined Condition In Python?


We can raise an exception based on some condition.

84
17. What Are Python Iterators?
Iterators in Python are array-like objects which allow moving on the next element. We use them
in traversing a loop, for example, in a “for” loop.

18. What Is The Difference Between An Iterator And Iterable?


The collection type like a list, tuple, dictionary, and set are all iterable objects whereas they are
also iterable containers which return an iterator while traversing.

19. What Are Python Generators?


A Generator is a kind of function which lets us specify a function that acts like an iterator and
hence can get used in a “for” loop.

20. What Are Closures In Python?


Python closures are function objects returned by another function. We use them to eliminate
code redundancy.

21. What Are Decorators In Python?


Python decorator gives us the ability to add new behavior to the given objects dynamically. In
the example below, we’ve written a simple example to display a message pre and post the
execution of a function.

22. How Do You Create A Dictionary In Python?


Let’s take the example of building site statistics. For this, we first need to break up the key-
value pairs using a colon(“:”). The keys should be of an immutable type, i.e., so we’ll use the
data-types which don’t allow changes at runtime. We’ll

23. How Do You Read From A Dictionary In Python?


To fetch data from a dictionary, we can directly access using the keys. We can enclose a “key”
using brackets […] after mentioning the variable name corresponding to the dictionary.

24. How Do You Traverse Through A Dictionary Object In Python?


We can use the “for” and “in” loop for traversing the dictionary object.

25. How Do You Add Elements To A Dictionary In Python?


We can add elements by modifying the dictionary with a fresh key and then set the value to it.
85
26. How Do You Delete Elements Of A Dictionary In Python?
We can delete a key in a dictionary by using the del() method.

27. How Do You Check The Presence Of A Key In A Dictionary?


We can use Python’s “in” operator to test the presence of a key inside a dict object.

28. What Is The Syntax For List Comprehension In Python?


The signature for the list comprehension is as follows:

29. What Is The Syntax For Dictionary Comprehension In Python?


A dictionary has the same syntax as was for the list comprehension but the difference is that it
uses curly braces:

30. What Is The Syntax For Generator Expression In Python?


The syntax for generator expression matches with the list comprehension, but the difference is
that it uses parenthesis:
( expression(var) for var in iterable )

86
EXPERIMENT 11
GUI, GRAPHICS
a) Write a GUI for an Expression Calculator using tk
AIM:
Write a GUI for an Expression Calculator using tk
PROCEDURE:
Here is a simple Expression Calculator built using Python's Tkinter library. This calculator can
evaluate mathematical expressions entered by the user.
Features:
 User can input expressions like 2+3*4, (10/2)+5, etc.
 Supports basic arithmetic operations: +, -, *, /, and parentheses.
 Displays the result in a text field.
 Clear button to reset the input.

# Python program to create a simple GUI


# calculator using Tkinter

# import everything from tkinter module


from tkinter import *

# globally declare the expression variable


expression = ""

# Function to update expression


# in the text entry box
def press(num):
# point out the global expression variable
global expression

# concatenation of string
expression = expression + str(num)

# update the expression by using set method


equation.set(expression)

87
# Function to evaluate the final expression
def equalpress():
# Try and except statement is used
# for handling the errors like zero
# division error etc.

# Put that code inside the try block


# which may generate the error
try:

global expression

# eval function evaluate the expression


# and str function convert the result
# into string
total = str(eval(expression))

equation.set(total)

# initialize the expression variable


# by empty string
expression = ""

# if error is generate then handle


# by the except block
except:

equation.set(" error ")


expression = ""

# Function to clear the contents


# of text entry box
def clear():
global expression
expression = ""
equation.set("")
88
# Driver code
if __name__ == "__main__":
# create a GUI window
gui = Tk()

# set the background colour of GUI window


gui.configure(background="light green")

# set the title of GUI window


gui.title("Simple Calculator")

# set the configuration of GUI window


gui.geometry("270x150")

# StringVar() is the variable class


# we create an instance of this class
equation = StringVar()

# create the text entry box for


# showing the expression .
expression_field = Entry(gui, textvariable=equation)

# grid method is used for placing


# the widgets at respective positions
# in table like structure .
expression_field.grid(columnspan=4, ipadx=70)

# create a Buttons and place at a particular


# location inside the root window .
# when user press the button, the command or
# function affiliated to that button is executed .
button1 = Button(gui, text=' 1 ', fg='black', bg='red',
command=lambda: press(1), height=1, width=7)
button1.grid(row=2, column=0)

button2 = Button(gui, text=' 2 ', fg='black', bg='red',


89
command=lambda: press(2), height=1, width=7)
button2.grid(row=2, column=1)

button3 = Button(gui, text=' 3 ', fg='black', bg='red',


command=lambda: press(3), height=1, width=7)
button3.grid(row=2, column=2)

button4 = Button(gui, text=' 4 ', fg='black', bg='red',


command=lambda: press(4), height=1, width=7)
button4.grid(row=3, column=0)

button5 = Button(gui, text=' 5 ', fg='black', bg='red',


command=lambda: press(5), height=1, width=7)
button5.grid(row=3, column=1)

button6 = Button(gui, text=' 6 ', fg='black', bg='red',


command=lambda: press(6), height=1, width=7)
button6.grid(row=3, column=2)

button7 = Button(gui, text=' 7 ', fg='black', bg='red',


command=lambda: press(7), height=1, width=7)
button7.grid(row=4, column=0)

button8 = Button(gui, text=' 8 ', fg='black', bg='red',


command=lambda: press(8), height=1, width=7)
button8.grid(row=4, column=1)

button9 = Button(gui, text=' 9 ', fg='black', bg='red',


command=lambda: press(9), height=1, width=7)
button9.grid(row=4, column=2)

button0 = Button(gui, text=' 0 ', fg='black', bg='red',


command=lambda: press(0), height=1, width=7)
button0.grid(row=5, column=0)

plus = Button(gui, text=' + ', fg='black', bg='red',


90
command=lambda: press("+"), height=1, width=7)
plus.grid(row=2, column=3)

minus = Button(gui, text=' - ', fg='black', bg='red',


command=lambda: press("-"), height=1, width=7)
minus.grid(row=3, column=3)

multiply = Button(gui, text=' * ', fg='black', bg='red',


command=lambda: press("*"), height=1, width=7)
multiply.grid(row=4, column=3)

divide = Button(gui, text=' / ', fg='black', bg='red',


command=lambda: press("/"), height=1, width=7)
divide.grid(row=5, column=3)

equal = Button(gui, text=' = ', fg='black', bg='red',


command=equalpress, height=1, width=7)
equal.grid(row=5, column=2)

clear = Button(gui, text='Clear', fg='black', bg='red',


command=clear, height=1, width=7)
clear.grid(row=5, column='1')

Decimal= Button(gui, text='.', fg='black', bg='red',


command=lambda: press('.'), height=1, width=7)
Decimal.grid(row=6, column=0)
# start the GUI
gui.mainloop()

91
b) Write a program to implement the following figures using turtle

AIM:
Write a program to implement the following figures using turtle

PROCEDURE 1:
import turtle as tt
tt.pensize(5)
tt.speed(10)
for i in range(4):
for color in ('red','blue','green'):
tt.color(color)
tt.circle(50)
tt.left(30)
tt.hideturtle()

PROCEDURE 2:
import turtle
for i in range(36):
for j in range(4):
turtle.fd(100)
turtle.rt(90)
turtle.rt(30)

OUTPUT:

92
EXPLANATION:
 Ensure Python and Turtle module are installed on your system.
 Save each code block as separate files (figure1.py and figure2.py).
 Open a terminal or command prompt and navigate to the file's directory.

93
VIVA QESTIONS:

1. How Do You Write A Conditional Expression In Python?

We can utilize the following single statement as a conditional expression. default_statment if


Condition else another_statement

2. What Do You Know About The Python Enumerate?

While using the iterators, sometimes we might have a use case to store the count of iterations.
Python gets this task quite easy for us by giving a built-in method known as the enumerate().
The enumerate() function attaches a counter variable to an iterable and returns it as the
“enumerated” object.

3. What Is The Use Of Globals() Function In Python?

The globals() function in Python returns the current global symbol table as a dictionary object.

Python maintains a symbol table to keep all necessary information about a program. This info
includes the names of variables, methods, and classes used by the program.
All the information in this table remains in the global scope of the program and Python allows
us to retrieve it using the globals() method.

4. Why Do You Use The Zip() Method In Python?

The zip method lets us map the corresponding index of multiple containers so that we can use
them using as a single unit.

5. What Are Class Or Static Variables In Python Programming?

In Python, all the objects share common class or static variables.

But the instance or non-static variables are altogether different for different objects.

6. How Does The Ternary Operator Work In Python?

The ternary operator is an alternative for the conditional statements. It combines true or false
values with a statement that you need to test.

7. What Does The “Self” Keyword Do?

The self is a Python keyword which represents a variable that holds the instance of an object.
94
In almost, all the object-oriented languages, it is passed to the methods as a hidden parameter.

8. What Are The Different Methods To Copy An Object In Python? There are two ways to
copy objects in Python.
copy.copy() function

It makes a copy of the file from source to destination. It’ll return a shallow copy of the
parameter.
copy.deepcopy() function

It also produces the copy of an object from the source to destination.

It’ll return a deep copy of the parameter that you can pass to the function.

9. What Is The Purpose Of Docstrings In Python?

In Python, the docstring is what we call as the docstrings. It sets a process of recording Python
functions, modules, and classes.

10. Which Python Function Will You Use To Convert A Number To A String?

For converting a number into a string, you can use the built-in function str(). If you want an
octal or hexadecimal representation, use the inbuilt function oct() or hex().

11. How Do You Debug A Program In Python? Is It Possible To Step Through The Python
Code?

Yes, we can use the Python debugger (pdb) to debug any Python program. And if we start a
program using pdb, then it let us even step through the code.

12. List Down Some Of The PDB Commands For Debugging Python Programs? Here are a
few PDB commands to start debugging Python code.
Add breakpoint (b) Resume execution (c) Step by step debugging (s) Move to the next line (n)
List source code (l)
Print an expression (p)

13. What Is The Command To Debug A Python Program?

The following command helps run a Python program in debug mode.


95
14. $ python -m pdb python-script.py

15. How Do You Monitor The Code Flow Of A Program In Python?

In Python, we can use the sys module’s settrace() method to setup trace hooks and monitor the
functions inside a program.
You need to define a trace callback method and pass it to the settrace() function. The callback
should specify three arguments as shown below.

16. Why And When Do You Use Generators In Python?

A generator in Python is a function which returns an iterable object. We can iterate on the
generator object using the yield keyword. But we can only do that once because their values
don’t persist in memory, they get the values on the fly.
Generators give us the ability to hold the execution of a function or a step as long as we want
to keep it. However, here are a few examples where it is beneficial to use generators.

17. What Does The Yield Keyword Do In Python?

The yield keyword can turn any function into a generator. It works like a standard return
keyword. But it’ll always return a generator object. Also, a method can have multiple calls to
the yield keyword.

18. How To Convert A List Into Other Data Types?

Sometimes, we don’t use lists as is. Instead, we have to convert them to other types.

19. How Do You Count The Occurrences Of Each Item Present In The List Without
Explicitly Mentioning Them?

Unlike sets, lists can have items with the same values.
In Python, the list has a count() function which returns the occurrences of a particular item.

20. What Are Different Ways To Create An Empty NumPy Array In Python?

There are two methods which we can apply to create empty NumPy arrays. The First Method

import numpy
numpy.array([])
To Create An Empty Array.
96
The Second Method To Create An Empty Array.

# Make an empty NumPy array


numpy.empty(shape=(0,0))

21. What is the output of print str if str = 'Hello World!'?

It will print complete string. Output would be Hello World!.What is the output of print str[0] if
str = 'Hello World!'?

It will print first character of the string. Output would be H.

22. What is the output of print str[2:5] if str = 'Hello World!'?

It will print characters starting from 3rd to 5th. Output would be llo.

23. What is the output of print str[2:] if str = 'Hello World!'?

It will print characters starting from 3rd character. Output would be lloWorld!.

24. What is the output of print str * 2 if str = 'Hello World!'?

It will print string two times. Output would be Hello World!Hello World!.

25. What is the output of print str + "TEST" if str = 'Hello World!'?

It will print concatenated string. Output would be Hello World!TEST.

26. What is the output of print list if list = [ bcd', 786 , 2.23, 'john', 70.2 ]?

it will print complete list. Output would be ['abcd', 786, 2.23, 'john', 70.200000000000003].

27. What is the output of print list[0] if list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]?

It will print first element of the list. Output would be abcd.

28. What is the output of print list[1:3] if list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]?
It will print elements starting from 2nd till 3rd. Output would be [786, 2.23].

97
29. What is the output of print list[2:] if list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]?

It will print elements starting from 3rd element. Output would be [2.23, 'john',
70.200000000000003].

30. How Does The Ternary Operator Work In Python?


The ternary operator is an alternative for the conditional statements. It combines true or false
values with a statement that you need to test.

98
EXPERIMENT 12
DATA BASES
a) Develop a Python application to create a table, Insert rows into the table, Updates rows in
the table, Delete rows from the table and Drops the table. [ Use MySql ]
AIM:
Develop a Python application to create a table, Insert rows into the table, Updates rows in
the table, Delete rows from the table and Drops the table. [ Use MySql ]
PROCEDURE:
#importing required library
import mysql
# connecting to the database
con=pymysql.connect(host='localhost',database='anyname',user='root',password='mysql')
# preparing a cursor object
cursor=con.cursor()
cursor.execute('create table empo(')
cursor.execute('insert into emp values()')
cursor.execute('insert into emp values()')
cursor.execute('insert into emp values()')
query="select * from emp"
cursor.execute(query)
a=cursor.fetchall()
for i in a:
print(i)
cursor.execute('update tablename set ename=" " where eno=')
print("After performing updation operation on the table emp")
query="select * from emp"
cursor.execute(query)
a=cursor.fetchall()
for i in a:
print(i)
cursor.execute('delete from tablename where eno=')
print("After performing deletion operation on the table emp")
query="select * from emp"
cursor.execute(query)
a=cursor.fetchall()
for i in a:
print(i)
#cursor.execute('drop table tablename')
con.commit()
con.rollback()

99
VIVA QUESTIONS:

1. How do you debug a Python program?


By using this command we can debug a python program
$ python -m pdb python-script.py

2. What is <Yield> Keyword in Python?


The <yield> keyword in Python can turn any function into a generator. Yields work like a
standard return keyword. But it’ll always return a generator object. Also, a function can have
multiple calls to the <yield> keyword.

3. How to convert a list into a string?


When we want to convert a list into a string, we can use the <”.join()> method which joins all
the elements into one and returns as a string.

4. How to convert a list into a tuple?


By using Python <tuple()> function we can convert a list into a tuple. But we can’t change
the list after turning it into tuple, because it becomers immutable.

5. How to convert a list into a set?


User can convert list into set by using <set()> function.

6. How to count the occurrences of a perticular element in the list?


In Python list, we can count the occurences of a individual element by using a <count()>
function.

7. What is NumPy array?


NumPy arrays are more flexible then lists in Python. By using NumPy arrays reading and
writing items is faster and more efficient.

8. How can you create Empty NumPy Array In Python?


We can create Empty NumPy Array in two ways in Python,
1) import numpy numpy.array([])

2) numpy.empty(shape=(0,0))

100
9. What is a negative index in Python?
Python has a special feature like a negative index in Arrays and Lists. Positive index reads
the elements from the starting of an array or list but in the negative index, Python reads
elements from the end of an array or list.

10. What is the output of the below code?


>> import array
>>> a = [1, 2, 3]
>>> print a[-3]
>>> print a[-2]
>>> print a[-1]
The output is: 3, 2, 1

11. What is the output of the below program?


>>>names = [‘Chris’, ‘Jack’, ‘John’, ‘Daman’]
>>>print(names[-
1][-1]) The
output is: n

12. What is Enumerate() Function in Python?


The Python enumerate() function adds a counter to an iterable object. enumerate() function can
accept sequential indexes starting from zero.

13. What is data type SET in Python and how to work with it?
The Python data type “set” is a kind of collection. It has been part of Python since version 1

14. How do you Concatenate Strings in Python?


We can use ‘+’ to concatenate strings.

15. How to generate random numbers in Python?


We can generate random numbers using different functions in Python. They are:

16. How to print sum of the numbers starting from 1 to 100?


We can print sum of the numbers starting from 1 to 100 using this code:

101
17. How do you set a global variable inside a function?
Yes, we can use a global variable in other functions by declaring it as global in each function
that assigns to it:

18. What is namespace in Python?


In Python, every name introduced has a place where it lives and can be hooked for. This
is known as namespace. It is like a box where a variable name is mapped to the object
placed. Whenever the variable is searched out, this box will be searched, to get
corresponding object.

19. What is lambda in Python?


It is a single expression anonymous function often used as inline function.

20. Why lambda forms in python does not have statements?

A lambda form in python does not have statements as it is used to make new function
object and then return them at runtime.

21. What is pass in Python?


Pass means, no-operation Python statement, or in other words it is a place holder in
compound statement, where there should be a blank left and nothing has to be written
there.

22. In Python what are iterators?


In Python, iterators are used to iterate a group of elements, containers like list.

23. What is unittest in Python?


A unit testing framework in Python is known as unittest. It supports sharing of setups,
automation testing, shutdown code for tests, aggregation of tests into collections etc.

24. In Python what is slicing?


A mechanism to select a range of items from sequence types like list, tuple, strings etc. is known
as slicing.

102
25. What are generators in Python?
The way of implementing iterators are known as generators. It is a normal function except
that it yields expression in the function.

26. What is negative index in Python?


Python sequences can be index in positive and negative numbers. For positive index, 0 is
the first index, 1 is the second index and so forth. For negative index, (-1) is the last index
and (-2) is the second last index and so forth.

27. How you can convert a number to a string?


In order to convert a number into a string, use the inbuilt function str(). If you want a octal or
hexadecimal representation, use the inbuilt function oct() or hex().

28. What is the difference between Xrange and range?


Xrange returns the xrange object while range returns the list, and uses the same memory
and no matter what the range size is.

29. What is module and package in Python?


In Python, module is the way to structure program. Each Python program file is a module,
which imports other modules like objects and attributes.

30. How can you share global variables across modules?


To share global variables across modules within a single program, create a special
module. Import the config module in all modules of your application. The module will
be available as a global variable across modules.

103

You might also like