Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 27

Assistant professor Ill Semester B.C.A.

Degree Exhmination, March/April 2023


Brijesh CG (NEP) (Freshers) (2022-23 and Onwards) COMPUTER SCIENCE
Python Programming

1. Why python is an interpreted language ?


Python is an interpreted language because its source code is not directly converted into
machine code. Instead, Python code is executed line by line by an interpreter at runtime.
When you run a Python program, the interpreter translates the high-level code into a
platform-specific intermediate code that can be understood by the computer. This process
allows for more flexibility and ease of use, but it can also result in slower execution speed
compared to compiled languages.

In summary, Python is an interpreted language because it relies on an interpreter to translate


and execute its code during runtime, rather than being compiled into machine code
beforehand.
2. Explain membership operators.
Membership operators are used in programming languages to test whether a value is a
member of a sequence, such as strings, lists, or tuples. In Python, there are two membership
operators:

1. `in`: This operator checks if a specified value is present in the given sequence. It returns
`True` if the value is found in the sequence, and `False` otherwise.

Example:
```
list1 = [1, 2, 3, 4, 5]
result = 3 in list1
print(result) # Output: True

string1 = "Hello, world!"


result = 'world' in string1
print(result) # Output: True
```

2. `not in`: This operator checks if a specified value is NOT present in the given sequence. It
returns `True` if the value is not found in the sequence, and `False` otherwise.

Example:
```
list1 = [1, 2, 3, 4, 5]
result = 6 not in list1
print(result) # Output: True

string1 = "Hello, world!"


result = 'Python' not in string1
print(result) # Output: True
```
Assistant professor Ill Semester B.C.A. Degree Exhmination, March/April 2023
Brijesh CG (NEP) (Freshers) (2022-23 and Onwards) COMPUTER SCIENCE
Python Programming
These membership operators are useful for checking the presence or absence of values in
various data structures and can be used in conditional statements to control the flow of a
program based on whether specific values are found within sequences.
3. What is a tuple ? Give an example.
A tuple is an immutable, ordered collection of elements in Python. It is
similar to a list, but its elements cannot be modified once created. Tuples are commonly used for
storing related data, especially when the data should not be changed throughout the program. They
are represented by elements enclosed in parentheses `()` and separated by commas.

Here's an example of a tuple:

```python

coordinates = (12.5, 45.7, 86.3)

```

In this example, `coordinates` is a tuple containing three floating-point values representing 3D


coordinates (x, y, z). Since tuples are immutable, you cannot change the values of the coordinates
once they are assigned. To access elements within the tuple, you can use indexing, just like with lists:

```python

x = coordinates[0] # Access the first element of the tuple (12.5)

y = coordinates[1] # Access the second element of the tuple (45.7)

z = coordinates[2] # Access the third element of the tuple (86.3)

```

Keep in mind that attempting to modify a tuple's elements will result in a TypeError, as they are
immutable:

```python

coordinates[0] = 20.0 # This will raise a TypeError

```

4. Define encapsulation and inheritance.


Encapsulation and inheritance are two fundamental concepts in object-
oriented programming (OOP) that are supported in Python:

1. Encapsulation: Encapsulation refers to the bundling of data and the methods that operate
on that data within a single unit, typically a class. It is a way to restrict access to certain parts
of an object and protect them from being accidentally modified or accessed from outside the
class. In Python, encapsulation is achieved by using private and protected access modifiers
for class attributes and methods.

- Private attributes and methods are denoted by double underscores before their names
(e.g., `__private_attribute`). They can only be accessed within the class itself.
Assistant professor Ill Semester B.C.A. Degree Exhmination, March/April 2023
Brijesh CG (NEP) (Freshers) (2022-23 and Onwards) COMPUTER SCIENCE
Python Programming
- Protected attributes and methods are denoted by a single underscore before their names
(e.g., `_protected_attribute`). They can be accessed by the class itself and its subclasses.

Example of encapsulation in Python:

```python
class BankAccount:
def __init__(self, account_number, balance):
self._account_number = account_number
self.__balance = balance

def deposit(self, amount):


self.__balance += amount

def withdraw(self, amount):


if amount <= self.__balance:
self.__balance -= amount
else:
print("Insufficient funds")

def get_balance(self):
return self.__balance
```

2. Inheritance: Inheritance is a mechanism that allows one class to inherit the attributes and
methods of another class, enabling code reuse and the creation of more specialized classes
based on existing ones. The class that is being inherited from is called the "base class" or
"parent class," while the class that inherits from the base class is called the "derived class" or
"child class."

In Python, inheritance is achieved by passing the parent class as a parameter to the child
class during its definition.

Example of inheritance in Python:

```python
class Animal:
def __init__(self, name):
self.name = name

def speak(self):
print("The animal makes a sound")

class Dog(Animal):
def speak(self):
print("The dog barks")
Assistant professor Ill Semester B.C.A. Degree Exhmination, March/April 2023
Brijesh CG (NEP) (Freshers) (2022-23 and Onwards) COMPUTER SCIENCE
Python Programming
class Cat(Animal):
def speak(self):
print("The cat meows")

dog = Dog("Buddy")
cat = Cat("Whiskers")

dog.speak() # Output: The dog barks


cat.speak() # Output: The cat meows
```
In this example, `Dog` and `Cat` classes inherit from the `Animal` class. Both child classes
override the `speak` method to provide their specific implementation.

5. What is constructor method in python ?


In Python, a constructor method is a special method used to initialize objects
when they are created. The constructor method is defined using the `__init__` method name
within a class. It is automatically called when a new instance of the class is created, allowing
you to set default values for attributes or perform any necessary setup for the object.

The `__init__` method typically takes the `self` parameter, which is a reference to the
instance of the class, along with any additional parameters needed to initialize the object.

Here's an example of a constructor method in Python:

```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def display_info(self):
print(f"Name: {self.name}, Age: {self.age}")

# Creating a new instance of the Person class


person1 = Person("Alice", 30)

# Calling the display_info method on the person1 object


person1.display_info() # Output: Name: Alice, Age: 30
```

In this example, the `Person` class has a constructor method `__init__` which takes two
parameters, `name` and `age`, in addition to the `self` parameter. When a new instance of
the `Person` class is created, the `__init__` method is called with the provided arguments,
initializing the `name` and `age` attributes for the object.
Assistant professor Ill Semester B.C.A. Degree Exhmination, March/April 2023
Brijesh CG (NEP) (Freshers) (2022-23 and Onwards) COMPUTER SCIENCE
Python Programming

6. What is a file ? Mention the type of files.


In the context of Python, a file refers to a container for storing data on a computer
or storage device, which can be read or written to by a Python program. Python can handle
various types of files, including text files, binary files, and specialized file formats, as
mentioned in the previous answer.

When working with files in Python, you typically use the built-in `open()` function to open a
file and create a file object. This file object then allows you to read from or write to the file
using various methods. The file object has a mode associated with it that determines how it
can be accessed:

1. Text files: When working with text files in Python, you usually open them in text mode by
specifying the mode as `'r'` (read), `'w'` (write), or `'a'` (append). In text mode, Python reads
or writes the file's content as a sequence of strings.

Example:
```python
# Opening a text file for reading
with open('example.txt', 'r') as file:
content = file.read()
print(content)
```

2. Binary files: To work with binary files in Python, you open them in binary mode by
specifying the mode as `'rb'` (read binary), `'wb'` (write binary), or `'ab'` (append binary). In
binary mode, Python reads or writes the file's content as a sequence of bytes.

Example:
```python
# Opening an image file (binary) for reading
with open('example.jpg', 'rb') as file:
content = file.read()
```

3. Specialized file formats: Python can also work with various specialized file formats using
specific libraries or modules. Some of these libraries include `csv` for CSV files, `json` for
JSON files, `pickle` for serialized Python objects, `xlrd`/`xlwt` or `openpyxl` for Excel files, and
`Pillow` for image manipulation.

Example (reading a CSV file using the `csv` module):


```python
import csv

with open('example.csv', 'r') as file:


csv_reader = csv.reader(file)
for row in csv_reader:
Assistant professor Ill Semester B.C.A. Degree Exhmination, March/April 2023
Brijesh CG (NEP) (Freshers) (2022-23 and Onwards) COMPUTER SCIENCE
Python Programming
print(row)
```
When working with files in Python, always remember to close the file after performing the
necessary operations. Using the `with` statement, as shown in the examples, ensures that
the file is automatically closed when the block of code is exited.

PART _ B
Answer any 4 questions. Each question carries 5 marks :

7. Explain the features of python.


Python is a popular, high-level, and versatile programming language known for its readability,
simplicity, and vast library support. Some of the key features of Python include:

1. Easy to learn: Python has a simple and easy-to-understand syntax that emphasizes readability and
reduces the cost of program maintenance. It is designed to be accessible for beginners and
experienced programmers alike.

2. High-level language: Python is a high-level programming language, meaning it abstracts the


complexities of lower-level languages (like memory management) and allows developers to focus on
the problem they want to solve rather than getting lost in the details.

3. Cross-platform compatibility: Python can run on various operating systems like Windows, Linux,
and macOS, making it a platform-independent language.

4. Open-source: Python is open-source, which means its source code is freely available and can be
modified, distributed, and used for both commercial and non-commercial purposes.

5. Extensive libraries: Python has a rich set of libraries, also known as the Python Standard Library,
which includes modules for various tasks like web development, databases, data analysis, regular
expressions, and more. Additionally, there are numerous third-party libraries available for use.

6. Object-oriented programming: Python supports object-oriented programming (OOP) concepts,


allowing developers to create classes, objects, and inheritance for efficient and reusable code.

7. Dynamically-typed: In Python, the data type of a variable is determined at runtime, making it a


dynamically-typed language. This provides flexibility when writing code, as developers don't have to
explicitly declare the data type of a variable.

8. Strong community support: Python has a large and active community of developers who
contribute to its development, create and maintain libraries, and provide support through forums
and online resources.

9. Integrated Development Environment (IDE) support: Python is supported by various IDEs like
PyCharm, Visual Studio Code, Jupyter Notebook, and Spyder, which offer features like code
completion, debugging, and syntax highlighting to make coding more efficient and enjoyable.
Assistant professor Ill Semester B.C.A. Degree Exhmination, March/April 2023
Brijesh CG (NEP) (Freshers) (2022-23 and Onwards) COMPUTER SCIENCE
Python Programming

10. Wide range of applications: Python is used in diverse domains such as web development (using
frameworks like Django and Flask), data analysis and visualization (with libraries like Pandas, NumPy,
and Matplotlib), machine learning and artificial intelligence (with TensorFlow, PyTorch, and Scikit-
learn), automation, and more.

8. . What is string slicing in python ? Explain with examples.


String slicing in Python is the process of extracting a portion (substring) from the
original string by specifying the starting and ending indices. It is a powerful feature that allows you to
access and manipulate parts of a string easily.

In Python, strings are indexed, with each character assigned a unique index based on its position.
Indexing starts from 0 for the first character and increases by 1 for each subsequent character. You
can also use negative indices, which count from the end of the string, with -1 being the last character,
-2 being the second last character, and so on.

To slice a string, you can use the slice notation with square brackets and a colon ([:]) to specify the
start and end indices. The syntax is as follows:

`string[start:end]`

Here, `start` is the index of the first character you want to include in the slice, and `end` is the index
of the first character you want to exclude from the slice. If you don't provide a start or end index, it
defaults to the beginning and end of the string, respectively.

Here are some examples:

```python

text = "Hello, World!"

# Extract a substring from index 0 to 4 (excluding 5)

substring = text[0:5]

print(substring) # Output: Hello

# Extract a substring from index 7 to the end

substring = text[7:]

print(substring) # Output: World!

# Extract a substring from the beginning to index 4 (excluding 5)


Assistant professor Ill Semester B.C.A. Degree Exhmination, March/April 2023
Brijesh CG (NEP) (Freshers) (2022-23 and Onwards) COMPUTER SCIENCE
Python Programming
substring = text[:5]

print(substring) # Output: Hello

# Extract a substring using negative indices

substring = text[-6:-1]

print(substring) # Output: World

# Extract a substring with a step value (every 2nd character)

substring = text[0:13:2]

print(substring) # Output: Hlo ol!

```

Note that the end index is exclusive, meaning it is not included in the resulting substring. Also, if the
start index is greater than or equal to the end index, the result will be an empty string.

9. What is the difference between lists and tuples ? Explain with


examples.
Lists and tuples are both data structures in Python used to store collections
of items. They have some similarities, but there are key differences between them:

1. Mutability: The primary difference between lists and tuples is that lists are mutable,
whereas tuples are immutable. This means that you can modify the contents of a list, but
you cannot change the contents of a tuple once it is created.

2. Syntax: Lists are created using square brackets `[]`, while tuples are created using
parentheses `()` or simply by separating items with commas.

Here are some examples to illustrate the differences between lists and tuples:

```python
# Creating a list and a tuple
my_list = [1, 2, 3, 4]
my_tuple = (1, 2, 3, 4)

# Accessing elements (same for both lists and tuples)


print(my_list[1]) # Output: 2
print(my_tuple[1]) # Output: 2

# Modifying elements (only possible with lists)


my_list[1] = 5
Assistant professor Ill Semester B.C.A. Degree Exhmination, March/April 2023
Brijesh CG (NEP) (Freshers) (2022-23 and Onwards) COMPUTER SCIENCE
Python Programming
print(my_list) # Output: [1, 5, 3, 4]

# The following line would cause an error, as tuples are immutable


# my_tuple[1] = 5

# Appending elements (only possible with lists)


my_list.append(6)
print(my_list) # Output: [1, 5, 3, 4, 6]

# The following line would cause an error, as tuples are immutable


# my_tuple.append(6)

# Concatenation (same for both lists and tuples)


new_list = my_list + [7, 8]
print(new_list) # Output: [1, 5, 3, 4, 6, 7, 8]

new_tuple = my_tuple + (7, 8)


print(new_tuple) # Output: (1, 2, 3, 4, 7, 8)
```

In general, you should use lists when you need a collection that can change over time, and
tuples when you have a fixed collection of items that should not be altered. Tuples can be
more memory-efficient and faster than lists in certain situations, especially when working
with large datasets.

10.Explain how you create classes and objects in python.


In Python, classes are created using the `class` keyword followed by the class
name and a colon. The class can contain attributes (variables) and methods (functions) that
define the properties and behaviors of the objects created from the class. Objects are
instances of the class, which means they have the same properties and behaviors defined in
the class.

Here's a step-by-step explanation of how to create classes and objects in Python:

1. Define a class: Start by defining a class using the `class` keyword, followed by the class
name and a colon. The class name should typically follow the PascalCase naming convention
(capitalizing the first letter of each word).

```python
class MyClass:
```

2. Add attributes and methods: Inside the class, you can define attributes and methods. To
define an attribute, you can use the `__init__` method (constructor), which is a special
method that gets called when an object is created. To define a method, you write a function
within the class using the `def` keyword.
Assistant professor Ill Semester B.C.A. Degree Exhmination, March/April 2023
Brijesh CG (NEP) (Freshers) (2022-23 and Onwards) COMPUTER SCIENCE
Python Programming
```python
class MyClass:
# Constructor method
def __init__(self, attribute1, attribute2):
self.attribute1 = attribute1
self.attribute2 = attribute2

# A custom method
def my_method(self):
return f"Attribute 1: {self.attribute1}, Attribute 2: {self.attribute2}"
```

3. Create an object: To create an object (instance) of the class, you call the class name
followed by parentheses, passing any required arguments that the constructor method
(`__init__`) expects.

```python
my_object = MyClass("Value 1", "Value 2")
```

4. Access attributes and methods: Once you have created an object, you can access its
attributes and methods using the dot (.) notation.

```python
# Access attributes
print(my_object.attribute1) # Output: Value 1
print(my_object.attribute2) # Output: Value 2

# Access methods
result = my_object.my_method()
print(result) # Output: Attribute 1: Value 1, Attribute 2: Value 2
```
Here's a complete example:
```python
class Dog:
def __init__(self, name, breed, age):
self.name = name
self.breed = breed
self.age = age

def bark(self):
return f"{self.name} says Woof!"

# Create a Dog object


my_dog = Dog("Buddy", "Golden Retriever", 3)

# Access attributes
Assistant professor Ill Semester B.C.A. Degree Exhmination, March/April 2023
Brijesh CG (NEP) (Freshers) (2022-23 and Onwards) COMPUTER SCIENCE
Python Programming
print(my_dog.name) # Output: Buddy
print(my_dog.breed) # Output: Golden Retriever
print(my_dog.age) # Output: 3

# Access methods
print(my_dog.bark()) # Output: Buddy says Woof!
```

11. Explain different file modes in python.


In Python, when working with files, you need to specify a file mode that
determines how the file should be opened and what operations can be performed on it. The
following are the most common file modes in Python:

1. `'r'` (Read mode): This mode is used when you want to read data from an existing file. It is
the default mode if no mode is specified. If the file does not exist, an error is raised.
```python
file = open('example.txt', 'r')
```

2. `'w'` (Write mode): This mode is used when you want to create a new file and write data
to it, or overwrite the content of an existing file. If the file does not exist, it will be created. If
the file exists, its content will be overwritten.
```python
file = open('example.txt', 'w')
```

3. `'a'` (Append mode): This mode is used when you want to open an existing file and append
data to it, preserving the existing content. If the file does not exist, it will be created.
```python
file = open('example.txt', 'a')
```

4. `'x'` (Exclusive creation mode): This mode is used when you want to create a new file, but
only if it does not already exist. If the file exists, an error is raised.
```python
file = open('example.txt', 'x')
```

5. `'b'` (Binary mode): This mode is used when you want to work with binary files, such as
images or executables. It can be combined with other modes (e.g., `'rb'`, `'wb'`, `'ab'`, `'xb'`)
to read, write, append, or exclusively create binary files.
```python
file = open('example.bin', 'rb')
```
Assistant professor Ill Semester B.C.A. Degree Exhmination, March/April 2023
Brijesh CG (NEP) (Freshers) (2022-23 and Onwards) COMPUTER SCIENCE
Python Programming
6. `'t'` (Text mode): This mode is used when you want to work with text files. It is the default
mode if no mode is specified, and can be combined with other modes (e.g., `'rt'`, `'wt'`, `'at'`,
`'xt'`) to explicitly indicate that a file should be treated as a text file.
```python
file = open('example.txt', 'rt')
```

7. `'+'` (Updating mode): This mode is used when you want to both read and write data
to/from a file. It can be combined with other modes (e.g., `'r+'`, `'w+'`, `'a+'`, `'x+'`, `'rb+'`,
`'wb+'`, `'ab+'`, `'xb+'`) to enable simultaneous reading and writing.
```python
file = open('example.txt', 'r+')
```

Remember to always close the file after you are done with it to free up system resources. You
can use the `close()` method or the `with` statement (which automatically closes the file
when the block is exited).

```python
# Using close() method
file = open('example.txt', 'r')
content = file.read()
file.close()

# Using with statement


with open('example.txt', 'r') as file:
content = file.read()
```

12.What is data visualization ? List the libraries that are used for data
visualization in python.
Data visualization is the graphical representation of data and information using
various visual elements such as charts, graphs, maps, and plots. It helps to make complex data
more understandable, accessible, and actionable by presenting it in a visual format. Data
visualization enables decision-makers, researchers, and analysts to identify patterns, trends, and
correlations within the data, which might be challenging to uncover through text or numerical
formats alone.

Python offers several libraries for data visualization, which provide powerful tools and techniques
to create informative and appealing visualizations. Some of the popular data visualization
libraries in Python include:

1. Matplotlib: A widely used library for creating static, interactive, and animated visualizations in
Python. It provides a low-level interface for drawing attractive and informative statistical
graphics. Matplotlib can be used to create various types of plots, such as line plots, scatter plots,
bar plots, histograms, and more.
Assistant professor Ill Semester B.C.A. Degree Exhmination, March/April 2023
Brijesh CG (NEP) (Freshers) (2022-23 and Onwards) COMPUTER SCIENCE
Python Programming
2. Seaborn: A statistical data visualization library built on top of Matplotlib, providing a high-level
interface for drawing attractive and informative statistical graphics. Seaborn comes with several
built-in themes and color palettes to make it easy to create aesthetically pleasing visualizations. It
is particularly useful for visualizing complex datasets with multiple variables.

3. Plotly: A library for creating interactive and web-based visualizations. Plotly supports various
types of charts, such as line charts, scatter plots, bar charts, pie charts, bubble charts, and more.
It also provides support for creating 3D plots and animations. Plotly visualizations can be easily
embedded in web applications or dashboards.

4. Bokeh: A library for creating interactive, web-based visualizations similar to Plotly, but with a
focus on providing more control over the look and feel of the visualizations. Bokeh allows users
to create custom interactive plots and dashboards using Python without requiring any
knowledge of JavaScript.

5. ggplot: A library based on the Grammar of Graphics, which is a popular data visualization
concept in R programming. ggplot provides a high-level interface for creating complex and
aesthetically pleasing visualizations using a layered approach.

6. Altair: A declarative statistical visualization library for Python, which allows users to create
visualizations by specifying what they want the visualization to encode rather than focusing on
the details of how it should be rendered. Altair produces interactive visualizations using a simple
syntax.

7. Pandas: While Pandas is primarily a data manipulation library, it also provides basic plotting
capabilities built on top of Matplotlib. These plotting functions are convenient for quick
visualizations of data stored in Pandas DataFrames.

These libraries offer various features and cater to different use cases, so the choice of library
depends on the specific requirements and preferences of the user.

PART _ C
Answer any 4 questions. Each question carries 8 marks.
a) What are tokens ? Explain various tokens in python with examples.
Tokens are the basic building blocks of a programming language. They represent
the smallest individual units of code that have a specific meaning in the language. In Python, the
Assistant professor Ill Semester B.C.A. Degree Exhmination, March/April 2023
Brijesh CG (NEP) (Freshers) (2022-23 and Onwards) COMPUTER SCIENCE
Python Programming
source code is first broken down into a sequence of tokens during the lexical analysis phase before
being parsed and executed.

There are several types of tokens in Python, including:

1. Keywords: Keywords are reserved words in Python that have a special meaning and cannot be
used as variable names, function names, or identifiers. Examples of keywords include `if`, `else`,
`while`, `for`, `def`, `class`, `import`, `True`, and `False`.

```python

if x > 0:

print("Positive")

```

2. Identifiers: Identifiers are user-defined names used to represent variables, functions, classes, and
other objects in Python. Identifiers must start with a letter (a-z, A-Z) or an underscore (_) and can be
followed by any combination of letters, sdigits, or underscores.

```python

my_variable = 10

def my_function():

pass

```

3. Literals: Literals represent constant values in the program. There are several types of literals in
Python, such as:

- Numeric literals: Include integers (e.g., `42`, `-7`), floating-point numbers (e.g., `3.14`, `-0.5`), and
complex numbers (e.g., `1+2j`, `3-4j`).

- String literals: Include single-line strings (e.g., `'hello'`, `"world"`), and multi-line strings (e.g.,
`'''hello\nworld'''`, `"""hello\nworld"""`).

- Boolean literals: Include the two boolean values `True` and `False`.

- None literal: Represents the absence of a value and is denoted by the keyword `None`.

```python

integer_literal = 42

float_literal = 3.14

string_literal = "hello, world!"

boolean_literal = True
Assistant professor Ill Semester B.C.A. Degree Exhmination, March/April 2023
Brijesh CG (NEP) (Freshers) (2022-23 and Onwards) COMPUTER SCIENCE
Python Programming
none_literal = None

```

4. Operators: Operators are symbols that perform specific operations on operands (variables or
values). Python has various types of operators, such as:

- Arithmetic operators (e.g., `+`, `-`, `*`, `/`, `%`, `**`, `//`)

- Comparison operators (e.g., `==`, `!=`, `<`, `>`, `<=`, `>=`)

- Logical operators (e.g., `and`, `or`, `not`)

- Bitwise operators (e.g., `&`, `|`, `^`, `~`, `<<`, `>>`)

- Assignment operators (e.g., `=`, `+=`, `-=`, `*=`, `/=`, `%=`)

```python

result = 2 + 3 * 4

is_equal = 5 == 5

not_true = not True

bitwise_and = 3 & 5

x=1

x += 2

```

5. Delimiters: Delimiters are special characters used to separate and organize code elements, such as
parentheses, brackets, braces, and various punctuation marks. Examples of delimiters include `()`,
`[]`, `{}`, `,`, `:`, `;`, and `.`.

```python

my_list = [1, 2, 3]

my_dict = {'a': 1, 'b': 2}

def my_function(x, y):

return x * y

result = my_function(2, 3)

```
Assistant professor Ill Semester B.C.A. Degree Exhmination, March/April 2023
Brijesh CG (NEP) (Freshers) (2022-23 and Onwards) COMPUTER SCIENCE
Python Programming
6. Comments: Comments are used to provide explanations or notes about the code. They are not
executed by the Python interpreter and are ignored during the execution. Single-line comments start
with the hash symbol (`#`), while multi-line comments are enclosed within triple single quotes (`'''`).

```python

# This is a single-line comment

'''

b. ) Explain core data types in python.


Python has several core built-in data types that are used to define the structure and
behavior of data in a program. The core data types in Python include:

1. Numbers:
- Integers (`int`): These represent whole numbers, both positive and negative, without a
decimal point (e.g., `42`, `-7`).
- Floating-point numbers (`float`): These represent real numbers with a decimal point (e.g.,
`3.14`, `-0.5`).
- Complex numbers (`complex`): These represent numbers with a real part and an
imaginary part (e.g., `1+2j`, `3-4j`).

```python
integer_value = 42
float_value = 3.14
complex_value = 1+2j
```

2. Booleans (`bool`): These represent the truth values `True` and `False`, mainly used in
conditional expressions and logical operations.

```python
is_true = True
is_false = False
Assistant professor Ill Semester B.C.A. Degree Exhmination, March/April 2023
Brijesh CG (NEP) (Freshers) (2022-23 and Onwards) COMPUTER SCIENCE
Python Programming
```

3. Strings (`str`): These represent sequences of characters and can be created using single
quotes (`'hello'`), double quotes (`"world"`), or triple quotes for multi-line strings (`'''Hello\
nWorld'''`, `"""Hello\nWorld"""`).

```python
string_value = "Hello, world!"
multi_line_string = '''This is a
multi-line string'''
```

4. Lists (`list`): These represent ordered, mutable collections of items. Lists can contain items
of different data types, including other lists. Lists are created using square brackets `[]` and
can be indexed and modified.

```python
my_list = [1, 2, 3, "hello", [4, 5]]
my_list[2] = "changed"
```

5. Tuples (`tuple`): These represent ordered, immutable collections of items. Like lists, tuples
can contain items of different data types. Tuples are created using parentheses `()` or just by
separating items with commas.

```python
my_tuple = (1, 2, 3, "hello", (4, 5))
# The following line would cause an error, as tuples are immutable
# my_tuple[2] = "changed"
```
Assistant professor Ill Semester B.C.A. Degree Exhmination, March/April 2023
Brijesh CG (NEP) (Freshers) (2022-23 and Onwards) COMPUTER SCIENCE
Python Programming
6. Sets (`set`): These represent unordered collections of unique items. Sets do not allow
duplicate values and are useful for performing operations like union, intersection, and
difference. Sets are created using curly braces `{}` or the `set()` function.

```python
my_set = {1, 2, 3, 4, 4}
# Output: {1, 2, 3, 4} (duplicate values are removed)
```
7. Dictionaries (`dict`): These represent unordered collections of key-value pairs. Dictionaries
allow you to store and access data using unique keys instead of indices. Dictionaries are
created using curly braces `{}` with key-value pairs separated by colons.
```python
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 42}
```
These core data types are the building blocks for creating more complex data structures and
handling various types of data in Python programs.

14. . What are functions ? How to define and call a function in python ?
Explain with example.
Functions in programming are reusable pieces of code that perform a specific
task. They help in organizing and structuring the code, making it more readable and
maintainable. Functions also enable code reusability and modularity.

In Python, functions are defined using the `def` keyword, followed by the function name,
parentheses `()` containing any input parameters, and a colon `:`. The function body is
indented, and the `return` statement is used to return a value from the function.

Here's an example of defining and calling a function in Python:

```python
# Defining a function
def add_numbers(a, b):
Assistant professor Ill Semester B.C.A. Degree Exhmination, March/April 2023
Brijesh CG (NEP) (Freshers) (2022-23 and Onwards) COMPUTER SCIENCE
Python Programming
result = a + b
return result

# Calling the function


sum_result = add_numbers(5, 3)
print(sum_result) # Output: 8
```

Explanation:

1. We define a function called `add_numbers` with two input parameters `a` and `b`.
2. Inside the function, we add the two input parameters and store the result in the variable
`result`.
3. The `return` statement is used to return the value of `result`.
4. To call the function, we pass two arguments (5 and 3) to `add_numbers`, and the returned
value is stored in the variable `sum_result`.
5. Finally, we print the value of `sum_result`, which is 8 in this case.

15.a. ) Explain if... elif... else control flow statement with example.
The `if... elif... else` control flow statement in Python is used to make
decisions based on certain conditions. It allows the program to execute a specific block of
code only when a given condition is met.
Here's an explanation of each part:
1. `if`: This checks whether a condition is true. If it is, the code within the indented block
following the `if` statement is executed.
2. `elif`: Short for "else if", this is used to check additional conditions if the previous
conditions were not met. You can have multiple `elif` blocks to check for different conditions
in sequence.
3. `else`: This block of code is executed if none of the previous conditions are met.
Here's an example demonstrating the `if... elif... else` control flow statement:

```python
Assistant professor Ill Semester B.C.A. Degree Exhmination, March/April 2023
Brijesh CG (NEP) (Freshers) (2022-23 and Onwards) COMPUTER SCIENCE
Python Programming
age = 18

if age < 13:


print("You are a child.")
elif age >= 13 and age < 18:
print("You are a teenager.")
else:
print("You are an adult.")
```

Explanation:

1. We define a variable `age` with the value 18.


2. The `if` statement checks if `age` is less than 13. If this condition is true, it would print
"You are a child." In this case, the condition is false, so the code moves to the next block.
3. The `elif` statement checks if `age` is greater than or equal to 13 and less than 18. If this
condition is true, it would print "You are a teenager." In this case, the condition is also false,
so the code moves to the next block.
4. Since none of the previous conditions are met, the `else` block is executed, and it prints
"You are an adult."

15.b.Write a program to perform indexing and slicing in lists.


In Python, indexing and slicing are used to access and manipulate elements
within a list. Indexing refers to accessing a single element using its index, while slicing is
about accessing a range of elements.
Here's a program that demonstrates indexing and slicing in lists:
```python
# Defining a list
fruits = ["apple", "banana", "cherry", "orange", "grape"]

# Indexing: Accessing single elements using their index


first_fruit = fruits[0] # apple
Assistant professor Ill Semester B.C.A. Degree Exhmination, March/April 2023
Brijesh CG (NEP) (Freshers) (2022-23 and Onwards) COMPUTER SCIENCE
Python Programming
second_fruit = fruits[1] # banana
last_fruit = fruits[-1] # grape

print("First fruit:", first_fruit)


print("Second fruit:", second_fruit)
print("Last fruit:", last_fruit)

# Slicing: Accessing a range of elements


first_three_fruits = fruits[0:3] # ["apple", "banana", "cherry"]
middle_fruits = fruits[1:4] # ["banana", "cherry", "orange"]
all_fruits = fruits[:] # ["apple", "banana", "cherry", "orange", "grape"]

print("First three fruits:", first_three_fruits)


print("Middle fruits:", middle_fruits)
print("All fruits:", all_fruits)
```

Explanation:

1. We define a list called `fruits` containing five elements.


2. We access individual elements using indexing, storing the first, second, and last fruit in
separate variables.
3. We print the accessed elements using indexing.
4. We access ranges of elements using slicing, storing the first three fruits, middle fruits, and
all fruits in separate variables.
5. We print the accessed elements using slicing.
Assistant professor Ill Semester B.C.A. Degree Exhmination, March/April 2023
Brijesh CG (NEP) (Freshers) (2022-23 and Onwards) COMPUTER SCIENCE
Python Programming

16. How do you perform reading and writing files in python ?


Explain with an example program.
In Python, you can perform reading and writing operations on files using built-
in functions such as `open()`, `read()`, `write()`, and `close()`. The `with` statement can also
be used to manage file resources efficiently.

Here's an example program demonstrating reading and writing files in Python:

```python
# Writing to a file
file_name = "example.txt"

# Using 'with' statement to manage resources


with open(file_name, "w") as file:
file.write("Hello, World!\n")
file.write("This is an example program for reading and writing files in Python.")

# Reading from a file


with open(file_name, "r") as file:
content = file.read()
print("File content:")
print(content)

# Reading lines from a file


with open(file_name, "r") as file:
lines = file.readlines()
print("File lines:")
for line in lines:
Assistant professor Ill Semester B.C.A. Degree Exhmination, March/April 2023
Brijesh CG (NEP) (Freshers) (2022-23 and Onwards) COMPUTER SCIENCE
Python Programming
print(line.strip())
```

Explanation:

1. We define a variable `file_name` containing the name of the file we want to create and
read from.

2. To write to a file, we use the `open()` function with the mode set to `'w'` (write mode).
The `with` statement ensures that the file is properly closed after the operation.

3. Inside the `with` block, we use the `write()` function to write two lines of text to the file.

4. To read the entire content of a file, we use the `open()` function with the mode set to `'r'`
(read mode) and the `read()` function to read the file content. We then print the file content.

5. To read the file line by line, we use the `readlines()` function, which returns a list of lines.
We then iterate over the lines and print them, using the `strip()` function to remove leading
and trailing whitespace (e.g., the newline character).

17. Define pickling in python. Explain serialization and


deserialization.
Pickling in Python is the process of converting a Python object into a byte
stream that can be easily stored, transmitted, or used later. This process is also known as
serialization. The reverse process, i.e., converting a byte stream back into a Python object, is
called unpickling or deserialization.

Serialization is the process of converting a data structure or object into a format that can be
stored (e.g., in a file or memory buffer) or transmitted (e.g., over a network connection).
This is useful when you want to save the state of an object or transfer it between different
programs or systems.
Assistant professor Ill Semester B.C.A. Degree Exhmination, March/April 2023
Brijesh CG (NEP) (Freshers) (2022-23 and Onwards) COMPUTER SCIENCE
Python Programming
Deserialization is the process of reconstructing a data structure or object from its serialized
format. It allows you to restore the state of an object or reconstruct it in another program or
environment.

Python provides the `pickle` module to perform pickling and unpickling of Python objects.
Here's an example:

```python
import pickle

# Example Python object (a dictionary)


data = {
"name": "John",
"age": 30,
"city": "New York"
}

# Serialization (pickling)
serialized_data = pickle.dumps(data)

# Deserialization (unpickling)
deserialized_data = pickle.loads(serialized_data)

print("Original data:", data)


print("Serialized data:", serialized_data)
print("Deserialized data:", deserialized_data)
```

Explanation:
Assistant professor Ill Semester B.C.A. Degree Exhmination, March/April 2023
Brijesh CG (NEP) (Freshers) (2022-23 and Onwards) COMPUTER SCIENCE
Python Programming
1. We import the `pickle` module.
2. We create a dictionary called `data` containing some example information.
3. We use the `pickle.dumps()` function to serialize (pickle) the dictionary into a byte stream.
4. We use the `pickle.loads()` function to deserialize (unpickle) the byte stream back into a
Python object (a dictionary).
5. Finally, we print the original data, serialized data, and deserialized data to demonstrate
the process.

18. a) Explain matplotlib.


Matplotlib is a widely-used Python library for creating static, interactive, and animated
visualizations in Python. It provides a high-level interface for drawing attractive and informative
statistical graphics. Matplotlib is particularly useful for data analysis, as it allows you to visualize
patterns, trends, and relationships in your data.

Some key features of Matplotlib include:

1. Versatility: Matplotlib supports a wide variety of plots, including line plots, scatter plots, bar plots,
histograms, 3D plots, and more.

2. Customizability: You can customize almost every aspect of a plot, such as colors, line styles,
markers, labels, legends, and axis limits.

3. Integration: Matplotlib can be used in Jupyter notebooks, IPython consoles, and various integrated
development environments (IDEs) like PyCharm, Visual Studio Code, and Spyder

4. Export formats: Matplotlib supports many output formats, including PNG, PDF, SVG, and more,
allowing you to save your visualizations in the desired format.

Here's an example of creating a simple line plot using Matplotlib:

```python

import matplotlib.pyplot as plt

# Sample data

x = [0, 1, 2, 3, 4, 5]

y = [0, 1, 4, 9, 16, 25]

# Create a line plot

plt.plot(x, y)

# Add labels and title


Assistant professor Ill Semester B.C.A. Degree Exhmination, March/April 2023
Brijesh CG (NEP) (Freshers) (2022-23 and Onwards) COMPUTER SCIENCE
Python Programming
plt.xlabel("X-axis")

plt.ylabel("Y-axis")

plt.title("Simple Line Plot")

# Display the plot

plt.show()

```

Explanation:

1. We import the `pyplot` module from the Matplotlib library and use the common alias `plt`.

2. We create two lists, `x` and `y`, containing sample data for our plot.

3. We use the `plt.plot()` function to create a line plot with the given data.

4. We add labels for the X-axis and Y-axis and a title for the plot using `plt.xlabel()`, `plt.ylabel()`, and
`plt.title()`, respectively.

5. Finally, we use the `plt.show()` function to display the plot.

b) Write Python code to create a simple plot using matolotlib


module.
Here's a Python code example that demonstrates how to create a simple line plot using the
Matplotlib library:
```python
import matplotlib.pyplot as plt

# Sample data
x = [0, 1, 2, 3, 4, 5]
y = [0, 1, 4, 9, 16, 25]

# Create a line plot


plt.plot(x, y)

# Add labels and title


plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Simple Line Plot")

# Display the plot


plt.show()
```
Assistant professor Ill Semester B.C.A. Degree Exhmination, March/April 2023
Brijesh CG (NEP) (Freshers) (2022-23 and Onwards) COMPUTER SCIENCE
Python Programming

Explanation:

1. We import the `pyplot` module from the Matplotlib library and use the common alias `plt`.
2. We create two lists, `x` and `y`, containing sample data for our plot.
3. We use the `plt.plot()` function to create a line plot with the given data.
4. We add labels for the X-axis and Y-axis and a title for the plot using `plt.xlabel()`, `plt.ylabel()`, and
`plt.title()`, respectively.
5. Finally, we use the `plt.show()` function to display the plot.

You might also like