Python Answers
Python Answers
UNIT-1
Q1 Illustrate the concepts of tuple in python with regard to creation, accessing, updating, and
deleting.
A1 In Python a tuple is an ordered collection of items that is immutable, meaning its elements cannot
be changed once it is created.Tuples are defined using parentheses() and can contain elements of
different datatypes.
1) Creation of a tuple: To create a tuple you can simply enclose comma-seprated values
within parantheses.
Eg: tuple = (1, 2, 3, ‘a’, ‘b’, ‘c’)
2) Accessing tuple elements: Tuple elements can be accessed using indexing.Indexing starts
from 0 for the first element.
Eg: print(tuple[0]) #output: 1
print(tuple[3]) #output: ‘a’
3) Updating a Tuple: Since tuples are immutable, you cannot update individual elements
directly. However, you can create a new tuple by concatenating or slicing the existing
tuples.
Eg: new_tuple = tuple + (‘X’ , ‘Y’, ‘Z’)
print(new_tuple) #Output : (1, 2, 3, ‘a’, ‘b’ , ‘c’ , ‘x’ , ‘y’ , ‘z’ )
4) Deleting a Tuple: Since tuples are immutable, you cannot delete individual elements.
However, you can delete the entire tuple using the ‘del’ keyword.
Eg: del tuple
print(tuple) #raises nameerror: name ‘tuple’ not defined
Q2 Discuss the features of python programming language in detail.
A2 Python is a versatile and powerful programming language known for its simplicity, readability and
extensive set of libraries and frameworks.
Here are some key features of python:
1. Readability: Python emphasizes code readability and uses a clean and consistent syntax. It
uses indentation and whitespaces to define code blocks, making it easy to read and
understand
2. Easy to learn and use: Python has a straightforward and beginner-friendly syntax, making
it easy to learn for newcomers to programming.
3. Large Standard library: Python comes with a large standard library that provides ready-
to-use modules and functions for various tasks. This extensive library makes it easy to
perform a wide range of tasks without requiring additional external libraries
4. Third party libraries and framework: Python has a rich ecosystem of third party libraries
and frameworks that extend its functionality for various domains such as webdevelopment
data analysis machine learning etc. Popular libraries include Numpy,Pandas ,Django and
Flask
5. Interpreted language: Python is an interpreted language, which means that code is
executed line by line at runtime by the Python interpreter.
6. Object oriented Programming: Python supports object oriented programming principles
allowing developers to structure their code using classes and objects.
7. Cross-platform: Python is a cross platfrom language, meaning it can run on different
operating systems.
8. Dynamic typing: Python is dynamically typed, meaning variable types are determined by
runtime.
9. Extensibility: Python can be extended by writing modules in other languages such as C
and C++,
10. Community and support: Python has a vibrant and active community of developers
worldwide
Q3 Explain the concept of implicit and explicit data type conversion. Give two examples for
each data type conversion.
A3 Implicit datatype conversion: Implicit data type conversion, also knows as automatic or implicit
casting, occurs automatically by the interpreter when an operation involves operands of different
types. Python automatically converts one data types to another based on predefined set of rules.
Eg:
Implicit conversion from int to float
x=5
y = 2.5 + x
print(y) #output: 7.5
Explicit Data Type Conversion: Explicit data type conversion, also known as type casting, is
performed explicitly by the programmer using built-in functions or constructors to convert a value
from one type to another. Here are two examples:
Eg:
Explicit conversion from float to int
p = 3.7
q = int(p)
print(q) #output: 3
Explicit conversion from string to list
text = “Hello”
lst = list(text)
print(lst) #output: [‘H’, ‘e’, ‘l’ , ‘l’, ‘o’]
Q4 Write a python code to:
i. Print the values of tuples separately, give the tuple = (2,4,6,8,10).
ii. Input a string and count all the lower case, upper case, numbers and special
characters
Q5 Write a python code to replace key Income to Salary in the following dictionary and print
the modified dictionary as output.
dict1={"name": "Prashanth", "age": 28, "Income": 10000, "City":"Kolar"}
Q6 Marks scored by the student in five different course is given as a dictionary. Write a python
code to find the sum and average of the digits, ignoring all Other characters.
dict1={"Maths": 98, "BTD": 62, "FME": 76, "MSM":63, "MAP": 80}
Q7 Write a python code to remove all the occurence of the number 28 from the list given and
print the modified list.
list = ["Raju", 2 , "Apple" , 28, 54, 24, 28, 89, "India" ,92 ,28]
Q8 What is python dictionary? Create a dictionary which consists of names and age of four
students. Try to add the email of the students to the existing dictionary.
A8 A python dictonary is an unordered collection of key-valued pairs. It is also known as an associative
array or hashmap.Dictonaries are enclosed in curly braces ‘{}’ and consist of keys and their
corresponding values.Keys are unique within dictonaries and they are used to access the associated
values efficiently.
To create a dictionary consisting of names and ages of four students, and then add the email
addresses to the existing dictionary
Q9 Write a python program to find the area of the triangle, given the three sides of the triangle
as a, b and c. Input suitable values for of a, b and c from the terminal.
Q10 Write a python code to convert Celsius to Fahrenheit and Fahrenheit to Celsius. The
program to should be able to read the temperature values from the terminal.
A11 Statements in python is a unit of code that performs an action. It typically ends with a
newline or a semicolon(;). Assignment statements, Function call statements, conditional statements
Eg: x = 10;
Print(“Hello, world!”)
Expressions in python is a combination of values, variables, operators, and a function calls that
results in a value. Expressions can be a part of a larger statements or can stand alone as a statement
by themselves. Arithmetic Expression , Comparison Expression, Function call expression etc
Eg: result = 2 + 3 + 4
is_equal = (x == y)
sum_value = sum([1, 2, 3, 4, 5,])
Q12 Discuss any two exception handling in python
A12 ‘try-except’ statement: this allows you to handle exceptions that may occur during the
execution of a block of code. It provides a way to catch and handle specific types of exceptions,
preventing the program from terminating abruptly
Eg:
In this example, the try block contains the code that may potentially raise exceptions. If an
exception occurs, the program jumps to the corresponding except block based on the type of
exception. The ZeroDivisionError exception is caught if the user enters 0 as the second number,
and the ValueError exception is caught if the user enters non-integer values. The program prints
an error message based on the caught exception.
‘finally’ Block: it is used along ‘try-except’ statement to define a block of code that always
executes, regardless of whether an exception occurs or not. It is useful for performing cleanup
operations or releasing resources that should be executed underall circumstances
In this example, the try block attempts to open a file for reading. If an IOError occurs (e.g., if the
file doesn't exist or cannot be opened), an error message is printed. The finally block is always
executed, ensuring that the file is closed, regardless of whether an exception occurred or not.
Q13 What is data type conversion?
A13 Data type conversion in python refers to the process of converting a value from one data
type to another in Python. Python provides built in functions and methods to facilitate these
conversions.
Q14 What is python variable? What are four rules for creating the variables? Explain the
same through an example.
A14 A variable is a named reference value stored in computer’s memory. It is a way to assign a
label or a name to a value, making it easier to refer and to manipulate that value in a program.
Four rules for creating variables in python :
1. Variable name must start with the letter or an underscore(_) character
2. Variable names can contain letters, numbers, and underscores
3. Variable names are case sensitive
4. Variable name should be descriptive and follow a naming convention
Eg:
Q15 With the help of examples, explain lists and tuples
A15 Lists: lists are ordered mutable and versatile data structures in python. They are defined
using square brackets[] and can contain elements of different data types. Elements in a list are
separated by commas and can be accessed by using indexing and slicing. List can be modified by
adding, removing or changing elements
Tuples: Tuples are ordered, immutable sequences in python. They are defined using paranthesis()
or without any brackets. Tuples can contain elements of different data types, similar to lists.
Elements in a tuple are separated by commas and can be accessed using indexing and slicing
Q16 Illustrate various datatypes in python with suitable examples.
age = 25
height = 1.75
complex_num = 3 + 4j
2. String:
3. Boolean:
is_student = True
4. List:
- Lists are mutable, allowing modifications like adding, removing, or changing elements.
numbers = [1, 2, 3, 4, 5]
5. Tuple:
- Dictionaries are mutable and allow easy retrieval and modification of values based on their keys.
7. Set:
- An unordered collection of unique elements enclosed in curly braces {} or created using the `set()`
function.
- They are useful for operations like membership testing, removing duplicates, and mathematical
operations.
unique_numbers = {1, 2, 3, 4, 5}
These are just a few examples of commonly used data types in Python. Each data type serves different
purposes and has specific properties and methods associated with it. Understanding these data types
allows you to work with different kinds of data efficiently within your Python programs.
Q17 Define Set & Illustrate with an example how you add and access the items defined in
set.
In Python, a set is an unordered collection of unique elements. It is defined using curly braces {} or
the set() function. Sets do not allow duplicate values, and the order of elements is not guaranteed.
Q18 Define Tuple & explain the following with a suitable example each:-
i. Create a Tuple
ii. Find length of a Tuple
iii. Convert the type to list and change the values
The len() function is used to determine the length or the number of elements in a tuple.
Tuples are immutable, meaning their elements cannot be modified once created. However, we can
convert a tuple to a list using the list() function, make changes to the list, and convert it back to a
tuple if desired.
UNIT-2
Q1 Write a program using python to find whether a number is a Power of Two or not
Q2 Write a python code to read a file and append it six new lines and output the updated file.
Q3 Provide a python code to write all the contents of the given file(test.txt) with eight lines
into a new file(new.txt) by skipping the third line from the given file
Q4 Write a python program to find the largest of the three numbers. The numbers should be
input from the terminal
To write content into an existing file in Python, you can use the open() function with the mode set
to 'a' (append) to open the file in append mode. Then, you can use the write() method to write the
desired content to the file.
In this example, we open the file named "example.txt" in append mode by passing 'a' as the second
argument to the open() function. This mode ensures that the new content is added to the existing
content of the file, rather than overwriting it.
We then use the write() method to write the desired content to the file. In this case, we write the
lines "This is some additional content." and "Hello, world!" to the file. The write() method appends
the content to the end of the file.
Finally, it is good practice to close the file using the close() method to release system resources and
ensure that the changes are saved.
After running this code, the specified content will be added to the existing file "example.txt"
without overwriting its previous content.
Q8 Discuss the following with the syntax and examples for the following in python Statements:
i) if- else statement
ii) for statement
iii) while statement
The if-else statement allows you to execute different blocks of code based on a condition. It checks
whether a condition is true or false and executes the corresponding block of code.
The for statement is used to iterate over a sequence (such as a list, tuple, or string) or other iterable
objects. It allows you to execute a block of code repeatedly for each item in the sequence.
The while statement allows you to repeatedly execute a block of code as long as a condition is true.
It is useful when you want to repeat a set of instructions until a specific condition is met.
Q9 What is file handling in Python? What are four different methods (modes) for opening a file? Write
the syntax for all the four modes.
A9 File handling in python refers to the process of working with files, which includes creating,
reading, writing and manipulating files.
The four different modes for opening a file in python is:
1. Read Mode(‘r’): Open a file for reading
2. Write Mode(‘w’): Open a file for writing. If file doesn’t exists, it creates a new file. If the
file exists, it truncates it.
3. Append Mode(‘a’): Open a file for appending. If the file doesn’t exist, it creates a new file. If
the file exists, it appends data to the end of the file.
4. Read an Write mode(‘r+’): Open a file for both reading and writing
UNIT3
Q1 Using regular expressions, write a python program to read all the email ids from the text
file and print them. Segregate those ending with @gmail.com and print them seperately.
Q2 Define a Module in python? Write a python code to find the fibonacci number series up to a
given value ‘n’. The value of ‘n’ should be an input from the terminal.
A2 A module in Python is a file containing Python definitions and statements that can be imported and
used in other Python programs. It allows you to organize code into reusable units and promotes
code reusability and modularity. A module can include functions, classes, variables, and other
Python code.
Create a new file named ‘fibonacci.py’ and add the following code:
Save the file ‘fibonacci.py’
Now,in another Python program, you can import the ‘fibonacci’ module and use the ‘fibonacci_series()’
function to find the Fibonacci series upto a given value ‘n’:
Q3 Write a python program to get a string made of the first 2 and the last 2 characters from a
given a string. If the string length is less than 2, return instead of the empty string.
Q4 Write a python program to get a string from a given string where all occurrences of its first
char have been changed to '$', except the first char itself.
Q5 Define regular expression and discuss the following functions with an example each:
i)search
ii) findall
iii) split
A5 Regular expression, often abbreviated as regex, is a sequence of characters that forms a search
pattern. It is used for matching and manipulating strings based on specific patterns or rules. In
Python, regular expressions are supported by the re module, which provides various functions for
working with regular expressions.
Search: The search() function is used to search for a specified pattern within a string. It returns a
match object if the pattern is found, otherwise, it returns None.
Findall: The findall() function returns all non-overlapping matches of a specified pattern in a
string as a list. Each match is represented as a separate element in the list.
Split: The split() function splits a string into a list of substrings based on a specified pattern. It
divides the string whenever the pattern is found and returns the resulting list.
Q6 Explain the following string functions with examples:
(i) casefold()
(ii) split()
(iii) islower()
(iv) index()
(v) capitalize()
(vi) find()
(vii) endswith()
(viii) concatenation
(ix) string format
(x) strip
casefold(): The casefold() function is used to convert a string to lowercase. It is similar to the
lower() function but handles additional special characters and Unicode characters for caseless
matching.
Split(): The split() function is used to split a string into a list of substrings based on a specified
delimiter. It divides the string whenever the delimiter is found.
islower(): The islower() function is used to check whether all characters in a string are lowercase.
It returns True if all characters are lowercase, otherwise False
Index(): The index() function is used to find the index of the first occurrence of a specified
substring within a string. It raises a ValueError if the substring is not found.
Capitalize(): The capitalize() function is used to convert the first character of a string to
uppercase and make the remaining characters lowercase.
find(): The find() function is used to find the index of the first occurrence of a specified substring
within a string. It returns the index if the substring is found, otherwise -1.
endswith(): The endswith() function is used to check whether a string ends with a specified suffix.
It returns True if the string ends with the given suffix; otherwise, it returns False.
Concatenation: String concatenation is the process of combining two or more strings together. In
Python, you can concatenate strings using the + operator or by using the str.join() method.
String format: String formatting is a way to insert dynamic values into a string. Python provides
different approaches for string formatting, including the % operator and the str.format() method.
In recent versions of Python, formatted string literals (f-strings) are also commonly used.
Strip(): The strip() function is used to remove leading and trailing whitespace (spaces, tabs,
newlines) from a string. It returns a new string with the leading and trailing whitespace removed.
Q7 Define a module in python.
A7 In Python, a module is a file that contains Python code, including functions, classes, and variables,
which can be imported and used in other Python programs. Modules provide a way to organize and
reuse code, making it easier to maintain and enhance the functionality of a program.
Q8 Define the regular expression special sequences ‘\b\ and ‘\w’ operators. Demonstrate the
working of the same with the help of an example, which should read the sentence as string
and print the object, span, string and the match using regular expression.
A8 The regular expression special sequences \b and \w are operators used to match specific patterns
in strings.
\b - Word Boundary: The \b special sequence matches the empty string at the beginning or end
of a word. It represents a word boundary.
\w - Word Character: The \w special sequence matches any alphanumeric character and
underscores. It is equivalent to the character class [a-zA-Z0-9_].
Q9 Signify the importance of Regex in python. What are the meta characters used to evaluate a
regular expression? Write a python program to validate an email adress
A1 The importance of regular expressions (regex) in Python lies in their ability to provide a powerful
and flexible tool for pattern matching and text manipulation. Regex allows you to search, extract,
and validate strings based on specific patterns, making it an invaluable tool for tasks such as data
validation, text parsing, and pattern matching.
Some of the key reasons why regex is important in Python include:
Pattern Matching: Regex allows you to define complex patterns and search for matches within
strings, enabling you to identify specific patterns of text or characters.
Data Validation: Regex provides a convenient way to validate and verify input data, such as email
addresses, phone numbers, or dates, ensuring they meet a specific pattern or format.
Text Extraction and Manipulation: Regex allows you to extract specific parts of a string or
manipulate text by replacing, removing, or rearranging specific patterns or characters.
Efficient Data Processing: Regex provides a highly efficient way to process and manipulate large
amounts of text or data, offering significant time and effort savings.
Meta characters are special characters that have special meanings in regular expressions.
They are used to define the structure and behavior of the patterns being matched. Some
commonly used meta characters in regex include:
. (Dot): Matches any single character except a newline.
* (Star): Matches zero or more occurrences of the preceding character or group.
+ (Plus): Matches one or more occurrences of the preceding character or group.
? (Question Mark): Matches zero or one occurrence of the preceding character or group.
[] (Square Brackets): Defines a character class, matches any single character within the brackets.
() (Parentheses): Defines a group, captures a portion of the matched text.
| (Pipe): Acts as a logical OR, matches either the expression before or after the pipe.
UNIT 4
Q1 Create a function called bubble and write a program using python to sort an array using
bubble sort technique
Q5 Write a python code to create a class rectangle and has attributes length and width with the
method as area and returns the area of the rectangle.
Q6 Write a python function to check whether the number entered is even or odd.
Q7 Write a python program using function that asks the college student as user to enter their
name and age. Print a message that tells the year when they would be 70 years old.
Q8 Write a python code to create a class method consisting of minimum three functions.
Q9 Create an inner function to calculate the addition in the following way:
i. Create an outer function that will accept two parameters a and b
ii. Create an inner function inside an outer function that will calculate the addition of a
and b
iii. At last, an outer function will add 5 into addition and return it.
Q10 Write a python function to read three numbers and find the largest among them.
Q11 Discuss with an example program how to create a class and its respective object in
detail.
In Python, a class is a blueprint for creating objects (instances) that share similar attributes and
behavior. It defines the structure and behavior of the objects that will be created from it. An object
is an instance of a class that represents a specific entity or concept.
In this example, we define a class named Car that represents a car object. It has attributes such as
brand, model, and year, as well as a method named start_engine to start the car's engine.
To create an object of the Car class, we use the class name followed by parentheses, similar to
calling a function. In this case, my_car is an instance (object) of the Car class.
We can access the attributes of the object using dot notation, such as my_car.brand,
my_car.model, and my_car.year. We can also call methods of the object, such as
my_car.start_engine(), which executes the code within the start_engine method.
By defining classes and creating objects, you can encapsulate data and behavior into reusable and
modular components. Objects allow you to work with instances of the class, accessing their
attributes and invoking their methods, enabling you to model and manipulate entities or concepts
in your Python programs.
Q1 Define Inheritance and discuss with an example code snippet how to perform multiple
inheritance in python