Model Paper-1
Introduction to Python Programming
ANSWERS
1) a) Define Python programming. List and explain any five features of python.
Python is a high-level, general-purpose, interpreted programming language.
Key features of python Python is a high level programming language.
Easy to learn and use: It is much easier to learn than any other programming languages like C, C++, Java, Ruby
and Swift. It has few keywords and thus very less syntactical constraints. Thus the language is very developer friendly
and easy to pick up.
Free and Open Source → Python is a open sourced language. Thus it is publicly available to download
and use and even anyone can contribute to its development.
Easy to maintain → Python code base is very easy to maintain.
Object Oriented Language → Python is an Object Oriented language. Thus is provides all the key
features of an Object Oriented Programming language like Encapsulation, Inheritance, Abstraction and
Polymorphism. Nevertheless, Python also offers a scope to write code as in a Procedural Programming
Language.
Extensibility → Python is very extensible. We can write and integrate some Python code into C and
C++ and hence compile it using its irrespective compilers.
Portability → Python provides high portability. Thus same piece of code can be run in all platforms of
Windows, UNIX and Linux.
Large Standard Library → Python has a large set of large standard library which possess some inbuilt
rich set of functions such that we need not to write code for every single thing.
Dynamically Typed Language → Python is a dynamically typed language. Here, we need not to
declare the type of the variable like int, float and char. It is also auto-set as we assign a value to the variable.
Garbage Collection → Python also supports auto garbage collection .
1 .b) With proper syntax and examples explain any three type conversion
functions in python.
There can be two types of Type Casting in Python –
Implicit Type Casting
Explicit Type Casting
Implicit Type Conversion
In implicit type conversion, Python converts data types automatically, without any user
involvement. This happens when we perform operations between different data types. For
example:
a=5 # an integer
b = 3.14 # a floating point number
c=a+b # the sum of a and b
print(c) # Output: 8.14
print(type(c)) # Output: <class 'float'>
Explicit Type Conversion:
In explicit type conversion, Python requires user involvement to convert one data type to another.
This is done using type casting functions such as:
int(): converts a float or a string to an integer
float(): converts an integer or a string to a float
str(): converts an integer or a float to a string
# Type Casting int to float
a=5 # an integer
b = float(a) # convert a to a float
print(b) # Output: 5.0
print(type(b)) # Output: <class 'float' >
# Type Casting float to int
x = 3.14 # a float
y = int(x) # convert x to an integer
print(y) # Output: 3
print(type(y)) # Output: <class 'int'>
# Type Casting int to string
m = 42 # an integer
n = str(m) # convert m to a string
print(n) # Output: '42'
print(type(n)) # Output: <class 'str'>
1.c) Write a python program to predict greatest among three numbers.
Input three numbers from users.
z
2.a) Define Identifiers. Explain rules to define an identifier in
python.
Ans . Variable is a name that is used to refer to memory location. Python
variable is also known as an identifier and used to hold value.
Rules to define Variables are:
1. The first character of the variable must be an alphabet or underscore ( _ ).
2. All the characters except the first character may be an alphabet of lower-case(a-z), upper-case
(A-Z), underscore, or digit (0-9).
3. Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &, *).
4. Identifier name must not be similar to any keyword defined in the language.
5. Identifier names are case sensitive; for example, my name, and MyName is not the same.
Declaring Variable:
Python does not bind us to declare a variable before using it in the application. It allows us to
create a variable at the required time.
The equal (=) operator is used to assign value to a variable.
Example: . a = 50
2. b) List and explain different arithmetic operators supported by Python.
Discuss about their precedence and associativity .
Python supports several arithmetic operators that can be used to perform
mathematical operations on numeric data types such as integers and floats. Here's a
list of the arithmetic operators supported by Python:
1. Addition +: Adds two operands and returns their sum.
2. Subtraction -: Subtracts the second operand from the first and returns their difference.
3. Multiplication *: Multiplies two operands and returns their product.
4. Division /: Divides the first operand by the second and returns their quotient as a float.
5. Floor Division //: Divides the first operand by the second and returns their quotient as an integer,
rounding down to the nearest whole number.
6. Modulus %: Divides the first operand by the second and returns the remainder.
7. Exponentiation **: Raises the first operand to the power of the second operand and returns the
result.
Precedence and Associativity:
Operators in Python have a specific precedence and associativity, which determine the order in
which they are evaluated when multiple operators appear in an expression.
Precedence refers to the priority of an operator over other operators, with higher precedence
operators evaluated first. For example, multiplication and division have a higher precedence than
addition and subtraction. If an expression contains operators of equal precedence, then the order
of evaluation is determined by their associativity.
Associativity refers to the direction in which an operator is evaluated when it has the same
precedence as other operators. In Python, most operators have left-to-right associativity, which
means that expressions are evaluated from left to right.
Here's the precedence and associativity of the arithmetic operators in Pyth
2. c) Develop a python program to predict given number is prime or not
prime.
3.a )Explain different types of parameter passing is used in Python
functions? Justify your answer with sample programs.
1. Positional Parameters: In this type of parameter passing, the arguments
are passed to the function based on their position. These are the most
commonly used parameters in Python functions. The position of the
arguments should match the order of the parameters defined in the
function.
def sum(a, b):
return a + b
result = sum(3, 5)
print(result) # output: 8
2. Keyword Parameters: In this type of parameter passing, the
arguments are passed to the function using their parameter
names. This way the order of the arguments doesn’t matter,
but the parameter name has to match.
def sum(a, b):
return a + b
result = sum(b=5, a=3)
print(result) # output: 8
3. Default Parameters: In this type of parameter passing, a default value is
set for a parameter in the function definition. If no value is passed for that
parameter during the function call, then the default value is used.
def greet(a , b=10):
print(a +b)
greet(12) # output: 22
Write a python program to demonstrate string traversing using
for loop to print length of the string and number of lowercase,
uppercase, digits, spaces present in the input string.
3.c)Justify strings are immutable with proper example.
Strings are immutable in Python, which means once a string is created, its contents
cannot be modified. Any operation that appears to modify a string actually creates a
new string object with the desired changes instead of modifying the original string
in place.
Ex 1)my_string = "hello"
my_string[0] = "H"
If we run the above code, it will raise a TypeError
Instead, we can create a new string object with the desired changes:
Ex 2 )my_string = "hello"
new_string = "H" + my_string[1:]
print(new_string)
#output = Hello
Hence , we can tell that strings are immutable but new string can be
created
4.a) Define String in Python. Explain different ways of accessing values in
the string with examples.
We can access the characters in a string in three ways.
Indexing: One way is to treat strings as a list and use index values. For example,
Negative Indexing: Similar to a list, Python allows negative
indexing for its strings. For example,
Slicing: Access a range of characters in a string by using the
slicing operator colon :. For example,
4.b )Distinguish between local and global variables with examples.
Local Variables:
A local variable is a variable that is defined within a function or a block of code. A
local variable can only be accessed within the function or block of code where it is
defined. Once the function or block of code execution is completed, the local
variable is destroyed. A local variable cannot be accessed outside of its scope .
def my_function():
x = 10 # x is a local variable
print("Value of x inside the function:", x)
my_function()
# Output: Value of x inside the function: 10
Global Variables:
A global variable is a variable that is defined outside of a function or a block of code.
A global variable can be accessed anywhere in the program, including inside a
function. If a local variable has the same name as a global variable, the local variable
takes precedence and shadows the global variable within its scope
x = 10 # x is a global variable
def my_function():
print("Value of x inside the function:", x)
my_function()
# Output: Value of x inside the function: 10
4.c)Develop a program using functions to check whether two
numbers are equal or not?
5.a)Describe Lists in python. With a proper example discuss working of
following list built-in functions.
i.count() ii. sorted() iii. remove() iv. insert() v. len()
A list can contain elements of different data types, such as integers, floats, strings, or
even other lists.
Here is an example of how to create a list
my_list = [1, 2, 3, 'hello', 4.5]
Count(): The count() function is used to count the number of
occurrences of a particular element in a list.
my_list = [1, 2, 3, 2, 4, 2, 5]
# Count the number of occurrences of 2 in the list
count = my_list.count(2)
print("Number of occurrences of 2 in the list:", count)
Number of occurrences of 2 in the list: 3
sorted(): The sorted() function is used to sort a list in ascending
order. It does not modify the original list but returns a new sorted list.
my_list = [3, 5, 1, 4, 2]
# Sort the list in ascending order
sorted_list = sorted(my_list)
print("Sorted list:", sorted_list)
Sorted list: [1, 2, 3, 4, 5]
iii. remove(): The remove() function is used to remove the first
occurrence of a specified element from a list. If the element is not found
in the list, it raises a ValueError.
Here's an example:
my_list = [1, 2, 3, 2, 4, 2, 5] # Remove the first occurrence of 2 from the list
my_list.remove(2)
print("Updated list:", my_list) Updated list: [1, 3, 2, 4, 2, 5]
5.b)Write a python program to search for a given key element using
linear search technique using functions.
Explain the concept of list cloning with example?
To create a new copy of the list, we need to perform list cloning. List cloning creates a completely new
copy of the original list, so any changes made to the cloned list will not affect the original list and vice
versa.
There are two ways to clone a list in Python:
1. Using the copy() method:
# Example 1: Using the copy() method
original_list = [1, 2, 3, 4, 5]
cloned_list = original_list.copy()
# Update the cloned list
cloned_list[2] = 6
# Print both lists
print("Original list:", original_list)
print("Cloned list:", cloned_list)
output-
Original list: [1, 2, 3, 4, 5]
Cloned list: [1, 2, 6, 4, 5]
7b.)Writea python program that print histogram of frequency of characters
occurring in a message using dictionaries.
message = input("Enter a message: ")
# Create an empty dictionary to store the frequency of each
character
freq = {}
# Iterate over each character in the message
for char in message:
# If the character is already in the dictionary, increment its
count
if char in freq:
freq[char] += 1
# Otherwise, add the character to the dictionary with a count of
1
else:
freq[char] = 1
# Print the histogram
print("Histogram of character frequency:")
for char in freq:
print(char, "-" * freq[char])
output of code
7.a)Develop a program that inputs a text file. The program should
print all of the unique words in the file in alphabetical order.
With the help of an example, explain how do you raise custom exception?
Object-Oriented Programming (OOP) is a programming paradigm that uses the
concept of "objects" to represent and manipulate data. The important features of OOP
include:
1. Encapsulation: the ability to bundle data and methods together into a single unit, called
a class, and restrict access to the data from outside the class.
2. Inheritance: the ability to create new classes by deriving them from existing classes,
which inherit the attributes and methods of the parent class.
3. Polymorphism: the ability to use a single interface to represent multiple types of
objects.
4. Abstraction: the ability to simplify complex systems by breaking them down into
smaller, simpler components.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
ullas = person(Ullas , 18)
Ramesh = person(ramesh , 25)
Ullas.greet()
Ramesh.greet()
output
Hello, my name is Ullas and I am 18years old
Hello, my name is ramesh and I am 25 years old
9.b)Explain different types of inheritance supported by Python with
simple code snippet
single inheritance: a subclass inherits from a single parent class.
2. Multiple inheritance: a subclass inherits from multiple parent classes.
3. Multilevel inheritance: a subclass inherits from a parent class, which in
turn inherits from another parent class.
4. Hierarchical inheritance: multiple subclasses inherit from a
single parent class.
10.a)Explain about the different types of Exceptions in Python.
In Python, exceptions are errors that occur during program execution. They can be
handled using try-except blocks to gracefully handle errors and continue executing
the program. Python provides many built-in exceptions for handling different types
of errors. Some of the commonly used built-in exceptions are:
1. TypeError: Raised when an operation or function is applied to an object of
inappropriate type.
2. ValueError: Raised when a built-in operation or function receives an argument that
has the right type but an inappropriate value.
3. NameError: Raised when a local or global name is not found.
4. IndexError: Raised when an index is out of range.
5. KeyError: Raised when a key is not found in a dictionary.
6. AttributeError: Raised when an attribute reference or assignment fails.
7. ZeroDivisionError: Raised when the second operand of a division or modulo
operation is zero.
8. FileNotFoundError: Raised when a file or directory is requested but doesn't exist.
In addition to the built-in exceptions, Python also allows users to create their own
custom exceptions by creating a new class that inherits from the Exception class.
Custom exceptions can be useful for handling specific errors in a program.
Handling exceptions in Python is a powerful way to write robust code that can
handle errors gracefully and continue executing even in the face of unexpected
input or conditions
10.b)Develop a program that defines a class named rectangle that
takes the parameters length and breadth. The class rectangle should
also contain a method for computing its perimeter
With suitable examples discuss the difference between function overloading and [07 Marks] CO5 L2
function overriding concepts in Python.
Function Overloading: Function overloading refers to defining
multiple functions with the same name in a single class, but with different
parameters. The function to be called is determined at compile time
based on the number, order, and types of the arguments passed to the
function.
class MyClass:
def func(self, x, y=0):
print("x =", x)
print("y =", y)
obj = MyClass()
# Call func with one argument
obj.func(10)
# Call func with two arguments
obj.func(10, 20)
Function Overriding: Function overriding refers to defining a function
in a subclass that has the same name as a function in the superclass. The
function in the subclass overrides the function in the superclass, providing
a new implementation for the same method name.
class Animal:
def make_sound(self):
print("Generic animal sound")
class Dog(Animal):
def make_sound(self):
print("Bark")
class Cat(Animal):
def make_sound(self):
print("Meow")
# Create instances of the classes
my_animal = Animal()
my_dog = Dog()
my_cat = Cat()
# Call the make_sound method for each instance
my_animal.make_sound() # outputs "Generic animal sound"
my_dog.make_sound() # outputs "Bark"
my_cat.make_sound() # outputs "Meow"
8.a)Why does python require file handling? Explain opening files
in python with all modes?
In Python, file handling is done through the built-in open() function, which takes a file name and a
mode as arguments. The mode parameter specifies the type of access you want to the file, whether
it's read-only, write-only, or both.
Here are the different modes that can be used while opening files in Python:
'r' - read mode (default)
opens the file for reading
raises an error if the file does not exist
'w' - write mode
opens the file for writing
creates a new file if it doesn't exist or overwrites the existing file
'x' - exclusive mode
creates a new file, but raises an error if the file already exists
'a' - append mode
opens the file for writing
appends new content to the end of the file, rather than overwriting it
'b' - binary mode
opens the file in binary mode
used for non-text files like images, audio, and video
't' - text mode (default)
opens the file in text mode
used for text files like .txt, .csv, etc.
'+' - read and write mode
opens the file for reading and writing
Here is an example of opening a file in Python in write mode:
Similarly we can write syntax for different modes of opening