Ill Semester B.C.A.
Degree Exhmination, March/April 2023
(NEP) (Freshers) (2022-23 and Onwards)
COMPUTER SCIENCE
Python Programming
PART - A
Answer any 4 questions. Each question carries 2 marks:
1. Why is Python an interpreted language?
Python is considered an interpreted language because its code is executed line-by-line by an
interpreter, rather than being compiled into machine language before execution. This
enables dynamic execution and allows developers to run scripts without prior compilation.
2. Explain membership operators.
Membership operators are used to test whether a value is a member of a sequence, such as
a string, list, or tuple.
• in: Returns True if the value is found in the sequence.
• not in: Returns True if the value is not found in the sequence.
Example:
x = [1, 2, 3]
print(2 in x) # Output: True
print(4 not in x) # Output: True
3. What is a tuple? Give an example.
A tuple is an immutable, ordered collection of elements in Python. Once created, its
elements cannot be modified. Tuples are defined using parentheses ().
Example:
my_tuple = (1, "apple", 3.14)
print(my_tuple) # Output: (1, 'apple', 3.14)
4. Define encapsulation and inheritance.
• Encapsulation: The process of bundling data and methods into a single unit, typically
a class. It also involves restricting access to some components using access modifiers
like private (_ or __).
• Inheritance: A mechanism where one class (child) can derive properties and methods
from another class (parent), allowing code reuse and hierarchy.
5. What is a constructor method in Python?
A constructor is a special method in Python, defined as __init__(), that is automatically
called when an object of a class is created. It initializes the object's attributes.
Example:
class Person:
def __init__(self, name):
self.name = name
p = Person("Alice")
print(p.name) # Output: Alice
6. What is a file? Mention the types of files.
A file is a collection of data stored on a disk that can be accessed and manipulated using
Python. Files allow for persistent storage of information.
Types of files:
1. Text files: Store plain text, e.g., .txt.
2. Binary files: Store data in binary format, e.g., images, videos, .bin.
PART - B
Answer any 4 questions. Each question carries 5 marks :
7. Explain the features of Python.
Python is a versatile, high-level programming language with the following key features:
1. Easy to Learn and Use: Python has a simple and readable syntax, making it beginner-
friendly.
2. Interpreted: Python executes code line-by-line, allowing immediate feedback and
easier debugging.
3. Object-Oriented: Supports object-oriented programming concepts like classes,
objects, encapsulation, and inheritance.
4. Dynamically Typed: Variable types are determined at runtime, eliminating the need
for explicit declarations.
5. Extensive Libraries: Python offers a vast collection of standard libraries for various
tasks, including web development, data analysis, and machine learning.
6. Cross-Platform: Python is platform-independent and can run on Windows, macOS,
and Linux.
7. High-Level Language: Python simplifies programming tasks by abstracting hardware-
level details.
8. What is string slicing in Python? Explain with examples.
String slicing allows extracting a portion of a string using the slice operator [:].
Syntax:
string[start:end:step]
• start: Starting index (inclusive).
• end: Ending index (exclusive).
• step: Increment between characters (default is 1).
Examples:
s = "PythonProgramming"
print(s[0:6]) # Output: Python
print(s[6:]) # Output: Programming
print(s[::2]) # Output: Pto rgamn
print(s[-1:-10:-1]) # Output: gnimmargor
9. What is the difference between lists and tuples? Explain with examples.
Feature List Tuple
Definition Mutable, ordered collection Immutable, ordered collection
Syntax Defined using [ ] Defined using ( )
Mutability Can be modified Cannot be modified
Performance Slower due to mutability Faster due to immutability
Use Case When data needs modification For fixed data
Examples:
# List
my_list = [1, 2, 3]
my_list[1] = 5
print(my_list) # Output: [1, 5, 3]
# Tuple
my_tuple = (1, 2, 3)
# my_tuple[1] = 5 # Raises an error
print(my_tuple) # Output: (1, 2, 3)
10. Explain how you create classes and objects in Python.
• Class: A blueprint for creating objects. Defined using the class keyword.
• Object: An instance of a class that holds specific data and behavior.
Example:
# Define a class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound."
# Create an object
dog = Animal("Dog")
print(dog.speak()) # Output: Dog makes a sound.
11. Explain different file modes in Python.
Python provides several file modes for opening and handling files:
Mode Description
r Read mode (default). Opens a file for reading.
w Write mode. Overwrites the file if it exists, otherwise creates a new file.
a Append mode. Adds data to the end of the file.
x Exclusive creation mode. Fails if the file already exists.
r+ Read and write mode.
b Binary mode. Used for binary files (e.g., images).
t Text mode (default). Used for text files.
Example:
with open("example.txt", "w") as file:
file.write("Hello, Python!")
12. What is data visualization? List the libraries used for data visualization in Python.
Data Visualization: The process of representing data graphically to identify patterns, trends,
and insights. It helps in better understanding and communication of data.
Popular Python Libraries:
1. Matplotlib: Used for creating static, interactive, and animated visualizations.
2. Seaborn: Built on Matplotlib, it offers advanced statistical plotting.
3. Plotly: Provides interactive, web-based visualizations.
4. Pandas Visualization: Offers quick plotting directly from dataframes.
5. Bokeh: Enables interactive and web-ready visualizations.
6. Altair: Declarative statistical visualization library.
7. ggplot: Implements a grammar of graphics in Python.
PART - C
Answer any 4 questions. Each question carries 8 marks:
13. a) What are tokens? Explain various tokens in Python with examples.
Tokens are the smallest units of a Python program. They include keywords, identifiers,
literals, operators, and punctuation (delimiters).
1. Keywords: Reserved words in Python that have predefined meanings.
Example: if, else, def, while
2. if x > 0:
3. print("Positive number")
4. Identifiers: Names used to identify variables, functions, or classes.
Example: my_var, calculate_sum
5. my_var = 10
6. Literals: Constant values directly assigned in a program.
Example: Numbers, strings, True, False
7. x = 5 # Integer literal
8. y = "Hello" # String literal
9. Operators: Symbols used to perform operations.
Example: +, -, *, /, ==, and
10. result = 10 + 5
11. Punctuation/Delimiters: Symbols that structure the code.
Example: (), {}, [], :
12. def greet():
13. print("Hello!")
13. b) Explain core data types in Python.
1. Numeric Types:
o int: Integer numbers.
o float: Decimal numbers.
o complex: Complex numbers.
2. Sequence Types:
o str: Textual data.
o list: Mutable ordered collection.
o tuple: Immutable ordered collection.
3. Set Types:
o set: Unordered collection of unique elements.
4. Mapping Types:
o dict: Key-value pairs.
5. Boolean Type:
o bool: Represents True or False.
6. None Type:
o None: Represents the absence of value.
14. What are functions? How to define and call a function in Python?
Functions are reusable blocks of code that perform a specific task. Functions help in modular
programming.
Defining a Function: Use the def keyword.
Calling a Function: Use the function name followed by parentheses.
Example:
# Define a function
def greet(name):
return f"Hello, {name}!"
# Call the function
print(greet("Alice"))
Output: Hello, Alice!
15. a) Explain if... elif... else control flow statement with example.
Control flow statements direct the execution of code based on conditions.
• if: Executes if the condition is true.
• elif: Executes if the previous conditions are false and this condition is true.
• else: Executes if all previous conditions are false.
Example:
x = 10
if x > 15:
print("Greater than 15")
elif x > 5:
print("Between 6 and 15")
else:
print("5 or less")
# Output: Between 6 and 15
15. b) Write a program to perform indexing and slicing in lists.
Example Program:
# Indexing
my_list = [10, 20, 30, 40, 50]
print(my_list[2]) # Output: 30
# Slicing
print(my_list[1:4]) # Output: [20, 30, 40]
print(my_list[::-1]) # Output: [50, 40, 30, 20, 10]
16. How do you perform reading and writing files in Python?
Reading Files: Use the open() function with mode 'r'.
Writing Files: Use open() with mode 'w', 'a', or 'x'.
Example Program:
# Writing to a file
with open("example.txt", "w") as file:
file.write("Hello, Python!\n")
# Reading from a file
with open("example.txt", "r") as file:
content = file.read()
print(content) # Output: Hello, Python!
17. Define pickling in Python. Explain serialization and deserialization.
Pickling: The process of serializing (converting) Python objects into a byte stream. This
enables saving or transmitting objects.
Serialization: Converts a Python object into a format (e.g., byte stream) that can be stored
or transmitted.
Deserialization: Converts the byte stream back into a Python object.
Example:
import pickle
# Serialization
data = {"name": "Alice", "age": 25}
with open("data.pkl", "wb") as file:
pickle.dump(data, file)
# Deserialization
with open("data.pkl", "rb") as file:
loaded_data = pickle.load(file)
print(loaded_data) # Output: {'name': 'Alice', 'age': 25}
18. a) Explain Matplotlib.
Matplotlib is a Python library for creating static, animated, and interactive visualizations. It is
widely used for plotting graphs and charts.
• Key Features:
o Supports various types of plots (e.g., line, bar, scatter).
o Customizable visuals (labels, legends, colors).
o Integrates with other libraries like NumPy and Pandas.
18. b) Write Python code to create a simple plot using Matplotlib.
Example Program:
import matplotlib.pyplot as plt
# Data
x = [1, 2, 3, 4]
y = [10, 20, 25, 30]
# Plot
plt.plot(x, y, label="Line Plot", color="blue", marker="o")
# Customize
plt.title("Simple Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.legend()
# Show plot
plt.show()