Pps Solved 2019 November

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

PPS_SOLVED_2019_NOVEMBER

Q1)

a) What is a function? Explain code reuse. Explain with an example Docstring. [6]

 A function is a block of organized, reusable code that performs a specific task.

 Code reuse refers to the practice of using existing code for new purposes, rather than
rewriting it from scratch.

- Example with a Docstring:

```python

def greet(name):

"""

This function greets the person passed as an argument.

"""

print("Hello, " + name + "!")

# To access the docstring, use the __doc__ attribute

print(greet.__doc__)

```

Here, the docstring provides a description of what the function does.

b) Explain Lambda function with an example. [6]

A lambda function is a small anonymous function defined using the lambda keyword. It can take any
number of arguments but can only have one expression. They are often used when you need a
simple function for a short period of time.

Example:

``` PYTHON

# R EGULAR FUNCTION
DEF ADD ( X , Y ):

RETURN X +Y

# E QUIVALENT LAMBDA FUNCTION

ADD _ LAMBDA = LAMBDA X , Y : X + Y

PRINT ( ADD (2, 3)) # O UTPUT : 5

PRINT ( ADD _ LAMBDA (2, 3)) # O UTPUT : 5

```

c) Write a Python program using a function to find the greatest of three numbers by passing
numbers as arguments. [6]

```python

def find_greatest(num1, num2, num3):

"""

This function returns the greatest of three numbers.

"""

if num1 >= num2 and num1 >= num3:

return num1

elif num2 >= num1 and num2 >= num3:

return num2

else:

return num3

# Test the function

print(find_greatest(10, 20, 15)) # Output: 20

```

OR
Q2)

a) Differentiate between Local & Global variables. Write a Python program to demonstrate the
difference between local and global variables. [6]

 Local variables are defined within a function and can only be accessed inside that function.
 Global variables are defined outside of any function and can be accessed throughout the
program.

```python

# Global variable

global_var = 10

def function():

# Local variable

local_var = 20

print("Inside function - local_var:", local_var)

print("Inside function - global_var:", global_var)

# Accessing global variable outside the function

print("Outside function - global_var:", global_var)

# Trying to access local variable outside the function will raise an error

# print("Outside function - local_var:", local_var) # This will raise an error

# Calling the function

function()

```

b) Explain keyword arguments in Python. Write a Python program to demonstrate keyword


argument
Keyword arguments enable you to pass arguments to a function by explicitly stating the parameter
names. This allows for clearer identification of which argument corresponds to which parameter,
thereby enhancing the readability of your code.

Here's a Python program to demonstrate keyword arguments:

```python

def greet(name, message="Hello"):

print(message, name)

# Calling the function with positional arguments

greet("Alice") # Output: Hello Alice

# Calling the function with keyword arguments

greet(message="Hi", name="Bob") # Output: Hi Bob

```

c) Write a Python program using a function to find whether a number is odd or even. [6]

Here's a Python program to find whether a number is odd or even using a function:

```python

def check_odd_even(num):

if num % 2 == 0:

return "Even"

else:

return "Odd"

# Test the function

number = 7

result = check_odd_even(number)

print("The number", number, "is", result)


```

Q3) a) Explain the following string methods with examples: [6]

i) Rindex

ii) Zfill

iii) Split

- Rindex: Returns the highest index where the substring is found.

- Zfill: Pads a numeric string on the left with zeros.

- Split: Splits the string into a list of substrings.

Examples:

```python

s = "Hello, World!"

print(s.rindex('o')) # Output: 8

print("42".zfill(5)) # Output: 00042

print("hello world".split()) # Output: ['hello', 'world']

```

--------------------------------------------------------------------------------------------------------------------------------------

b) Write a Python program to display tables from 1 to 10 using formatting characters. [6]

Here's a Python program to display tables from 1 to 10 using formatting characters:

```python

for i in range(1, 11):

for j in range(1, 11):

print("{:2d} x {:2d} = {:2d}".format(i, j, i * j))

print()

```
c) What will be the output of the following statement S = “Welcome to Python”. [5]

i) print(s[1:9]) - Outputs "elcome t", slicing from index 1 to 8.

ii) print(s[:6]) - Outputs "Welcome", slicing from the beginning to index 5.

iii) print(s[4:]) - Outputs "ome to Python", slicing from index 4 to the end.

iv) print(s[1:-1]) - Outputs "elcome to Pytho", slicing from index 1 to the second last character.

v) print("Come" not in str) - Outputs True, as "Come" is not present in the string.

OR

Q4)

a) Explain the following string methods with examples: [6]

- Join: Concatenates elements of an iterable with a separator.

- Enumerate: Returns an enumerate object with index and value pairs.

- Strip: Removes leading and trailing whitespace.

Examples:

```python

# Join

my_list = ['apple', 'banana', 'cherry']

print(", ".join(my_list)) # Output: apple, banana, cherry

# Enumerate

for index, value in enumerate(my_list):

print(index, value) # Output: (0, 'apple'), (1, 'banana'), (2, 'cherry')

# Strip
print(" Hello ".strip()) # Output: Hello

```

b) Write a Python program to find whether a given character is present in a string or not. In case it
is present, print the index at which it is present. Do not use built-in string methods. [6]

Here's a Python program to achieve that:

```python

def find_character(string, char):

for index, c in enumerate(string):

if c == char:

return index

return -1

# Test the function

string = "Hello, World!"

char = "o"

index = find_character(string, char)

if index != -1:

print("Character '{}' is present at index {}".format(char, index))

else:

print("Character '{}' is not present in the string".format(char))

```

c) Write a Python program to check whether a given string starts with a specified character. [5]

Here's a Python program to achieve that:


```python

def starts_with(string, char):

if string[0] == char:

return True

else:

return False

# Test the function

string = "Hello, World!"

char = "H"

if starts_with(string, char):

print("The string starts with the character '{}'".format(char))

else:

print("The string does not start with the character '{}'".format(char))

```

--------------------------------------------------------------------------------------------------------------------------------------

Q5)

a) Define programming paradigm. List programming paradigms. Explain any one. [6]

A programming paradigm is a fundamental style or approach to programming, which provides


guidelines and techniques for designing and implementing computer programs. It dictates the
structure, organization and flow of a program.

List of programming paradigms:

1. Imperative

2. Declarative

3. Procedural

4. Functional

5. Object-oriented

Explanation of Object-oriented programming (OOP):

Object-oriented programming (OOP) is a programming paradigm that organizes software design


around objects, rather than functions and logic. Objects are instances of classes, which encapsulate
data (attributes) and behavior (methods) into a single unit. OOP promotes code reuse, modularity
and scalability by allowing inheritance, polymorphism, and encapsulation.

b) Justify the statement “Inheritance helps to make reusable code”. [6]

Inheritance is a key concept in object-oriented programming that allows a class (subclass) to inherit
properties and behavior from another class (superclass). It promotes code reuse by enabling the
subclass to inherit the attributes and methods of the superclass without needing to redefine them.

For example, consider a superclass Shape with attributes and methods common to all shapes, such
as area() and perimeter(). Now, subclasses like Circle, Rectangle, and Triangle can inherit these
attributes and methods from Shape and only need to define their unique characteristics. This
reduces redundancy and promotes efficient code maintenance.

c) Write a Python program that uses a class to store exam numbers and marks of four subjects. Use
a list to store the marks of four subjects. [6]

```python

class Exam:

def __init__(self, exam_number, marks):

self.exam_number = exam_number

self.marks = marks

# Test the class

exam_number = "E001"

marks = [85, 90, 78, 95] # Marks for four subjects

exam1 = Exam(exam_number, marks)

print("Exam Number:", exam1.exam_number)

print("Marks for Four Subjects:", exam1.marks)

```
In this program, we define a class `Exam` with attributes `exam_number` and `marks`. We create an
object `exam1` of the `Exam` class, passing exam number and marks as arguments. We use a list to
store the marks for four subjects. Finally, we print the exam number and marks for four subjects.

OR

Q6)

a) Explain the following Terms: [6]

i) Data Abstraction & Encapsulation:

- Data Abstraction: Data abstraction is the process of hiding the implementation details and showing
only the essential features of an object to the outside world. It helps in reducing programming
complexity and focusing on relevant details.

- Encapsulation: Encapsulation is the bundling of data (attributes) and methods (functions) that
operate on the data into a single unit (class). It prevents direct access to the data from outside the
class and ensures data integrity by controlling access through methods.

ii) Polymorphism:

Polymorphism is the ability of an object to take on multiple forms or behave differently in different
contexts. It allows objects of different classes to be treated as objects of a common superclass. There
are two types of polymorphism: compile-time polymorphism (method overloading) and runtime
polymorphism (method overriding).

b) With the help of an example, explain the significance of the `__init__()` method. [6]

The `__init__()` method is a special method in Python classes that is called automatically when a
new object of the class is created. It is used to initialize the attributes of the object with initial values.
The significance of the `__init__()` method lies in its ability to ensure that objects are properly
initialized when they are created, providing a convenient way to set initial values for object
attributes.

Example:
```python

class Car:

def __init__(self, name, cost):

self.name = name

self.cost = cost

# Creating objects of the Car class

car1 = Car("Toyota", 25000)

car2 = Car("Honda", 30000)

# Displaying information

print("Car 1 - Name:", car1.name, ", Cost:", car1.cost)

print("Car 2 - Name:", car2.name, ", Cost:", car2.cost)

```

This program defines a class `Car` with an `__init__` method to initialize the attributes `name` and
`cost`. It also has a method `display_info` to display the information of a car object. Two car objects,
`car1` and `car2`, are created using this class, and their information is displayed using the
`display_info` method.

c) Write a Python program to create a class Car with two attributes name & cost. Create two
objects and display information. [6]

```python

class Car:

def __init__(self, name, cost):

self.name = name

self.cost = cost

def display_info(self):

print(f"Car Name: {self.name}")

print(f"Car Cost: ${self.cost}")


# Creating objects of Car class

car1 = Car("Toyota Camry", 25000)

car2 = Car("Honda Civic", 22000)

# Displaying information of car1

print("Information of Car 1:")

car1.display_info()

print()

# Displaying information of car2

print("Information of Car 2:")

car2.display_info()

```

This program defines a class `Car` with an `__init__` method to initialize the attributes `name` and
`cost`. It also has a method `display_info` to display the information of a car object. Two car objects,
`car1` and `car2`, are created using this class, and their information is displayed using the
`display_info` method.

Q7

a) Write a Python program that reads data from one file and writes into another file line by line. [6]

```python

# Open the input file in read mode

with open('input.txt', 'r') as input_file:

# Open the output file in write mode

with open('output.txt', 'w') as output_file:

# Read each line from the input file

for line in input_file:

# Write each line to the output file

output_file.write(line)
```

Explanation:

- This code uses nested `with` statements to open two files simultaneously: 'input.txt' for reading
and 'output.txt' for writing.

- The `with` statement ensures that the files are properly closed after their respective suites finish
executing, even if an exception occurs.

- Inside the loop, each line from the input file is read and then written to the output file, effectively
copying the contents of the input file to the output file.

b) What is a directory? List any four directory methods and explain any two of them. [6]

Explanation:

- A directory is a container used to store files and other directories. It organizes files in a hierarchical
structure.

- Four directory methods in Python's `os` module are:

1. `os.mkdir(path)`: Creates a new directory at the specified `path`.

2. `os.rmdir(path)`: Removes the directory at the specified `path`.

3. `os.listdir(path)`: Returns a list of names of entries in the directory specified by `path`.

4. `os.chdir(path)`: Changes the current working directory to the specified `path`.

- Explanation of `os.listdir(path)`: This method returns a list of names of entries in the directory
specified by the `path` argument. It does not include the special entries '.' (current directory) and '..'
(parent directory). This method is useful for listing the contents of a directory.

- Explanation of `os.chdir(path)`: This method changes the current working directory to the specified
`path`. It allows you to navigate between different directories in the file system. This method is
helpful when you need to work with files and directories located in different locations.

c) Why do we need files? Explain relative and absolute paths in files. [5]

Explanation:
- Files are necessary for storing and organizing data persistently on a computer's storage devices.
They allow data to be saved, retrieved, and manipulated by programs. Files are essential for tasks
such as data storage, data processing, and communication between programs.

- Relative Path: A relative path specifies the location of a file or directory relative to the current
working directory. It does not include the root directory. For example, `my_folder/my_file.txt`.

- Absolute Path: An absolute path specifies the complete location of a file or directory from the root
directory of the file system. It includes the root directory. For example,
`/home/user/my_folder/my_file.txt`.

OR

Q8)

a) Write a Python program that counts the number of tabs and newline characters in a file. [6]

```python

# Initialize variables to count tabs and newlines

tab_count = 0

newline_count = 0

# Open the file in read mode

with open('filename.txt', 'r') as file:

# Iterate through each line in the file

for line in file:

# Count tabs and newlines in each line

tab_count += line.count('\t')

newline_count += line.count('\n')

# Print the counts

print("Number of tabs:", tab_count)

print("Number of newlines:", newline_count)

```
b) Write a Python program to display the current directory, create a directory, and remove the
created directory. [6]

```python

import os

# Display current directory

current_dir = os.getcwd()

print("Current directory:", current_dir)

# Create a new directory

new_dir = 'new_directory'

os.mkdir(new_dir)

print("New directory '{}' created.".format(new_dir))

# Remove the created directory

os.rmdir(new_dir)

print("Directory '{}' removed.".format(new_dir))

```

c) Differentiate between text and binary files. Explain any 4 access modes used in Python. [5]

- Text Files: Text files are human-readable files that store data as a sequence of characters. They
contain textual data encoded in formats like ASCII or UTF-8. Examples include .txt, .csv, and .html
files.

- Binary Files: Binary files contain data in a format that is not human-readable. They store data in a
sequence of bytes and can represent any type of data, including images, videos, executables, etc.

Access Modes in Python:


1. 'r' (Read): Opens a file for reading. The file must exist.

2. 'w' (Write): Opens a file for writing. If the file exists, it will be truncated. If it does not exist, a new
file will be created.

3. 'a' (Append): Opens a file for appending. New data will be written at the end of the file. If the file
does not exist, it will be created.

4. 'b' (Binary): Opens a file in binary mode. This mode is used when working with binary files to
prevent any newline character translation.

You might also like