PPS May - Jun - 2022 Complete Paper Solution
PPS May - Jun - 2022 Complete Paper Solution
These points should help you structure and write your answers
effectively during the exam. Good luck!
[Link]. TOTAL
E 1
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 1
i) a) f_name()
ii) c) .py
iii) b) chr
iv) b) r
v) b) upper
vi) a) _init_()
viii) b) def
x) d) [Link]()
[Link]. TOTAL
E 2
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 2
a) Function and function Definition:
- a function is a block of reusable code that performs a specific task.
- It helps in organizing code, promoting reusability, and improving readability.
- To define a function, you use the ‘def’ keyword followed by the function name,
parentheses, and a colon.
- The function body is indented below the function definition.
- syntax of function definition - def function_name() :
example of a simple function that adds two numbers and returns the result:
def add_numbers(num1, num2):
sum = num1 + num2
return sum
Function Call:
- After defining a function, you can call or invoke it to execute the code within the
function body.
- To call a function, you simply write the function name followed by parentheses
and provide any required arguments or parameters within the parentheses.
- In the above example, ‘add_numbers(5, 3)’ is the function call. It passes the
arguments
[Link]. TOTAL
E 3
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 2
the arguments ‘5’ and ‘3’ to the ‘add_numbers’ function.
- The function executes the code inside its body, performs the addition operation,
and returns the sum.
- The returned value, ‘8’, is then assigned to the ‘result’ variable.
Finally, we print the ‘result’, which print appropriate output.
Complete program :
def add_numbers(num1, num2):
sum = num1 + num2
return sum
result = add_numbers(5, 3)
print(result)
Output :
8
b) lambda Function:
- A lambda function is an anonymous function because it does not have a name.
It is defined using the ‘lambda’ keyword followed by the function's arguments and
a colon.
- Lambda functions are typically concise and written in a single line.
They are suitable for situations where a small function is required for a specific
purpose.
Syntax:
- The syntax of a lambda function is -
‘lambda arguments: expression’.
Where The arguments represent input parameters to the function, the
expression represents the single-line computation/ operation to be performed.
[Link]. TOTAL
E 4
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 2
- Lambda functions can take any number of arguments, including zero or multiple
arguments.
- The arguments are specified after the ‘lambda’ keyword and before the colon,
similar to regular function definitions.
- Lambda functions are limited to a single expression, which means they can execute
only one line of code.
- This expression is evaluated and returned as the result of the lambda function.
- Lambda functions provide convenient way to define simple functions, especially
when a named function is not required or for use with higher-order functions that
expect function arguments.
code explanation :
- In the above example, we define a lambda function named ‘multiply’ that takes
two arguments, ‘x’ and ‘y’.
- The lambda function's body consists of a single expression, ‘x * y’, which represents
the multiplication of ‘x’ and ‘y’.We then call the lambda function by passing
arguments ‘5’ and ‘3’ as ‘multiply(5, 3)’.
- The lambda function is invoked, performs the multiplication operation, and returns
the result, which is ‘15’.
- Finally, we print the result, which displays ‘15’ as the output.
Output :
15
[Link]. TOTAL
E 5
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 2
c) five key points for good Python programming practices.
4. Handle Exceptions:
Use try-except blocks to gracefully handle expected errors and exceptions.
- Exception handling prevents program crashes and enables proper error recovery.
प्र.क्र./Q. No.
Q. 3
a) i) Required Arguments:
- Required arguments are the basic type of function arguments that are mandatory
to provide when calling a function.
- These arguments are defined in the function definition with specific names, and
their values must be provided in the same order when calling the function.
code explanation :
- In the above example, the ‘greet’ function has two required arguments:
- ‘name’ and ‘age’. When calling the function ‘greet("Alice", 25)’, we provide values
for both arguments in the correct order.
- The function then prints a greeting and the age of the person.
Output :
Hello Bob !
You are 30 years old.
प्र.क्र./Q. No.
Q. 3
- Instead, they are specified with the corresponding parameter name followed by a
colon and the value.
code explanation :
- In this example, the function greet expects two keyword arguments: name and
age.
- When calling the function, we use the parameter names (name and age) followed
by a colon and the corresponding values ("Bob" and 30).
- The output displays the greeting message and the provided age.
Output:
Hello Bob !
You are 30 years old.
Additional information :
- required arguments are the basic arguments that must be provided in a specific
order, while keyword arguments are identified by their parameter names and can be
provided in any order.
- Both types of arguments serve different purposes and contribute to the flexibility
and readability of function calls in Python.
[Link]. TOTAL
E 8
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 3
b) - local and global variables are used to store and access data within different scopes.
- The scope refers to the region of the code where a particular variable is visible
and accessible.
1. Local Variables:
- Local variables are defined within a specific block or function and are only
accessible within that block or function.
- They have a limited scope, and their existence is restricted to the block in which
they are defined.
Example:
def my_function():
x = 10 # Local variable
print("Inside the function:", x)
my_function()
# print("Outside the function:", x)
# This would raise an error
code explanation :
- In the above example, the variable ‘x’ is defined inside the ‘my_function()’
function.
- It is a local variable because it is accessible only within that function.
- When the function is called, the value of ‘x’ is printed correctly.
- However, if we try to access ‘x’ outside the function, it would raise an error
because the variable is not defined in the global scope.
Output:
Inside the function: 102.
[Link]. TOTAL
E 9
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 3
Global Variables:
- Global variables are defined outside any function or block and can be accessed
from any part of the code.
- They have a global scope, making them accessible throughout the program.
Example:
y = 20
# Global variable
def my_function():
print("Inside the function:", y)
my_function()
print("Outside the function:", y)
Code explanation :
- In the above example, the variable ‘y’ is defined outside the function, making it
a global variable.
- It can be accessed from both the function and the code outside the function.
- When the function is called, the value of ‘y’ is printed correctly, and the same -
value is accessible outside the function as well.
Output:
Inside the function: 20
Outside the function: 20
Additional information :
- if you modify a global variable within a function, you need to explicitly specify
that you want to use the global variable by using the ‘global’ keyword.
- Otherwise, Python will create a new local variable within the function's scope.
[Link]. TOTAL
E 10
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 3
c) python program to swap two number using function :
def swap_numbers(a, b):
temp = a
a = b
b = temp
return a, b
# Example usage
num1 = 5
num2 = 10
print("Before swapping: num1 =", num1, "num2 =", num2)
num1, num2 = swap_numbers(num1, num2)
print("After swapping: num1 =", num1, "num2 =", num2)
code explanation :
- We define the ‘swap_numbers()’ function with parameters ‘a’ and ‘b’.Inside the
function, we swap the values of ‘a’ and ‘b’ using a temporary variable and return
the swapped values of ‘a’ and ‘b’.
- We define the initial values of the numbers to be swapped (‘num1’ and ‘num2’).
- print the values of ‘num1’ and ‘num2’ before swapping.
- We call the ‘swap_numbers()’ function, passing ‘num1’ and ‘num2’ as arguments.
- We use multiple assignment to receive the swapped values back into ‘num1’ and
‘num2’ and print the values of ‘num1’ and ‘num2’ after swapping.
- By following these steps, we successfully swap the values of ‘num1’ and ‘num2’
using the ‘swap_numbers()’ function.
- By executing this program, you'll see that the values of ‘num1’ and ‘num2’ are
successfully swapped using the ‘swap_numbers’ function.
Output:
Before swapping: num1 = 5 num2 = 10
After swapping: num1 = 10 num2 = 5
[Link]. TOTAL
E 11
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 4
a) String Operations with suitable example :
i) Concatenation:
- Concatenation is the operation of combining two or more strings into a single
string.
- It is performed using the ‘+’ operator.
Example:
str1 = "Hello"
str2 = "World"
concatenated = str1 + ", " + str2 + "!"
print(concatenated)
Code explanation :
- In the above example, the strings ‘str1’ and ‘str2’ are concatenated using the ‘+’
operator, along with a comma and an exclamation mark.
- The result is stored in the ‘concatenated’ variable and printed.
Output:
Hello, World!
ii) Appending:
- Appending is the operation of adding one string to the end of another string.
- It can be done using the ‘+=‘ operator or the ‘[Link]()’ method.
प्र.क्र./Q. No.
Q. 4
code explanation :
- In the above example, the string ‘str2’ is appended to the end of ‘str1’ using the
‘+=‘ operator. The updated value of ‘str1’ is then printed.
Output:
Hello World
Example:
str1 = "Python "
repeated = str1 * 3
print(repeated)
Code explanation :
- In the above example, the string ‘str1’ is repeated three times using the ‘*’
operator, and the result is stored in the ‘repeated’ variable.
- The value is then printed.
Output:
Python Python Python
Indexing:
- Indexing allows us to access individual characters in a string by their position.
[Link]. TOTAL
E 13
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 4
- Each character in a string has an index, starting from 0 for the first character.
- We can use square brackets ‘[]’ along with the index number to access a specific
character.
Example:
string = "Hello"
print(string[0])
# Accessing the first characterprint(string[3])
# Accessing the fourth character
code explanation :
- In the above example, we have a string ‘"Hello"‘. Using indexing, we access the
first character ‘"H"‘ by using ‘string[0]’ and the fourth character ‘"l"‘ by using
‘string[3]’.
Output:
Hl
Slicing:
- Slicing allows us to extract a portion of a string by specifying a range of indices.
- It is done using the colon ‘:’ operator inside the square brackets ‘[]’.
- The syntax for slicing is-
‘string[start:end:step]’,
where ‘start’ is the starting index, ‘end’ is the ending index (exclusive), and
‘step’ is the increment value (optional).
Example:
string = "Python Programming"
print(string[0:6]) # Slicing from index 0 to 5
print(string[7:]) # Slicing from index 7 to the end
print(string[:6]) # Slicing from the start to index 5
[Link]. TOTAL
E 14
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 4
print(string[:6]) # Slicing from the start to index 5
print(string[::2]) # Slicing with a step of 2
Code explanation :
In the above example, we slice the string ‘"Python Programming"‘ to extract different
portions:
- ‘string[0:6]’ retrieves characters from index 0 to 5 (inclusive).
- ‘string[7:]’ extracts characters from index 7 to the end of the string.
- ‘string[:6]’ retrieves characters from the start of the string to index 5 (inclusive).
- ‘string[::2]’ extracts characters with a step of 2, meaning every second character
is included.
Output:
Python
Programming
Python
Pto rgamn
c) python program to count the number of characters and words in the given
string:
# Counting characters
num_chars = len(s)
# Counting words
words = [Link]()
num_words = len(words)
[Link]. TOTAL
E 15
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 4
# Printing the results
print("Number of characters:", num_chars)
print("Number of words:", num_words)
code explanation :
- In this program, we start with the given string ‘s’, which is "Welcome to the
world of python programming".
- To count the number of characters, we use the ‘len()’ function on the string ‘s’
and assign the result to the variable ‘num_chars’.
- To count the number of words, we split the string into a list of words using the
‘split()’ method.
- The resulting list is stored in the variable ‘words’.
- We then use the ‘len()’ function on ‘words’ to get the count of words, which is
assigned to the variable ‘num_words’.
- Finally, we print the counts of characters and words using ‘print()’ statements.
- By running this program, you'll get the output displaying the number of characters
and words in the given string.
Output:
Number of characters: 40
Number of words: 7
[Link]. TOTAL
E 16
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 5
a) String Methods with suitable example :
i) strip():
- The ‘strip()’ method in Python is used to remove leading and trailing whitespace
characters from a string.
- It returns a new string with the whitespace removed.
Example:
text = " Hello, World!
"stripped_text = [Link]()
print(stripped_text)
Code explantion :
- In this example, the ‘strip()’ method is called on the ‘text’ string, which contains
leading and trailing whitespace.
- The ‘strip()’ method removes the whitespace characters and returns a new string,
‘stripped_text’, without the leading and trailing spaces.
- The output shows the string without the extra whitespace.
Output:
Hello, World!
ii) index():
- The ‘index()’ method is used to find the index of a substring within a string.
- It returns the index of the first occurrence of the substring if found, or it raises
a ‘ValueError’ if the substring is not found.
Example:
message = "Hello, World!"
index = [Link]("o")
[Link]. TOTAL
E 17
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 5
print(index)
Code explanation :
- In this example, the ‘index()’ method is called on the ‘message’ string to find
the index of the first occurrence of the substring ‘"o"‘.
- The method returns the index , which is the position of the first ‘"o"‘ character
in the string.
Output:
4
iii) isdigit():
- The ‘isdigit()’ method is used to check whether a string contains only digits
(numeric characters).
- It returns ‘True’ if all characters in the string are digits, and ‘False’ otherwise.
Example:
number1 = "12345"
number2 = "Hello123"
print([Link]()) # True
print([Link]()) # False
code explanation :
- In this example, the ‘isdigit()’ method is called on two strings, ‘number1’ and
‘number2’.
- The method checks if the strings contain only digits.
- The first ‘isdigit()’ call returns ‘True’ because all characters in ‘number1’ are
digits.
- The second ‘isdigit()’ call returns ‘False’ because ‘number2’ contains non-digit
characters.
Output:
[Link]. TOTAL
E 18
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 5
Output:
True
False
b) String:
- A string is a sequence of characters enclosed in single quotes (‘'‘) or double
quotes (‘"‘).
- It is an immutable data type in Python, which means it cannot be modified after
it is created.
- Strings support various operations, including concatenation (combining two or more
strings), slicing (extracting a portion of a string), and searching for substrings.
- Each character in a string can be accessed using its index.
- Indexing starts at 0, where the first character is at index 0, the second at index
1, and so on.
- Python offers string interpolation techniques to embed variables or expressions
within strings, enhancing readability and flexibility.
- In other word strings are essential data types in Python used to represent and
manipulate textual information.
- They offer various operations, indexing capabilities, and methods that enable
powerful string processing and manipulation.
Example:
# Iterating Strings
text = "Hello, World!"
for char in text:
print(char)
code explanation :
- In this example, the string ‘text’ contains the phrase "Hello, World!".Using a ‘for’
loop, we iterate over each character in the string.
[Link]. TOTAL
E 19
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 5
- Each character is printed on a separate line, demonstrating how we can access
and process individual characters in a string.
Output:
Hello, World!
Ord() :
- The ‘ord()’ function in Python returns the Unicode code point of a given character.
- It takes a single character as an argument and returns an integer representing its
Unicode value.
Example:
print(ord('A'))
print(ord('a'))
print(ord('€'))
Explanation :
- In this example, the ‘ord()’ function is used to get the Unicode code point of the
characters 'A', 'a', and '€'.
- The function returns the corresponding integer values.
Output:
65
97
8364
[Link]. TOTAL
E 20
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 5
chr() :
- On the other hand, the ‘chr()’ function in Python returns the character associated
with a specified Unicode code point.
- it takes an integer code point as an argument and returns the corresponding
character.
Example:
print(chr(65))
print(chr(97))
print(chr(8364))
Code explanation :
In this example, the ‘chr()’ function is used to obtain the characters associated
with the Unicode code points 65, 97, and 8364.
The function returns the characters 'A', 'a', and '€' respectively.
Output:
A
a
€
[Link]. TOTAL
E 21
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 6
a) Explanation of three programming paradigms:
1) Procedural Programming:
- Procedural programming is a paradigm in which the program is structured around
procedures or subroutines.
- It focuses on executing a sequence of procedures, where each procedure performs
a specific task.
- The emphasis is on dividing the program into smaller, reusable functions and
organizing them in a top-down manner.
- Flow control is typically achieved through conditionals and loops.
- Examples of procedural programming languages include C, Pascal, and Fortran.
3) Functional Programming:
- Functional programming is a paradigm that treats computation as the evaluation
of mathematical functions.
- It focuses on writing pure functions that do not have side effects and avoid
mutable data.
- Functions are first-class citizens, meaning they can be assigned to variables,
passed as arguments, and returned as values.
[Link]. TOTAL
E 22
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 6
- Functional programming encourages immutability, higher-order functions, and
recursion.
- It aims to write declarative, concise, and modular code.
- Examples of functional programming languages include Haskell, Lisp, and Erlang.
class :
- A class is a blueprint or template that defines the properties (attributes) and
behaviors (methods) that objects of that class will have.
- It acts as logical entity that encapsulate related data & functions into single unit.
- A class defines the structure, characteristics, and behaviors that objects of that
class will possess.
- It provides a blueprint for creating objects with similar attributes and behaviors.
- Classes promote code reusability, modularity, and easier maintenance.
’__init__()’ method :
The ‘__init__()’ method, also known as the initializer or constructor, is a special
method that gets automatically called when an object of a class is created.
Its purpose is to initialize the object's attributes or perform any setup operations
required for the object.
Here's an example that demonstrates the definition of a class and the ‘__init__()’
method:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def display_info(self):
print("Name:", [Link])
print("Age:", [Link])
[Link]. TOTAL
E 23
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 6
print("Age:", [Link])
# Creating an object of the Person
classperson1 = Person("Alice", 25)
# Calling the display_info() method of the object
person1.display_info()
Code Explanation :
- We define a class named ‘Person’ using the ‘class’ keyword.
- Inside the class, we define the ‘__init__()’ method that takes two parameters:
‘name’ and ‘age’.
- The ‘self’ parameter refers to the instance of the object being created.
- Within the ‘__init__()’ method, we assign the values of ‘name’ and ‘age’ to the
object's attributes using the ‘self’ keyword.
- We also define another method named ‘display_info()’ that prints the object's
attributes.- We create an object ‘person1’ of the ‘Person’ class, passing the values
"Alice" and 25 as arguments.
- Finally, we call the ‘display_info()’ method of the ‘person1’ object, which displays
the object's attributes.
Output:
Name: Alice Age: 25
1) Class:
- A class is a blueprint or template that defines the properties (attributes) and
behaviors (methods) that objects of that class will have.
- It acts as a logical entity that encapsulates related data and functions into a
single unit.
- A class defines the structure, characteristics, and behaviors that objects of that
[Link]. TOTAL
E 24
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 6
- A class defines the structure, characteristics, and behaviors that objects of that
class will possess.
- It provides a blueprint for creating objects with similar attributes and behaviors.
- Classes promote code reusability, modularity, and easier maintenance.
2) Object:
- An object is an instance of a class, It represents a specific entity or instance
created from the class.
- Objects have their own unique identity and can have their own specific values for
attributes defined in the class.
- Objects can invoke the methods defined in the class to perform specific actions
or behaviors.
- Multiple objects can be created from same class, each having its own distinct
state.
The concept of a class and an object in OOP can be understood through the following
program:
प्र.क्र./Q. No.
Q. 6
Code explanation :
- We define a class called ‘Person’ with the ‘__init__()’ method that takes a
parameter ‘name’ to initialize the object's ‘name’ attribute.
- The ‘greet()’ method is defined within the class to display a greeting message
with the person's name.
- We create two objects, ‘person1’ and ‘person2’, passing different names as
arguments.
- We call the ‘greet()’ method on each object, which prints the greeting message
with the respective names.
Output:
Hello, my name is AliceHello,
my name is Bob
[Link]. TOTAL
E 26
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 7
a) explanation of the features of Object-Oriented Programming (OOP):
i) Data Encapsulation:
- Data encapsulation is the process of combining data and methods/functions into
a single unit called an object.
- It allows the data to be hidden or protected from direct access by other parts of
the program.
- The data can only be accessed and modified through the defined methods of the
object, providing control over how the data is manipulated.
- Encapsulation helps achieve data security, maintainability, and reusability by
keeping related data and methods together.
iii) Polymorphism:
- Polymorphism is the ability of an object to take on different forms or behaviors.
- It allows objects of different classes to be treated as objects of a common
superclass.
- Polymorphism enables code to be written that can work with objects of different
types, providing flexibility and extensibility.
- It can be achieved through method overriding (in inheritance) and method
overloading (having multiple methods with the same name but different
parameters).
[Link]. TOTAL
E 27
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 7
- Polymorphism simplifies code maintenance and promotes code reusability by
enabling the use of common interfaces and behaviors.
By understanding and implementing these features of Object-Oriented Programming,
we can design and develop software that is modular, maintainable, and flexible.
1. Class Variables:
- Class variables are variables that are shared among all instances (objects) of a
class.
- They are defined within the class but outside of any methods.
- Class variables have the same value for every instance of the class.
- They are accessed using the class name or any instance of the class.
class Car:
# Class variable
car_count = 0
def __init__(self, make, model):
[Link]. TOTAL
E 28
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 7 # Object variables
[Link] = make
[Link] = model
Code explanation :
- The ‘Car’ class has a class variable ‘car_count’ initialized to ‘0’.- The ‘__init__()’
method is the constructor that initializes object variables ‘make’ and ‘model’.
- The ‘Car.car_count += 1’ statement increments the class variable ‘car_count’
whenever a new car instance is created.
- Two car instances (‘car1’ and ‘car2’) are created with different make and model
values.
- ‘Car.car_count’ is accessed using the class name to get the total number of cars.
- Object variables (‘make’ and ‘model’) are accessed using the instance names
(‘[Link]’, ‘[Link]’, etc.).
By running this code, we'll see that the class variable ‘car_count’ is shared
among all car instances, while the object variables ‘make’ and ‘model’ hold unique
values for each car instance.
Output:
[Link]. TOTAL
E 29
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 7
- ‘Car.car_count’ is accessed using the class name to get the total number of cars.
- Object variables (‘make’ and ‘model’) are accessed using the instance names
(‘[Link]’, ‘[Link]’, etc.).
By running this code, you'll see that the class variable ‘car_count’ is shared
among all car instances, while the object variables ‘make’ and ‘model’ hold unique
values for each car instance.
Output:
Number of cars: 2
Car 1: Toyota Corolla
Car 2: Honda Accord
c) the program to create a class 'Employee' with two attributes and display the
details of two employees:
step required :
प्र.क्र./Q. No.
Q. 7
- Print the employee details using the 'print' function.
Python program that uses class 'Employee' with two attributes and display the
details of two employees:
class Employee:
def __init__(self, name, designation):
[Link] = name
[Link] = designation
Code explanation :
- In this program, we define the 'Employee' class with the '__init__' method, which
initializes the 'name' and 'designation' attributes of an employee object.
- We then create two employee objects, 'employee1' and 'employee2', by instantiating
the 'Employee' class with different values for the 'name' and 'designation' attributes.
- To display the employee details, we access the attributes of each employee object
using the dot notation ([Link]).
[Link]. TOTAL
E 31
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 7
- We print the details using 'print' function, providing the necessary labels for clarity.
- By executing this program, you'll see the details of two employees, including their
names and designations.
Output:
Employee 1:
Name: John Doe
Designation: Manager
Employee 2:
Name: Jane Smith
Designation: Developer
[Link]. TOTAL
E 32
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 8
a) file :
- a file is a collection of related data or information stored on a computer storage
device.
- It is a named entity that acts as a repository for storing and retrieving data.
- Files can contain various types of data, such as text, images, audio, video, or
program instructions.
प्र.क्र./Q. No.
Q. 8
- The file pointer is positioned at the beginning of the file.
- Raises a ‘FileNotFoundError’ error if the file does not exist.
These access modes are passed as a string argument to the ‘open()’ function
to specify the intended behavior when opening the file.
b) Dictionary:
A dictionary in Python is an unordered collection of key-value pairs.
It allows you to store and retrieve data using a unique key as an identifier.
Dictionaries are useful for organizing and manipulating data that can be accessed
by their keys, rather than numerical indices like in lists.
1. Creating a Dictionary:
- Use curly braces ‘{}’ to define an empty dictionary or enclose key-value pairs
inside the braces.
- Separate each key-value pair with a colon ‘:’ and separate multiple pairs with
commas.
Example:
[Link]. TOTAL
E 34
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 8
Example:
# Creating an empty dictionary
my_dict = {}
# Creating a dictionary with initial key-value pairs
my_dict = {"name": "John", "age": 25, "city": "New York"}
Output:
John
25
New York
Output:
[Link]. TOTAL
E 35
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 8
Output:
{'name': 'John', 'age': 30, 'city': 'San Francisco'}
c) Relative Path:
- A relative path refers to the location of a file or directory relative to the current
working directory.
- It is specified based on the current working directory as a starting point.
- Relative paths do not start with the root directory or drive letter.
- They provide a concise way to reference files or directories within the same
directory or in a subdirectory.
Example:
Consider a directory structure:-
project/
- [Link]
- data/
- [Link]
- If the current working directory is ‘project/’, to reference ‘[Link]’, you can use
the relative path ‘data/[Link]’.
- If the current working directory is ‘project/data/’, you can use the relative path
‘../[Link]’ to reference the ‘[Link]’ file in the parent directory.
Absolute Path:
- An absolute path refers to the complete and exact location of a file or directory
in the file system.
- It specifies the file or directory's location starting from the root directory or drive
letter.
- Absolute paths provide an unambiguous way to reference files or directories
regardless of the current working directory.
Example:
[Link]. TOTAL
E 36
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 8
Example:
Consider a file system:
- C:/
- project/
- [Link]
- data/
- [Link]
प्र.क्र./Q. No.
Q. 9
a) three common methods for reading and writing files in Python, explained step
by step:
1. Reading Files:
- Open the file using the ‘open()’ function, specifying the file path and mode ('r'
for reading).
- Use the ‘read()’ method to read the entire contents of the file as a string or use
‘readline()’ to read one line at a time.
- Close the file using the ‘close()’ method to free up system resources.
Example:
# Step 1: Open the file in reading mode
file = open("[Link]", "r")
2. Writing Files:
- Open the file using the ‘open()’ function, specifying the file path and mode ('w'
for writing).
- Use the ‘write()’ method to write data to the file.
- Close the file using ‘close()’ method to save changes and free up system resources.
# Step 1: Open the file in writing mode
[Link]. TOTAL
E 38
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 9
Example:
# Step 1: Open the file in writing mode
file = open("[Link]", "w")
Output :
- The program will create or overwrite the file "[Link]" with the text "Hello,
World!"
- No output will be displayed.
प्र.क्र./Q. No.
Q. 9
# Step 4: Close the file
[Link]()
Output:
Hello, World! #Assuming the file "[Link]" contains the text "Hello, World!"
Additional information :
- note that the output may vary depending on the content of the file and the
specific operations performed.
- By following these steps, we can read and write files in Python using different
methods. to open the file, perform the desired operations, and then close the file
to ensure proper handling of resources.
1. ‘[Link]()’:
- The ‘[Link]()’ method returns the current working directory.
- It is used to retrieve the absolute path of the directory where the Python script
is currently being executed.
Example:
import os
current_directory = [Link]()
print("Current working directory:", current_directory)
Output:
Current working directory: /path/to/current/directory
[Link]. TOTAL
E 40
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 9
Code explanation :
- In this example, the ‘[Link]()’ method is called to retrieve the current working
directory, and it is stored in the ‘current_directory’ variable.
- The absolute path of the current directory is then printed.
2. ‘[Link](path)’:
- The ‘[Link](path)’ method is used to change the current working directory to
the specified path.
- It allows you to navigate to a different directory within the file system.
Example:
import os
new_directory = '/path/to/new/directory'
[Link](new_directory)
print("Changed working directory to:", [Link]())
Output:
Changed working directory to:
/path/to/new/directory
Code explanation :
- In this example, the ‘[Link]()’ method is used to change the current working
directory to ‘/path/to/new/directory’.
- The ‘[Link]()’ method is then called to verify the change, and the new
directory's absolute path is printed.
3. ‘[Link](path)’:
- The ‘[Link](path)’ method returns a list of all files and directories in the
specified path.
- It provides a way to retrieve the contents of a directory.
Example:
[Link]. TOTAL
E 41
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 9
Example:
import os
directory = '/path/to/directory'
contents = [Link](directory)
print("Contents of", directory + ":")
for item in contents:
print(item)
Output:
Contents of /path/to/directory:
[Link]
[Link]
folder1
Code explanation :
In this example, the ‘[Link]()’ method is used to retrieve the contents of the
directory specified by ‘/path/to/directory’.
The list of contents is stored in the ‘contents’ variable.
Then, a loop is used to iterate over the contents and print each item (file or
directory) present in the specified path.
c) Python program that reads the first 10 characters from a file and displays
them:
Step required :
1. Open the file:
- Use the ‘open()’ function to open the file in read mode.
- Provide the file path or name as the argument to ‘open()’.
प्र.क्र./Q. No.
Q. 9
2. Read the first 10 characters:
- Use the ‘read()’ function on the file object.
- Specify the number of characters to read as an argument (in this case, 10).
python program:
important point :
- Make sure to replace ‘"[Link]"‘ with the actual name or path of your file.
- By following these steps, the program will read the first 10 characters from the
specified file and display them.
- Please note that if the file has fewer than 10 characters, it will read all the
available characters.