0% found this document useful (0 votes)
0 views

python

fuckkkkkkkkkkkkkkkkkkkkk

Uploaded by

Siddhesh Rasane
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

python

fuckkkkkkkkkkkkkkkkkkkkk

Uploaded by

Siddhesh Rasane
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

1. List features of Python.

*
• Easy to Learn and Use • Interpreted Language • Interactive Mode • Free and Open Source • Platform Independence/Cross-
platform Language/Portable • Object-Oriented Language • Extensible

2. Describe membership operators in python


• The membership operators in Python are used to find the existence of a particular element in the sequence, and used only
with sequences like string, tuple, list, dictionary etc. • Membership operators are used to check an item or an element that
is part of a string, a list or a tuple. A membership operator reduces the effort of searching an element in the list. • Python
provides ‘in’ and ‘not in’ operators which are called membership operators and used to test whether a value or variable is in
a sequence.

3. Describe any two data conversion function.


• int(x [,base]): Converts x to an integer. base specifies the base if x is a string. Example: x=int('1100',base=2)=12
• long(x [,base]): Converts x to a long integer. base specifies the base if x is a string. Example: x=long(‘123’base=8)=83L
• float(x): Converts x to a floating point number. Example: x=float('123.45')=123.45
• complex(real[,imag]) : Creates a complex number. Example: x=complex(1,2) = (1+2j)

4. With neat example explain default constructor concept in Python.


The default constructor is simple constructor which does not accept any arguments. It’s definition has only one argument
which is a reference to the instance being constructed.
Example 1: Display Hello message using default constructor.
class Student:
def _ _init_ _(self):
print("This is non parametrized constructor")
def show(self,name):
print("Hello",name)
s1 = Student()
s1.show("Student1")

Output: This is non parametrized constructor


Hello Student1

5. Describe mkdir() function.


• We can make a new directory using the mkdir() method. • This method takes in the path of the new directory. If the full
path is not specified, the new directory is created in the current working directory.
Syntax: os.mkdir(“newdir”)
Example:
>>> import os
>>> os.mkdir("testdir")

6. Describe Multiline comment in python.


• In some situations, multiline documentation is required for a program. If we have comments that extend multiple lines,
one way of doing it is to use hash (#) in the beginning of each line. Another way of doing this is to use quotation marks,
either ''' or """. • Similarly, when it sees the triple quotation marks ''' it scans for the next ''' and ignores any text in between
the triple quotation marks.
Example: '''This is first python program
``Print is a statement'''

7. Explain any four file modes in Python.


1. - r - Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.
2. - rb - Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the
default mode.
3. - r+ - Opens a file for both reading and writing. The file pointer placed at the beginning of the file.
4. - rb+ - Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file.
8. Describe Keyword "continue" with example.
• The continue statement in Python returns the control to the beginning of the while loop. • The continue statement rejects
all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop.
Syntax: continue
Example: For continue statement.
i=0
while i<10:
i=i+1
if i==5:
continue
print("i= ",i)

9. Explain creating Dictionary and accessing Dictionary Elements with example.


Creating Dictionary The simplest method to create dictionary is to simply assign the pair of key:values to the dictionary
using operator (=). • There are two ways for creation of dictionary in python. 1. We can create a dictionary by placing a
comma-separated list of key:value pairs in curly braces{}. Each key is separated from its associated value by a colon:
Example: dict2={1:"Orange", 2:"Mango", 3:"Banana"}
>>> dict2 {1: 'Orange', 2: 'Mango', 3: 'Banana'}
2.Python provides a build-in function dict() for creating a dictionary.
Example: >>> d1=dict({1:"Orange",2:"Mango",3:"Banana"})
>>> d1
{1: 'Orange', 2: 'Mango', 3: 'Banana'}
Accessing Dictionary
• We can access the items of a dictionary by following ways:
1. Referring to its key name, inside square brackets([]).
Example: For accessing dictionary items [ ] using.
>>> dict1={'name':'vijay','age':40}
>>> dict1['name']
'vijay'

2. Using get() method returns the value for key if key is in the dictionary, else
None, so that this method never raises a KeyError.
Example: For accessing dictionary elements by get().
>>> dict1={'name':'vijay','age':40}
>>> dict1.get('name')
'vijay'

10. Write a Python program to find the factorial of a number provided by the user.
num=int(input("Enter Number:"))
fact=1
if num< 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
fact=fact*i
print("The factorial of ",num," is ",fact)
Output:
Enter Number: 5
The factorial of 5 is 120

11. Describe Tuples in Python.


A tuple is a collection of items which is ordered and unchangeable. Tuples are the sequence or series values of different
types separated by commas (,). Example: tup1=(10,20,30)
12. Explain any four Python's Built-in Function with example.*
• len(list)
It returns the length of the list. • sum(list)
Example: Calculates sum of all the elements of list.
>>> list1 Example:
[1, 2, 3, 4, 5] >>>list1
>>> len(list1) [1, 2, 3, 4, 5]
5 >>>sum(list1)
15
• max(list) • min(list)
It returns the item that has the maximum value in a list It returns the item that has the minimum value in a list.
Example: Example:
>>> list1 >>> list1
[1, 2, 3, 4, 5] [1, 2, 3, 4, 5]
>>> max(list1) >>> min(list1)
5 1

13. Write a python program to input any two tuples and interchange the tuple variables.
# Function to interchange tuple variables
def interchange_tuples(tuple1, tuple2):
return tuple2, tuple1

# Input the first tuple


tuple1 = tuple(input("Enter the first tuple (comma-separated values): ").split(','))

# Input the second tuple


tuple2 = tuple(input("Enter the second tuple (comma-separated values): ").split(','))

# Interchange the tuples


tuple1, tuple2 = interchange_tuples(tuple1, tuple2)

# Display the result


print("After interchange:")
print("Tuple 1:", tuple1)
print("Tuple 2:", tuple2)

14. With neat example differentiate between readline () and readlines ( ) functions in file-handling.
readline(): This method reads a single line from the file and returns it as a string. It moves the file pointer to the next line
after reading. If called again, it will read the subsequent line.
readlines(): This method reads all lines from the file and returns them as a list of strings. Each line is an individual element
in the list. It reads the entire file content and stores it in memory.

15. Explain Module and its use in Python.


Modules are primarily the (.py) files which contain Python programming code defining functions, class, variables, etc. with
a suffix .py appended in its file name. • A file containing .py python code is called a module. • If we want to write a longer
program, we can use file where we can do editing, correction. This is known as creating a script. As the program gets longer,
we may want to split it into several files for easier maintenance. • We may also want to use a function that you’ve written
in several programs without copying its definition into each program. • In Python we can put definitions in a file and use
them in a script or in an interactive instance of the interpreter. Such a file is called a module.
Use of module in python : Code organization: Modules allow you to organize related code into separate files, making it
easier to navigate and maintain large projects. Code reusability: Modules can be imported and reused in multiple programs,
enabling code reuse and reducing duplication. Encapsulation: Modules provide a way to encapsulate code and hide the
implementation details, allowing users to focus on the functionality provided by the module.
Name spacing: Modules help avoid naming conflicts by providing a separate namespace for the names defined within the
module.
16. Explain Bitwise operator in Python with appropriate example.*
1) Bitwise AND (&): Performs a bitwise AND operation on the corresponding bits of two numbers. Each bit of the output
is 1 if the corresponding bits of both operands are 1; otherwise, it is 0.
Example: a = 10 # binary: 1010
b = 6 # binary: 0110
result = a & b
print(result) # Output: 2 (binary: 0010)
2) Bitwise OR (|): Performs a bitwise OR operation on the corresponding bits of two numbers. Each bit of the output is 0
if the corresponding bits of both operands are 0; otherwise, it is 1.
Example: a = 10 # binary: 1010
b = 6 # binary: 0110
result = a | b
print(result) # Output: 14 (binary: 1110)
3) Bitwise XOR (^): Performs a bitwise XOR (exclusive OR) operation on the corresponding bits of two numbers. Each
bit of the output is 1 if the corresponding bits of the operands are different; otherwise, it is 0.
Example: a = 10 # binary: 1010
b = 6 # binary: 0110
result = a ^ b
print(result) # Output: 12 (binary: 1100)
4) Bitwise NOT (~): Performs a bitwise NOT operation on a single operand, which inverts all the bits. It returns the
complement of the given number.
Example:a = 10 # binary: 1010
result = ~a
print(result) # Output: -11 (binary: -1011)

17. Describe 'Self Parameter with example.


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 Person:
def __init__(self, name, age):
self.name = name
self.age = age

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

def change_name(self, new_name):


self.name = new_name

# Creating an instance of the Person class


person1 = Person("Alice", 30)

# Accessing attributes using the instance and displaying information


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

# Changing the name attribute using a method


person1.change_name("Bob")

# Displaying information again to confirm the change


person1.display_info()
# Output: Name: Bob, Age: 30
18. Write a program to show user defined exception in Python.
class MyException(Exception):
def __init__(self, message):
self.message = message
# Function that raises the custom exception
def divide_numbers(a, b):
if b == 0:
raise MyException("Division by zero is not allowed!")
else:
return a / b
# Main program
try:
num1 = int(input("Enter the numerator: "))
num2 = int(input("Enter the denominator: "))
result = divide_numbers(num1, num2)
print("Result:", result)
except MyException as e:
print("Exception:", e.message)

19. Write a Python Program to check if a string is palindrome Or not.


def is_palindrome(string):
# Convert the string to lowercase and remove spaces
string = string.lower().replace(" ", "")

# Check if the string is equal to its reverse


return string == string[::-1]

# Test the function


input_string = input("Enter a string: ")
if is_palindrome(input_string):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")

20. Write a Python Program to accept values from user in a list and find the largest number and smallest number in a
list.
list = []
num = int(input('How many numbers: '))
for n in range(num):
numbers = int(input('Enter number '))
list.append(numbers)
print("Maximum element in the list is :", max(list), "\nMinimum element in the list is :", min(list))

21. Write use of lambda function in python.


The lambda function, which is also called anonymous function. A lambda function can take any number of arguments, but
can only have one expression. Syntax: lambda arguments : expression
Example: x= lambda a,b : a*b
Print(x(10,5)
Output: 50

22. List file operations in Python.


• Opening file (using open() function) • Reading file (using read() function) • Writing file (using write() function)
• Copy files • Delete files (using remove() function) • Closing file (Using close() function)
23. Write a Python program to calculate sum of digit of given number using function.
def sum_of_digits(number):
# Convert the number to a string to iterate over its digits
number_str = str(number)

# Initialize a variable to store the sum of digits


sum_digits = 0

# Iterate over each digit in the string representation of the number


for digit in number_str:
# Convert the digit back to an integer and add it to the sum
sum_digits += int(digit)

# Return the sum of digits


return sum_digits

# Test the function


number = int(input("Enter a number: "))
print("Sum of digits:", sum_of_digits(number))

24. Explain any six set function with example.


1) union():Return a new set containing the union of
4)add(element):This function adds an element to a set.
two or more sets.
Example:fruits = {"apple", "banana", "cherry"}
Example:
fruits.add("orange")
set1 = {1, 2, 3}
print(fruits)
set2 = {3, 4, 5}
# Output: {'apple', 'banana', 'cherry', 'orange'}
union_set = set1.union(set2)
print(union_set) # Output: {1, 2, 3, 4, 5}
5)remove(element):
This function removes an element from a set.
2)Intersection:Intersection operation performed on two sets
Example:numbers = {1, 2, 3, 4, 5}
returns all the elements which are common or in both the sets.
numbers.remove(3)
Example: set1 = {1, 2, 3}
print(numbers) # Output: {1, 2, 4, 5}
set2 = {2, 3, 4}
intersection_set = set1.intersection(set2)
6) clear():
print(intersection_set) # Output: {2, 3}
This function removes all elements from a set, making it
an empty set.
3)Difference:Difference operation on two sets set1 and set2
Example:numbers = {1, 2, 3, 4, 5}
returns all the elements which are present on set1 but not in set2.
numbers.clear()
Example:
print(numbers) # Output: set()
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4}
difference_set = set1.difference(set2)
print(difference_set) # Output: {1, 2, 5}

25. Write any four methods of dictionary.


clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
26. Design a class student with data members : name, roll no., department, mobile no. Create suitable methods for
reading and printing student information.*
class Student:
def __init__(self):
self.name = ""
self.roll_no = ""
self.department = ""
self.mobile_no = ""

def read_student_info(self):
self.name = input("Enter student name: ")
self.roll_no = input("Enter roll number: ")
self.department = input("Enter department: ")
self.mobile_no = input("Enter mobile number: ")
def print_student_info(self):
print("Student Information:")
print("Name:", self.name)
print("Roll Number:", self.roll_no)
print("Department:", self.department)
print("Mobile Number:", self.mobile_no)
# Create an instance of the Student class
student = Student()
# Read and set student information
student.read_student_info()
# Print student information
student.print_student_info()

27. Write basis operations of list


1) Indexing There are various ways in which we can access the elements of a list. List Index: We can use the index operator
[] to access an item in a list. Index starts from 0. So, a list having 5 elements will have index from 0 to 4.
Example: >>> list1=[10,20,30,40,50]
>>> list1[0]
10
>>> list1[4]
50
>>> list1[1:3]
[20, 30]
2) List Slicing The slicing operator returns a subset of a list called slice by specifying two indices, i.e. start and end. Syntax:
List_variable[start_index:end_index]
Example: >>> l1=([10,20,30,40,50])
>>> l1[1:4]
[20, 30, 40]

28. Write Python code for finding greatest among four numbers.
list1 = [ ] Output:Enter number of elements in list: 4
num = int(input("Enter number of elements in list: ")) Enter elements: 10
for i in range(1, num + 1): Enter elements: 20
element = int(input("Enter elements: ")) Enter elements: 45
list1.append(element) Enter elements: 20
Largest element is: 45
29. Describe indentation in Python.
Indentation refers to the spaces at the beginning of a code line. Python indentation refers to adding white space before a
statement to a particular block of code. In another word, all the statements with the same space to the right, belong to the
same code block.
30. With suitable example explain inheritance in Python.*
In inheritance objects of one class procure the properties of objects of another class. Inheritance provide code usability,
which means that some of the new features can be added to the code while using the existing code. The mechanism of
designing or constructing classes from other classes is called inheritance. • The new class is called derived class or child
class and the class from which this derived class has been inherited is the base class or parent class. • In inheritance, the
child class acquires the properties and can access all the data members and functions defined in the parent class. A child
class can also provide its specific implementation to the functions of the parent class.
Syntax:
class A:
# properties of class A
class B(A):
# class B inheriting property of class A
# more properties of class B
Example:
class Animal:
def __init__(self, name):
self.name = name

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

class Dog(Animal):
def speak(self):
print("Dog barks")

class Cat(Animal):
def speak(self):
print("Cat meows")
dog = Dog("Buddy")
cat = Cat("Whiskers")

dog.speak() # Output: Dog barks


cat.speak() # Output: Cat meows

31. What is local and global variables? Explain with appropriate example.*
• 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.
• Local variables: Local variables are those which are initialized inside a function, local variables can be accessed only
inside the function in which they are declared.

Example:
g=10 #global variable g output:
def test(): local variable= 20
l=20 #local variable l Global variable= 10
print("local variable=",l) global variable= 10
# accessing global variable
print("Global variable=",g)
test()
print("global variable=",g)
32. Write python program to illustrate if else ladder.
i = 20
if (i == 10):
print ("i is 10") output:
elif (i == 15): i is 20
print ("i is 15")
elif (i == 20):
print ("i is 20")
else:
print ("i is not present")

print("Largest element is:", max(list1))

33. Explain how try-catch/except block is used for exception handling in python.
• In Python, exceptions can be handled using a try statement. A try block consisting of one or more statements is used by
programmers to partition code that might be affected by an exception. • A critical operation which can raise exception is
placed inside the try clause and the code that handles exception is written in except clause. • The associated except blocks
are used to handle any resulting exceptions thrown in the try block. That is we want the try block to succeed and if it does
not succeed, we want to control to pass to the catch block. • If any statement within the try block throws an exception,
control immediately shifts to the catch block. If no exception is thrown in the try block, the catch block is skipped. • There
can be one or more except blocks. Multiple except blocks with different exception names can be chained together. • The
except blocks are evaluated from top to bottom in the code, but only one except block is executed for each exception that is
thrown. • The first except block that specifies the exact exception name of the thrown exception is executed. If no except
block specifies a matching exception name then an except block that does not have an exception name is selected, if one is
present in the code. • For handling exception in Python, the exception handler block needs to be written which consists of
set of statements that need to be executed according to raised exception. There are three blocks that are used in the exception
handling process, namely, try, except and finally.
1. try Block: A set of statements that may cause error during runtime are to be written in the try block.
2. except Block: It is written to display the execution details to the user when certain exception occurs in the program. The
except block executed only when a certain type as exception occurs in the execution of statements written in the try block.
3. finally Block: This is the last block written while writing an exception handler in the program which indicates the set of
statements that many use to clean up to resources used by the program.
Syntax:
try:
D the operations here
......................
except Exception1:
If there is Exception1, then execute this block.
except Exception2:
If there is Exception2, then execute this block.
......................
else:
If there is no exception then execute this block.
Example:
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print ("Error: can\'t find file or read data")
else:
print ("Written content in the file successfully")
fh.close()
34. What is command line argument? Write python code to add b) two numbers given as input from command line
arguments and print its sum.
Python Command line arguments are input parameters passed to the script when executing them. Almost all programming
language provide support for command line arguments. Then we also have command line options to set some specific
options for the program.
There are many options to read python command line arguments. The three most common ones are:
i) Python sys.argv ii) Python getopt module iii) Python argparse module

Program:
import sys Output: C:\Python34\python sum.py 6 4
x=int(sys.argv[1]) The addition is : 10
y=int(sys.argv[2])
sum=x+y
print("The addition is :",sum)

35. Write python code to count frequency of each characters in a given file.
import collections
import pprint
file_input = input('File Name: ')
with open(file_input, 'r') as info:
count = collections.Counter(info.read().upper())
value = pprint.pformat(count)
print(value)

36. Write python program to read contents of abc.txt and write same content to pqr.txt.
def copy_file_contents(input_file, output_file):
try:
# Open the input file in read mode
with open(input_file, 'r') as f:
# Read the contents of the input file
file_contents = f.read()

# Open the output file in write mode


with open(output_file, 'w') as f:
# Write the contents to the output file
f.write(file_contents)

print("Contents copied successfully from", input_file, "to", output_file)

except FileNotFoundError:
print("File not found!")
except Exception as e:
print("An error occurred:", e)

# Specify input and output file names


input_file = "abc.txt"
output_file = "pqr.txt"

# Call the function to copy contents


copy_file_contents(input_file, output_file)

37. Define class and object in python


Class: A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling
data and functionality together.
Object: An object is an instance of a class that has some attributes and behavior. Objects can be used to access the attributes
of the class.
38. Example module. How to define module.
A module allows you to logically organize your Python code. Grouping related code into a module makes the code easier
to understand and use. A module is a Python object with arbitrarily named attributes that you can bind and reference. Simply,
a module is a file consisting of Python code. A module can define functions, classes and variables. A module can also include
runnable code.
Example The Python code for a module named aname normally resides in a file named aname.py. Here's an example of a
simple module, support.py
def print_func( par ):
print "Hello : ", par
return

To create a module just save the code you want in a file with the file extension .py:
Example Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)

Now we can use the module we just created, by using the import statement:
Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("ABC")

39. Write python program to perform following operations on Set (Instead of Tuple) i) Create set ii) Access set Element
iii) Update set iv) Delete set
# To Create set
S={10,20,30,40,50} output:
# To Access Elements from set
print (S) {50, 20, 40, 10, 30}
#To add element into set using add method
S.add(60) {50, 20, 40, 10, 60, 30}
print(S)
{'B', 50, 20, 'A', 40, 10, 60, 30}
#To update set using update method
S.update(['A','B']) {'B', 50, 20, 'A', 40, 10, 60}
print(S)
#To Delete element from Set using discard() method {'B', 50, 20, 40, 10, 60}
S.discard(30)
print(S) {50, 20, 40, 10, 60}
#To delete element from set using remove() method
S.remove('A')
print(S)
#To delete element from set using pop() method
S.pop()
print(S)

40. How to give single and multiline comment in python


Single line comment: Single-line comments are created simply by beginning a line with the hash (#) character, and they
are automatically terminated by the end of line.
Example: # print is a statement
print(‘Hello Python’)
Multi line comment: Python multi-line comment is a piece of text enclosed in a delimiter (""") Triple quotation marks.
Example: """ Multi-line comment used
print("Python Comments") """
41. Create a parent class named Animals and a child class Herbivorous which will extend the class Animal. In the child
class Herbivorous over side the method feed ( ). Create a object
# parent class
class Animal:
multicellular = True
eukaryotic = True

def breathe(self):
print("I breathe oxygen.")

def feed(self):
print("I eat food.")

class Herbivorous(Animal):
def feed(self):
print("I eat only plants. I am vegetarian.")

herbi = Herbivorous()
herbi.feed()
# calling some other function
herbi.breathe()

Output:
I eat only plants. I am vegetarian.
I breathe oxygen

42. List different modes of opening files in python.


Modes for opening file: • r: open an existing file for a read operation.
• w: open an existing file for a write operation. If the file already contains some data then it will be overridden.
• a: open an existing file for append operation. It won’t override existing data.
• r+: To read and write data into the file. The previous data in the file will be overridden.

43. Write a program to print following


for i in range(1,5):
1
for j in range(1,i+1):
12
print(j,end=' ')
123
print()
1234

44. Explain how to use user defined function in python with example.
• 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
45. Write a program to create class EMPLOYEE with ID and NAME & display its contents.
class employee :
id=0
name=""
def getdata(self,id,name):
self.id=id
self.name=name
def showdata(self):
print("ID :", self.id)
print("Name :", self.name)

e = employee()
e.getdata(11,"Vijay")
e.showdata()

Output:
ID : 11
Name : Vijay

46. Explain membership and assignment operators with example.


Membership Operators: The membership operators in Python are used to find the existence of a particular element in the
sequence, and used only with sequences like string, tuple, list, dictionary etc. Membership operators are used to check an
item or an element that is part of a string, a list or a tuple. A membership operator reduces the effort of searching an element
in the list. Python provides ‘in’ and ‘not in’ operators which are called membership operators and used to test whether a
value or variable is in a sequence.
Assignment Operators: Assignment operators are used in Python programming to assign values to variables. The
assignment operator is used to store the value on the right-hand side of the expression on the left-hand side variable in the
expression. For example, a = 5 is a simple assignment operator that assigns the value 5 on the right to the variable a on the
left. There are various compound operators in Python like a += 5 that adds to the variable and later assigns the same. It is
equivalent to a = a + 5.

47. Explain indexing and slicing in list with example.


List Slicing: Slicing is an operation that allows us to extract elements from units. The slicing feature used by Python to
obtain a specific subset or element of the data structure using the colon (:) operator.
The slicing operator returns a subset of a list called slice by specifying two indices, i.e. start and end.
Syntax: list_variable[start_index:end_index]
This will return the subset of the list starting from start_index to one index less than that of the endind
Example: For slicing list.
>>> l1=([10,20,30,40,50])
>>> l1[1:4]
[20, 30, 40]
>>>l1[2:5]
[30,40,50]

Indexing: An individual item in the list can be referenced by using an index, which is an integer number that indicates the
relative position of the item in the list. There are various ways in which we can access the elements of a list some as them
are given below:
1. List Index: We can use the index operator [] to access an item in a list. Index starts from 0. So, a list having 5 elements
will have index from 0 to 4.
Example: For list index in list.
>>> list1=[10,20,30,40,50]
>>> list1[0]
10
>>> list1[3:] # list[m:] will return elements indexed from mth index to last index
[40, 50]
48. Write a program for importing module for addition and substraction of two numbers.
calculation.py:
def add(x,y):
return (x+y)
def sub(x,y):
return (x-y)

operation.py:
import calculation
print(calculation.add(1,2))
print(calculation.sub(4,2))

Output:
3
2

49. Write a program to create dictionary of student includes their ROLL NO and NAME.
i. Add three students in above dictionary.
ii. Update NAME = ‘Shreyas’ of Roll no = 2
iii. Delete info of Roll no = 1

1)
>>> dict1={1:"Vijay",2:"Santosh",3:"Yogita"}
>>>print(dict1)
{1: 'Vijay', 2: 'Santosh', 3: 'Yogita'}
ii)
>>>dict1[2]="Shreyas"
>>>print(dict1)
{1: 'Vijay', 2: 'Shreyas', 3: 'Yogita'}
iii)
>>>dict1.pop(1)
‘Vijay'
>>>print(dict1)
{2: 'Shreyas', 3: 'Yogita'}

50. Differentiate between list and Tuple.*


Sno LIST TUPLE
1 Lists are mutable Tuples are immutable
2 The implication of iterations is Time- The implication of iterations is comparatively Faster
consuming
3 The list is better for performing operations, A Tuple data type is appropriate for accessing the elements
such as insertion and deletion.
4 Lists consume more memory Tuple consumes less memory as compared to the list
5 Lists have several built-in methods Tuple does not have many built-in methods.

51. Compare list and dictionary.


List Dictionary
The list is a collection of index value pairs like that The dictionary is a hashed structure of the key and value
of the array in C++. pairs.
The list is created by placing elements in [ The dictionary is created by placing elements in { } as
] separated by commas “,” “key”:”value”, each key-value pair is separated by commas “, “
The indices of the list are integers starting from 0. The keys of the dictionary can be of any data type.
The elements are accessed via indices. The elements are accessed via key-value pairs.
The order of the elements entered is maintained. There is no guarantee for maintaining order.
Lists are orders, mutable, and can contain duplicate Dictionaries are unordered and mutable but they cannot
values. contain duplicate keys.
52. Explain decision making statements If-else, if-elif-else with example.
The if-else statement: if statements executes when the conditions following if is true and it does nothing when the condition
is false. The if-else statement takes care of a true as well as false condition.
Syntax: Example: i=20
If condition: if(i<15):
If_Block
print(" less than 15")
else:
else_Block else:
print("greater than 15")

if-elif-else (ladder) statements: Here, a user can decide among multiple options. The if statements are executed from the
top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and
the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
Syntax: Example:
if (condition-1): i = 20
statement if (i == 10):
elif (condition-2): print ("i is 10") # output:i is 20
statements elif (i == 15):
elif(condition-n): print ("i is 15")
statements elif (i == 20):
else: print ("i is 20")
statements else:
print ("i is not present")

53. Explain use of format() method with example.


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

54. Explain building blocks of python.


Character set: All characters that python can recognize. The below table illustrates the Python character set along with
examples.
Tokens: Tokens in python are building blocks of the Python programming language. The role letters and words play for the
English language, Similar to role token play for a python programming language. Python has the following tokens:
1)keywords 2)identifiers
3)literals a)String literals b)Numeric literals c)Boolean Literals d)Special literal None
55. WAP to open a file in write mode and append some content at end of file.
file1 = open("myfile.txt", "w")
L = ["This is Delhi \n", "This is Paris \n", "This is London"] Output:
file1.writelines(L) Output of Readlines after appending
file1.close() This is Delhi
This is Paris
# Append-adds at last This is London
# append mode TodayTomorrow
file1 = open("myfile.txt", "a")

# writing newline character


file1.write("\n")
file1.write("Today")

# without newline character


file1.write("Tomorrow")

file1 = open("myfile.txt", "r")


print("Output of Readlines after appending")
print(file1.read())
print()
file1.close()

56. Illustrate with example method over loading.


• Method overloading is the ability to define the method with the same name but with a different number of arguments and
data types. • With this ability one method can perform different tasks, depending on the number of arguments or the types
of the arguments given. • Method overloading is a concept in which a method in a class performs operations according to
the parameters passed to it.
As in other languages we can write a program having two methods with same name but with different number of arguments
or order of arguments.
Python does not support method overloading, that is, it is not possible to define more than one method with the same name
in a class in Python. This is because method arguments in python do not have a type. A method accepting one argument can
be called with an integer value, a string or a double.
example.
class Demo:
def method(self, a):
print(a)
obj= Demo()
obj.method(50)
obj.method('Meenakshi')
obj.method(100.2)
Output:
50
Meenakshi
100.2

Same method works for three different data types. Thus, we cannot define two methods with the same name and same
number of arguments. It is clear that method overloading is not supported in python but that does not mean that we cannot
call a method with different number of arguments. There are a couple of alternatives available in python that make it possible
to call the same method but with different number of arguments.
57. Explain package Numpy with Example.
• NumPy is the fundamental package for scientific computing with Python. NumPy stands for "Numerical Python". It
provides a high-performance multidimensional array object, and tools for working with these arrays. • An array is a table of
elements (usually numbers), all of the same type, indexed by a tuple of positive integers and represented by a single variable.
NumPy's array class is called ndarray. It is also known by the alias array. • In NumPy arrays, the individual data items are
called elements. All elements of an array should be of the same type. Arrays can be made up of any number of dimensions.
• In NumPy, dimensions are called axes. Each dimension of an array has a length which is the total number of elements in
that direction. • The size of an array is the total number of elements contained in an array in all the dimension. The size of
NumPy arrays are fixed; once created it cannot be changed again. • Numpy arrays are great alternatives to Python Lists.
Some of the key advantages of Numpy arrays are that they are fast, easy to work with, and give users the opportunity to
perform calculations across entire arrays. • A one dimensional array has one axis indicated by Axis-0. That axis has five
elements in it, so we say it has length of five. • A two dimensional array is made up of rows and columns. All rows are
indicated by Axis-0 and all columns are indicated by Axis-1. If Axis-0 in two dimensional array has three elements, so its
length it three and Axis-1 has six elements, so its length is six.
Example:
For NumPy with array object.
>>> import numpy as np
>>> a=np.array([1,2,3]) # one dimensional array
>>> print(a)
[1 2 3]
>>> arr=np.array([[1,2,3],[4,5,6]]) # two dimensional array
>>> print(arr)
[[1 2 3]
[4 5 6]]
>>> type(arr)
<class 'numpy.ndarray'>
>>> print("No. of dimension: ", arr.ndim)
No. of dimension: 2
>>> print("Shape of array: ", arr.shape)
Shape of array: (2, 3)
>> >print("size of array: ", arr.size)
size of array: 6
>>> print("Type of elements in array: ", arr.dtype)
Type of elements in array: int32
>>> print("No of bytes:", arr.nbytes)
No of bytes: 24

58. WAP to illustrate user defined package in python.


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.
# File: main.py
# File: my_package/module1.py # Import modules from the package
def greet(name): from my_package import module1,
return f"Hello, {name}!" module2
def add(a, b): # Use functions from module1
return a + b print(module1.greet("Alice"))
print(module1.add(5, 3))
# File: my_package/module2.py
def multiply(a, b): # Use function from module2
return a * b print(module2.multiply(2, 4))

You might also like