[go: up one dir, main page]

0% found this document useful (0 votes)
13 views17 pages

PWP 1

Robbing

Uploaded by

Ronit Patil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views17 pages

PWP 1

Robbing

Uploaded by

Ronit Patil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Q1.

list Data types in Python


Ans:
-Python has various standard data types that are used to define the operations possible on them and the storage method
for each of them.
-Here’s a refined explanation of the Python data types you’ve listed:
1. Numbers:
o Represents numeric data used for mathematical operations.
o Types: int, float, complex.
2. String:
o Represents a sequence of text characters, special symbols, or alphanumeric data.
o Type: str (e.g., 'hello', "Python").
3. List:
o Represents an ordered collection of items that are mutable, meaning you can modify, add, or remove
items.
o Type: list (e.g., [1, 2, 3], ['apple', 'banana']).
4. Tuple:
o Similar to a list but immutable, meaning once created, its values cannot be changed.
o Type: tuple (e.g., (1, 2, 3), ('a', 'b')).
5. Dictionary:
o Represents a collection of key-value pairs. Each key must be unique, and it maps to a specific value.
o Type: dict (e.g., {'name': 'Alice', 'age': 25}).
6. Boolean:
o Represents truth values, either True or False.
o Type: bool (e.g., True, False).
These data types are fundamental in Python, helping store and manipulate different kinds of data.

Q2. Explain various modes of file object


Ans:
-‘r': Read (default mode)
-'w': Write (creates a new file or truncates an existing file)
-'x': Exclusive creation (fails if the file exists)
-'a': Append (adds content to the end of the file)
-'b': Binary (used with other modes to handle binary files)
-'t': Text (default mode, used for text files)
-'r+': Read and Write (file must exist)
-'w+': Write and Read (creates a new file or truncates an existing file)
-'a+': Append and Read (adds content to the end of the file)

-Example:
1. Read Mode ('r'):
-This is the default mode. It opens the file for reading.
-If the file doesn't exist, it raises a FileNotFoundError.
-When opened in this mode, attempting to write to the file will raise a UnsupportedOperation error.
-Example: open('file.txt', 'r')

2. Write Mode ('w'):


-Opens the file for writing. If the file doesn't exist, it creates a new file.
-If the file already exists, it truncates the file to zero length.
-Example: open('file.txt', 'w')

3. Append Mode ('a'):


-Opens the file for writing. If the file doesn't exist, it creates a new file.
-If the file already exists, it appends data to the end of the file.
-Example: open('file.txt', 'a')
Q3. Write concept of inheritance in python (Code,6m)
Ans:
-Inheritance is one of the fundamental principles of Object-Oriented Programming (OOP).
-It allows a new class to reuse the properties and methods of an existing class.
-The main goal of inheritance is to enable code reusability, hierarchical classification, and method overriding.

-Key Points:
1. Code Reusability: Inheritance lets you write common functionalities once in the parent class and reuse them
in child classes, reducing code duplication.
2. Improved Structure: It promotes a cleaner and logical organization of code, making it easier to understand
and maintain.
3. Method Overriding: A child class can override a method from the parent class to provide a specific
implementation.
4. Extensibility: Existing classes can be extended to include new behaviors without modifying the original class.

- Syntax in Python:
class Parent:
# parent class code

class Child(Parent):
# child class code (inherits from Parent)

Q4. Explain user defined package (6m)


Ans:
A package is a hierarchical file directory structure that defines a single Python application environment that consists of
modules and subpackages and sub-subpackages, and so on.
Packages allow for a hierarchical structuring of the module namespace using dot notation.
Creating a package is quite straightforward, since it makes use of the operating system’s inherent hierarchical file
structure.
Consider the following arrangement:

Here, there is a directory named pkg that contains two modules, mod1.py and mod2.py. The contents of the modules
are:
mod1.py
def m1():
print("first module")

mod2.py
def m2():
print("second module")

If the pkg directory resides in a location where it can be found, you can refer to the two modules with dot
notation(pkg.mod1, pkg.mod2) and import them with the syntax:

Syntax-1 import [, ...]


Example:
>>>import pkg.mod1, pkg.mod2
>>> pkg.mod1.m1()
first module
Q5. Explain Numpy Package
Ans:
-NumPy (Numerical Python) is a powerful open-source Python library used for scientific and numerical computing.
-It provides support for multi-dimensional arrays (ndarray) and offers a wide range of mathematical, statistical,
and linear algebra functions.
-Key Features:
• Efficient handling of large datasets using n-dimensional arrays.
• Built-in functions for operations like addition, mean, standard deviation, etc.
• Broadcasting for operations on arrays of different shapes.
• Linear algebra support like matrix multiplication, inverse, and determinant.
-Example:
import numpy as np
a = np.array([1, 2, 3])
Applications: Data science, machine learning, simulations, image processing.

Q6. Explain method overloading and overriding in python.


Ans:
Method Overloading and Overriding in Python (4 Marks)
1. Method Overloading:
• Method overloading means having multiple methods with the same name but different parameters.
• Python does not support true method overloading like Java or C++. If multiple methods with the same
name are defined, the last one overrides the previous ones.
• Overloading can be achieved using default arguments or *args.
Example:
class Example:
def show(self, a=None, b=None):
if a and b:
print(a + b)
elif a:
print(a)
else:
print("No arguments")

2. Method Overriding:
• Method overriding occurs when a child class redefines a method of its parent class.
• Used to implement runtime polymorphism and customize behavior in subclasses.
Example:
class Parent:
def show(self):
print("Parent class")

class Child(Parent):
def show(self):
print("Child class")

Q7. Explain Membership , Set , Bitwise , identity , assignment operators with example
Ans:
Membership operator:
-Membership operators are used to test if a value exists within a sequence like a list, tuple, string, or set.
-The two membership operators in Python are:
1. in: Returns True if the value is found in the sequence.
2. not in: Returns True if the value is not found in the sequence.

Example:
fruits = ['apple', 'banana', 'cherry']
print('apple' in fruits) # Output: True
This checks if 'apple' exists in the list fruits.

Bitwise Operators:
-Bitwise operators are used to perform operations on binary numbers (bits).
-They are applied to integers at the bit level.
-The main bitwise operators in Python are:
1. & (AND): Performs a bitwise AND operation.
2. | (OR): Performs a bitwise OR operation.
3. ^ (XOR): Performs a bitwise XOR (exclusive OR) operation.
4. ~ (NOT): Performs a bitwise NOT operation (inverts the bits).
5. << (Left Shift): Shifts bits to the left.
6. >> (Right Shift): Shifts bits to the right.

Example: Bitwise AND (&):


a=5
b=3
result = a & b
print(result) # Output: 1

Set Operators :
-Set operators are used to perform operations like union, intersection, difference, and symmetric difference on sets.
-The main set operators in Python are:
1. | (Union): Combines all elements from two sets.
2. & (Intersection): Returns common elements between two sets.
3. - (Difference): Returns elements in the first set but not in the second.
4. ^ (Symmetric Difference): Returns elements that are in either of the sets, but not in both.

Example: Set Intersection (&):


set1 = {1, 2, 3}
set2 = {2, 3, 4}
result = set1 & set2 # Intersection: {2, 3}
print(result) # Output: {2, 3}

Identity Operators:
Identity operators are used to compare the memory locations of two objects. They are:
• is: Returns True if two variables refer to the same object (i.e., have the same memory address).
• is not: Returns True if two variables refer to different objects (i.e., have different memory addresses).
Example:
a = [1, 2, 3]
b = [1, 2, 3]
c=a

print(a is b) # Output: False, as a and b refer to different objects


print(a is c) # Output: True, as a and c refer to the same object

Assignment Operators:
Assignment operators are used to assign values to variables. The most commonly used assignment operator is:
• =: Assigns the value of the right-hand side to the left-hand variable.
• +=: Adds the right-hand value to the left-hand variable and assigns the result to the left-hand variable.
• -=, *=, /=, etc.: Perform the specified operation and assign the result to the left-hand variable.
Example:
x=5 # Assignment operator
y = 10
x += y #x=x+y
print(x) # Output: 15
Q8. Explain how try-catch block is used for exception handling in python.
Ans:
Exception Handling is a mechanism in Python used to handle runtime errors (exceptions) so that the normal flow of
the program is not interrupted. Instead of the program crashing when an error occurs, Python allows us to manage
these situations gracefully using exception handling blocks.

try and except Block:


• The try block contains code that might raise an exception. It "tries" to execute risky code.
• The except block contains code that runs only if an exception occurs in the try block. It "catches" the error
and allows the program to continue or exit cleanly.
Syntax:
try:
# Block of code that may raise an exception
except ExceptionType:
# Code to handle the exception

Q9. Explain the Building Blocks of Python.


Ans:
Python is a high-level programming language, and its structure is made up of several core components called building
blocks. The main building blocks are:
1. Tokens
Tokens are the smallest units in a Python program. They include keywords, identifiers, literals, operators, and
punctuation marks. Each token has a specific meaning in the program and helps in defining the syntax.
2. Variables
Variables are names used to store data values in memory. In Python, variables are dynamically typed, which
means the data type is determined automatically at runtime based on the assigned value.
3. Data Types
Python supports various data types like integers, floats, strings, lists, tuples, sets, and dictionaries. Each data
type is used to represent specific kinds of information and allows suitable operations to be performed.
4. Control Structures
Control structures manage the flow of execution in a program. Python uses if, elif, and else for decision-
making and for and while loops for iteration, allowing programmers to create dynamic and logical flows.
5. Functions
Functions are reusable blocks of code that perform specific tasks. Python allows the creation of user-defined
functions and also provides many built-in functions to reduce redundancy and improve modularity.
6. Exception Handling
Exception handling in Python is done using try and except blocks. It helps manage runtime errors gracefully
without crashing the program, ensuring smooth execution and error control.

Q10. Explain method overloading and overriding in python.


Ans:
Method Overloading and Overriding in Python (4 Marks)
1. Method Overloading:
• Method overloading means having multiple methods with the same name but different parameters.
• Python does not support true method overloading like Java or C++. If multiple methods with the same
name are defined, the last one overrides the previous ones.
• Overloading can be achieved using default arguments or *args.
Example:
class Example:
def show(self, a=None, b=None):
if a and b:
print(a + b)
elif a:
print(a)
else:
print("No arguments")

2. Method Overriding:
• Method overriding occurs when a child class redefines a method of its parent class.
• Used to implement runtime polymorphism and customize behavior in subclasses.
Example:
class Parent:
def show(self):
print("Parent class")

class Child(Parent):
def show(self):
print("Child class")

Q11. List and explain any four built-in functions on set.


Ans:
1) len(list) :
It returns the length of the list.
Example:
>>> list1
[1, 2, 3, 4, 5]
>>> len(list1)
5

2) max(list) :
It returns the item that has the maximum value in a list
Example:
>>> list1
[1, 2, 3, 4, 5]
>>> max(list1)
5

3) sum(list) :
Calculates sum of all the elements of list.
Example:
>>>list1
[1, 2, 3, 4, 5]
>>>sum(list1)
15

4) min(list) :
It returns the item that has the minimum value in a list.
Example:
>>> list1
[1, 2, 3, 4, 5]
>>> min(list1)
1

Q12. Explain Module and its use in Python.


Ans:
Module:
-A module in Python is a file containing Python definitions and statements.
-It allows you to organize code into separate files, making it easier to manage and reuse.
-Modules can include functions, classes, and variables, and they can also contain runnable code.
-Uses of Modules:
1. Code Reusability: Modules allow you to organize your code into smaller, reusable components. Instead of
writing the same code multiple times, you can import a module and use its functions.
2. Namespace Organization: Using modules helps avoid naming conflicts and keeps the global namespace
clean.
3. Better Maintainability: Code is easier to maintain and debug when it's organized into modules.
-Example:
def add(a, b):
return a + b

import math_operations
print(math_operations.add(2, 3)) # Output: 5

Q13. Explain method of dictionary


Ans:
1. keys()
This method returns a view object that contains all the keys in the dictionary. It helps to iterate over all the
keys without manually indexing the dictionary.
2. values()
This method returns a view object containing all the values in the dictionary. It is useful when we only need to
work with the values, not the keys.
3. items()
This method returns a view object with all key-value pairs as tuples. It is commonly used in loops to access
both keys and their corresponding values.
4. get(key)
This method returns the value associated with the specified key. Unlike direct access, it doesn’t throw an error
if the key is not found; instead, it returns None or a default value if specified.

Q14. Explain how to use user defined function in python with example
Ans:
-In Python, def keyword is used to declare user defined functions.
-The function name with parentheses (), which may or may not include parameters and arguments and a colon:
-An indented block of statements follows the function name and arguments which contains the body of the function.
-Syntax:
def function_name():
statements
.
.
-Example:
def fun():
print(“User defined function”)
fun()
-output:
User defined function

Q15. Explain basic operations of list


Ans:
1. append() – Adds an item to the end of the list.
example:
my_list.append(10)

2. insert() – Inserts an item at a specific index.


example:
my_list.insert(1, 20) # Inserts 20 at index 1
3. pop() – Removes and returns the item at the given index. If no index is given, it removes the last item.
example:
my_list.pop() # Removes last item
my_list.pop(0) # Removes item at index 0

4. sort() – Sorts the list in ascending order (modifies the original list).
example:
my_list.sort()

5. len() – Returns the number of elements in the list.


example:
length = len(my_list)

Q16. Explain decision making if - else, if - elif – eise


Ans:
What is Decision Making?
In Python, decision making refers to the process of making choices based on conditions. It allows your program to
respond differently depending on the input or data at runtime. This is achieved using conditional statements like if, if-
else, and if-elif-else.

1. if Statement
The if statement is the simplest form of decision making. It evaluates a condition (an expression that results in True or
False). If the condition is True, the block of code under if is executed. If it is False, nothing happens.
Syntax:
if condition:
# code block to execute if condition is True

2. if-else Statement
The if-else structure provides two possible paths: one for when the condition is True, and one for when it's False.
Syntax:
if condition:
# block executed if condition is True
else:
# block executed if condition is False

3. if-elif-else Statement
This structure is used when you have multiple conditions to test. Python will check each condition in sequence, and
the first one that is true will have its block executed. If none of the if or elif conditions are true, the else block is
executed.
Syntax:
if condition1:
# block if condition1 is True
elif condition2:
# block if condition2 is True
elif condition3:
# block if condition3 is True
else:
# block if none of the above conditions are True

Q17. Explain use of Pass and Else keyword with for loops in python.
Ans:
1. pass Keyword:
The pass keyword is a null statement used as a placeholder when a statement is required syntactically but you don't
want to execute any code. It allows the program to continue without doing anything.
• Usage: The pass keyword is typically used when you are working on a block of code that is not yet
implemented or when you need an empty block (like in a loop or a function).
Example:
for i in range(5):
if i == 3:
pass # Do nothing when i equals 3
else:
print(i)
Output:
0
1
2
4

2. else Keyword with For Loops:


The else block in a for loop is executed only when the loop completes normally, meaning without encountering a
break statement. If the loop is terminated by a break, the else block will not be executed.
• Usage: The else block can be used to perform actions after the loop finishes, such as checking if a condition
was met during the loop.
Example:
The loop was broken at i = 3, so the else block is not executed.
However, if there’s no break and the loop completes normally:
for i in range(5):
print(i)
else:
print("Loop completed without break")
Output:
0
1
2
3
4

Q18. . Explain seek ( ) and tell ( ) function in python with example.


Ans:
seek():
-In python programming, within file handling concept seek() function is used to shift/change the position of file object
to required position.
-By file object we mean a cursor. And it’s cursor, who decides from where data has to be read or write in a file.
-Syntax:
f.seek(offset, fromwhere)
where offset represents how many bytes to move fromwhere, represents the position fromwhere the bytes are moving.
-Example:
f = open("demofile.txt", "r")
f.seek(4)
print(f.readline())

tell():
-tell() returns the current position of the file pointer from the beginning of the file.
- Syntax:
file.tell()
Example:
f = open("demofile.txt", "r")
# points at the start
print(f.tell())
Q19. Explain Local and Global variable
Ans:
Local Variables:
-Local variables are those which are initialized inside a function and belongs only to that particular function.
-It cannot be accessed anywhere outside the function.
-Example:
def f():
# local variable
s = "I love Python Programming"
print(s)
# Driver code
f()
-Output: I love Python Programming

Global Variables:
-The global variables are those which are defined outside any function and which are accessible throughout the
program i.e. inside and outside of every function.
-Example:
# This function uses global variable s
def f():
print("Inside Function", s)

# Global scope
s = "I love Python Programming" f
() print("Outside Function", s)

-Output: Inside Function I love Python Programming


Outside Function I love Python Programming

Q20. Describe Keyword "continue" with example.


Ans:
-The continue statement in Python returns the control to the beginning of the whileloop.
-The continue statement rejects all the remaining statements in the current iterationof the loop and moves the control
back to the top of the loop.
-Syntax: continue
-Example: For continue statement.
i=0
while I
i=i+1
if i==5:
continue
print("i= ",i)
-Output:
i=1
i=2
i=3
i=4
i=6
i=7
i=8
i=9
i=10

Q21. Explain Creating and accessing Dictonary elements with example


Ans:
Creating a Dictionary
You can create a dictionary using curly braces {} or the dict() constructor.
Example 1: Using Curly Braces
student = {
"name": "Alice",
"age": 21,
"course": "Computer Science"
}

Example 2: Using dict() function


employee = dict(name="John", id=101, department="HR")

Accessing Dictionary Elements


You can access the values in a dictionary by using keys.
Method 1: Using Square Brackets []
print(student["name"]) # Output: Alice
print(student["age"]) # Output: 21
If the key does not exist, it raises a KeyError.

Method 2: Using get() Method


print(student.get("course")) # Output: Computer Science
print(student.get("grade")) # Output: None (no error)
Safer than square brackets, as it returns None if the key is missing (or a default value if provided).

Adding or Updating Elements


student["grade"] = "A" # Adds a new key-value pair
student["age"] = 22 # Updates existing key

Removing Elements
student.pop("course") # Removes 'course' key
del student["age"] # Deletes 'age' key

Checking for Keys


if "name" in student:
print("Name exists in dictionary")

Q22. State the use of read() and readline () functions in python file handling.
Ans:
1. read([n]) Method:
-The read method reads the entire contents of a file and returns it as a string, if number of bytes are not given in the
argument.
-If we execute read(3), we will get back the first three characters of the file.
-Example: for read( ) method.
f=open("sample.txt","r")
print(f.read(5))
print(f.read())

2. readline([n]) Method:
-The readline() method just output the entire line whereas readline(n) outputs at most n bytes of a single line of a file.
-It does not read more than one line. Once, the end of file is reached, we get empty string on further reading.
-Example: For readline ( ) method.
f=open("sample.txt","r")
print(f.readline())
print(f.readline(3))
print(f.readline())
Q23. Describe 'Self Parameter with example.
Ans:
-In Python, the self parameter is a convention used in object-oriented programming (OOP) to refer to the instance of a
class within the class itself.
-It allows you to access the attributes and methods of the class from within its own methods.
-The name self is not a keyword in Python, but it is widely adopted and recommended as a convention.
- Example:
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def get_info(self):
info = f"Make: {self.make}, Model: {self.model}, Year: {self.year}"
return info
def start_engine(self):
print("Engine started!")
# Create an instance of the Car class
my_car = Car("Toyota", "Corolla", 2022)
# Access the attributes using the self parameter
print(my_car.make) # Output: Toyota
print(my_car.model) # Output: Corolla
print(my_car.year) # Output: 2022
# Call the method using the self parameter
car_info = my_car.get_info()
print(car_info) # Output: Make: Toyota, Model: Corolla, Year: 2022
# Call the method that does not require any additional parameters
my_car.start_engine() # Output: Engine started!

Q24. Explain Built-in tuple function


Ans:
1. len()
• Returns the number of elements in the tuple.
t = (10, 20, 30)
print(len(t)) # Output: 3

2. max()
• Returns the maximum value in the tuple (only works if the elements are comparable).
t = (5, 10, 3)
print(max(t)) # Output: 10

3. min()
• Returns the minimum value in the tuple.
t = (5, 10, 3)
print(min(t)) # Output: 3

4. sum()
• Returns the sum of all numeric elements in the tuple.
t = (1, 2, 3)
print(sum(t)) # Output: 6

5. tuple()
• Converts another data type (like a list) into a tuple.
lst = [1, 2, 3]
t = tuple(lst)
print(t) # Output: (1, 2, 3)
Q25. Explain indexing and slicing in list
Ans:
What is a List?
A list in Python is an ordered, mutable collection of elements, which can be accessed using indexing and slicing.

Indexing in Lists
Indexing means accessing individual elements in a list using their position number.
• Index starts from 0 (for the first element).
• Negative indexing allows access from the end of the list (-1 is the last element).
Example:
fruits = ["apple", "banana", "cherry", "date"]

print(fruits[0]) # Output: apple


print(fruits[2]) # Output: cherry
print(fruits[-1]) # Output: date (last element)

Slicing in Lists
Slicing is used to access a subsection of the list (a slice) using a range of indices.
Syntax:
list[start : end : step]
• start: index to begin the slice (inclusive).
• end: index to end the slice (exclusive).
• step: optional, how many elements to skip.
Example:
fruits = ["apple", "banana", "cherry", "date", "fig"]

print(fruits[1:4]) # Output: ['banana', 'cherry', 'date']


print(fruits[:3]) # Output: ['apple', 'banana', 'cherry']
print(fruits[::2]) # Output: ['apple', 'cherry', 'fig']
print(fruits[::-1]) # Output: reversed list

Q26. Explain use of format() method with example


Ans:
-The format() method formats the specified value(s) and insert them inside the string's placeholder.
-The placeholder is defined using curly brackets: {}.
-The format() method returns the formatted string.
-Syntax
string.format(value1, value2...)
-Example:
#named indexes:
>>>txt1 = ("My name is {fname}, I'm {age}".format(fname = "abc", age = 36))
>>>print(txt1)
My name is abc, I'm 36

#numbered indexes:
>>>txt2 =( "My name is {0}, I'm {1}".format("xyz",36))
>>>print(txt2)
My name is xyz, I'm 36

#empty placeholders:
>>>txt3 = ("My name is {}, I'm {}".format("pqr",36))
>>>print(txt3)
My name is pqr, I'm 36
Q27. Explain the Concept of indentation and variables
Ans:
i) Indentation:
• Python provides no braces to indicate blocks of code for class and function
definitions or flow control.
• Blocks of code are denoted by line indentation, which is compulsory.
• The number of spaces in the indentation is variable, but all statements within
the block must be indented the same amount.
• Example:
if True:
print "True"
else:
print "False"
• Thus, in Python all the continuous lines indented with same number of spaces
would form a block.

ii) Variables:
• Python Variable is containers that store values.
• We do not need to declare variables before using them or declare their type.
• A variable is created the moment we first assign a value to it.
• A Python variable is a name given to a memory location.
• It is the basic unit of storage in a program.
• Variable Naming Rules in Python
1) Variable name should start with letter(a-z ,A-Z) or underscore (_).
Example: age, _age, Age
2) In variable name, no special characters allowed other than underscore (_).
Example: age_, _age
3) Variables are case sensitive.
Example: age and Age are different, since variable names are case
sensitive.
4) Variable name can have numbers but not at the beginning.
Example: Age1
5) Variable name should not be a Python reserved keyword.
• Example:
x = 5 # x is of type integer
y = "John" # y is of type string

Q28. Explain the Concept of Pandas


Ans:
Panda:
• Pandas is a powerful and versatile library that simplifies the tasks of data
manipulation in Python.
• Pandas is well-suited for working with tabular data, such as spreadsheets or
SQL tables.
• The Pandas library is an essential tool for data analysts, scientists, and
engineers working with structured data in Python.
• It is built on top of the NumPy library which means that a lot of the
structures of NumPy are used or replicated in Pandas.
• The data produced by Pandas is often used as input for plotting functions in
Matplotlib, statistical analysis in SciPy, and machine learning algorithms in
Scikit-learn.

Q29. ) Explain the function open() and write() in python


Ans:
i) The open() function
-he open() function opens a file and returns it as a file object.
-Syntax:
open(file, mode)
file: The path and name of the file
mode: A string, define which mode you want to open the file in:
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exist
In addition you can specify if the file should be handled as binary or text mode
"t" - Text - Default value. Text mode
"b" - Binary - Binary mode (e.g. images)
-Example:
Open a file and print the content:
f = open("demofile.txt", "r")
print(f.read())

ii) The write() function


-The write() method writes a specified text to the file.
-Where the specified text will be inserted depends on the file mode and stream position.
"a": The text will be inserted at the current file stream position, default at the end of the
file.
"w": The file will be emptied before the text will be inserted at the current file stream
position, default 0.
-Syntax:
file.write(byte)
byte: The text or byte object that will be inserted.
-Example:
Open the file with "a" for appending, then add some text to the file:
f = open("demofile2.txt", "a")
f.write("Hi!")
f.close()
#open and read the file after the appending:
f = open("demofile2.txt", "r")
print(f.read())

Q30. Explain multiple inheritance


Ans:
Multiple Inheritance
-In multiple inheritance, a child class inherits from more than one parent class.
-This allows the child class to inherit attributes and methods from multiple classes, promoting code reusability and
flexibility.
-However, it can also lead to potential conflicts if methods with the same name exist in different parent classes.
-Example:
# Parent Class 1
class Parent1:
def greet(self):
print("Hello from Parent1!")

# Parent Class 2
class Parent2:
def greet(self):
print("Hello from Parent2!")

# Child Class inherits from Parent1 and Parent2


class Child(Parent1, Parent2):
pass
# Create an instance of Child class
child = Child()

# Call the greet method


child.greet() # Output: Hello from Parent1!

Q31. Explain loop control statement in python


Ans:
Loop Control Statements:
-Loop control statements are used to alter the flow of execution within loops (for and while loops).
-These statements help in modifying the behavior of loops, allowing you to skip iterations, stop loops early, or
continue to the next iteration.
-Python provides the following loop control statements:
1. break:
o The break statement is used to exit or terminate the current loop prematurely. Once the break
statement is encountered, the loop is immediately terminated, and the program continues with the next
statement after the loop.
2. continue:
o The continue statement is used to skip the current iteration of the loop and move to the next iteration.
The code below continue is not executed for that particular iteration.
3. pass:
o The pass statement is a placeholder used when a statement is syntactically required, but no action is
needed. It doesn’t affect the flow of the program.
-Example:
# Example of break
for i in range(1, 10):
if i == 5:
break # Exit the loop when i equals 5
print(i) # Output: 1 2 3 4

# Example of continue
for i in range(1, 10):
if i == 5:
continue # Skip when i equals 5
print(i) # Output: 1 2 3 4 6 7 8 9

# Example of pass
for i in range(1, 10):
if i == 5:
pass # Do nothing when i equals 5
print(i) # Output: 1 2 3 4 5 6 7 8 9
Q32. List VS Dictionary VS Tuple
Ans:
Feature List Dictionary Tuple
Ordered collection of Unordered collection of key- Ordered collection of
Definition
items value pairs items
Syntax my_list = [1, 2, 3] my_dict = {'key': 'value'} my_tuple = (1, 2, 3)
Order Yes (ordered) No (unordered) Yes (ordered)
Mutability Mutable Mutable Immutable
Keys are unique; values can be
Duplicates Allowed Allowed
duplicated
Accessing By index By key By index
Keys are immutable; values
Homogeneous/Heterogeneous Can store both types Can store both types
can be any type
Storing a collection of Storing key-value pairs for fast Storing a fixed
Use Case
items to modify lookup collection of items

You might also like