python
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. 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
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
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.
def display_info(self):
print("Name:", self.name)
print("Age:", self.age)
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))
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()
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")
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")
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()
except FileNotFoundError:
print("File not found!")
except Exception as e:
print("An error occurred:", e)
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)
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
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
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'}
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")
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