0% found this document useful (0 votes)
8 views26 pages

Python Programming Basics Explained

The document provides an overview of Python programming concepts, including definitions and differences between various programming elements such as interactive mode, batch mode, local and global variables, classes, objects, instance variables, and methods. It also covers operators, data types, error handling, and the use of tuples and sets. Additionally, it explains advanced topics like method overloading, constructor overloading, and the use of decorators.

Uploaded by

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

Python Programming Basics Explained

The document provides an overview of Python programming concepts, including definitions and differences between various programming elements such as interactive mode, batch mode, local and global variables, classes, objects, instance variables, and methods. It also covers operators, data types, error handling, and the use of tuples and sets. Additionally, it explains advanced topics like method overloading, constructor overloading, and the use of decorators.

Uploaded by

khirodbehera501
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

[Link] is Python?

Ans:-Python is a interprited,high level,genral purpose programming language.

[Link] is the fundamental diffrence between Interactive mode and batcj mode and
explain with steps?
Ans:-
Interactive mode
=================
->Execute the python program line by line.
->This mode is genrally use for testing purpose

steps
-----
->go to start menu select python3.7(64-bit)
->here type the lines
>>> a=100
>>> b=200
>>> a+b
300
>>> a-b
-100
>>> a*b
20000

Batch mode
===========
Execute the entire python program file is called Batch mode.

Steps of Batch Mode


-------------------
go start menu click on IDLE(Integreted Devlpment Enviroment) then select new
option
a=100
b=200
print(a+b)
print(b-a)
print(a*b)

[Link] which situation we have to use none type?


Ans:-
>Intially before taking the data from the user that that variable does not contain
anything.
>If you gie none to the variable then that variabble is none type.

[Link] is the diffrence between local varibale and global variable and explain with
examples?
Ans:-
Local Variable
-----------------
->A varibale which is declared within the function which known as local variable
->Local variable only accessed within the function.
Ex
===
def function1():
a=100 ---->Local variable
b=200 ---->Global variable
print("Addition=",a+b)
In this example a,b are Local variable these are only accessed eithin the
function.

def addition():
a=100
b=200
print("Addition of two number",a+b)
def substraction():
aprint("Substraction",a-b)
a,b are local variable of addition function so a,b are not accessed within
substraction

Global variable
===============
"global variable" variable declared in outside of the function
It can be accessed throughout the module.

Ex
====
Global_variable=1000
def function1():
print("function1(),global variable=",Global_variable)
def function2():
print("function2(),global variable=",Global_variable)
output
========
function1()
function1(),Global variable=1000
function2()
function,Global variable=1000

[Link] is a class?
Ans:-class is a collection of variable and methods.

[Link] is an Object?
Ans:-Object is a physical existance of a clas or a instance of a class.
[Link] is an Instance variable?
Ans:-if data is changing from one object to another object then should use instance
variable.
[Link] a program or write a program for showing the diffrence between,with out
typecasting and with type casting?
Ans
====
without typecasting
=====================
>without typecasting function we can only perform string operation.
>We can not perform arithmetic operation without using type casting
Ex
===
a=input('Enter the value of a')
b=input('Enter the value of b')
print(a+b)

output
======
Enter the value of a10
Enter the value of b20
1020
>here is we are going to add two it will concatinate the value.

with using typecasting


===========================
>With using typecasting function we can convert one type to another type.

Ex
========
int_value=int(input('Enter integer value'))
float_value=float(input('Enter float value'))
string_value=input('Enter string value')
bool_value=bool(input('Enter boolean value'))
complex_value=complex(input('Enter complex value'))
output
=======
Enter integer value10
Enter float value10.2
Enter string valuearjit
Enter boolean valueTrue
Enter complex value1+2j

[Link] is the diffrence between type function and id() function?


[Link] Decimal number system and binary number system?
[Link] is an operator and describe the types of operator in python?
[Link] is the diffrence between Decimal,Binary,Octal and Hexadecimal number
system?
[Link] is Diffrence between Arithmetic operator and Arithmetic Assignment
operator?
[Link] are the diffrence between instance variable and static variables?

Instance Variable Static Variable


================= ====================
1)If the data is changing from one instance to another instance then 1)if the
data is static to all object ot common to all objecct then programmer use static
variable
should be used instance variable.
2)Instance variable prefixed with self. 2)Static variable
prefixed with class name.

3)In memory instance variable create seprate copy,i.e 3)In memory static
variable create single copy for all the object.
number of variable equal to number of number of copies.
E1 Ex
---- ===
Emp_no='E001' Company_name='TCS'
Emp_Name='Raju' Company_ID='TCS001'

4)Instance variable stored within the function 4)static variable


stored outside the function.

5)Instance variable created at the time of object creation 5)static variable


created at the time class loading.

[Link] between Instance method and static method.


Ans:

Instance method static method


=============== ===============
>Instance method use to perform operation on instance variable. >static method use
perform operation on static variable.

>Instance method take "self" as a first parameter. >static method never


take "self" as a first parameter.

>Instance method called through object >static method called


through class name.
Note
-----

static method also called through


object by using decoretor.

[Link] is Bitwise operator?


Ans:
>Bitwise operator perform operation on bit.
>The following are Bitwise operator
i)'and' bitwise operator
ii)'or' bitwise operator7
iii)'XOR' bitwise operator
iv)'not' bitwise operattor
v)>Right shift bitwise operator(<<)
vi)Left shift operator(>>)
vii)One's compliment bitwisse operator(~).
[Link] is the fundamental diffrence between Bitwise operators and other operators
.
[Link] @staticmethod decoretor ans show the situation between @staticmethod
decoretor and without @staticmethod decoretor.
Ans:
i)@staticmethod is decorator to decorate is method as static method.
ii)this method can be called through object.
iii)if the @staticmethod is not applied then it cannot be called through object.
iv)@staticmethod is a system defined method.

[Link] is the diffrence between bitwise operator and bitwise assignment operator?
i)BitWise operator perform operation bits the following are the bitwise operator.
Ex
---
i)Bitwise and operator(&)
ii)Bitwise or operator(|)
iii)Bitwise XOR operator(^)
iv)Right shift operator(<<)
v)Left shift operator(>>)
vi)One's Compliment Bitwise Operator(~)

ii)
>Bitwise-Assignment operator perform two operation one bitwise operation and second
is assignment operation.
>It is also called as short hand assignment operator.
Ex
---
&=
|=
^=
<<=
>>=

[Link] is the practical Diffrence between list and string?


Ans
List
-------
Q)What is list?
Ans:list is a collection elements/object
list is eclosed within [] and separeted with comma
Lsit automatically recognize it's type
Q)What is String?
sequence of charecter is called
in string type it will only take string

[Link] is a tuple and diffrence between list and tuple.


Tuple List
------------------------------------------------------------- ------------
----------------------------
i)Tuple is write-protected i.e immutable object here i)list is not write-protected
i.e mutable data can be changed here.
data cannot be changed.
ii)Tuple accepted key in Dictionaries. ii)list not accepted key in
dictionaries.
Syntax Syntax
----------- --------------
Tuple enclosed within paranthesis list is enclosed within []

[Link] is the diffrence between method overloading vs method overriding?


Method Overloading Method overriding
---------------------------------- -----------------------------
----------
[Link] name same parameter are diffrent ii)Same Method same parameter

[Link] overloading within class ii)Method overriding outside of the


class.

[Link] overloading done with Inheritance. iii)Method overriding done


without Inheritance.

[Link] Method overloading Method operation [Link] Method overriding child class
change the method logic of parent class.
and method logic is same

[Link] is the diffrence between constructor overloading vs constructor overriding?


Constructor Overloading: Constructor Overriding
------------------------------------- ------------------
------------------------
[Link] having same name but diffrent parameter [Link] name same
parameter

[Link] Overloading is within the claass [Link]


Overriding is outside of the class.

[Link] Overloading is done without Inheritance. [Link]


Overriding is done with the class.
[Link] Overloading operation and method logic is same [Link]
Overriding child class change the logic of parent class based on the requirment.

[Link] is the diffrence between paking and un-paking of tuple show practically.
Ans:
Packing
-----------
Packing diffrent object into a tuple is called packing
Ex
----
>>> a=100
>>> b=200
>>> c=300
>>> d=400
>>> t=(a,b,c,d)
>>> t
(100, 200, 300, 400)
Un-packing
-------------------
Dividing the from the elementss from the tuple
Ex
---
>>> t=(10,20,30,40)
>>> a,b,c,d=t
>>> a
10
>>> b
20
>>> c
30
>>> d
40

[Link] to compare the tuples?


Ans:we can compare the tuple by using comparison operator(> < >= <= == !=).
EX
------
>>> a=(10,20,30,40,50)
>>> b=(10,20,30,40,50,60)
>>> a>b
False
>>> a<b
True
>>> a>b
False
>>> a<=b
True
>>> a==b
False
>>> a!=b
True

[Link] is the diffrence between Tuple and nested Tuple.


Ans:
Tuple
---------
Tuple is a collection of element
Ex
----
a=(10,20,30,40)
Nested Tuple
------------------------
One Tuple is existed in another Tuple is called Nested Tuple.

[Link] to call either parent class method or parent class constructor in child
class.
Ans:By using super Method we call parent class method into child class.
(OR)
By using super() Method we can also call parent class constructor into child class

Ex:Let us call parent class Method into child class Method by using super() method.
---
class Parent:
def AO(self):
self.a=int(input('Enter first integer'))
self.b=int(input('Enter seconnd integer'))
print('Addition',self.a+self.b)
print('Substraction',self.a-self.b)
class Child(Parent):
def AO(self):
super().AO()
print('Multiplication:',self.a*self.b)
print('Division',self.a/self.b)
c1=Child()
[Link]()

Let us call parent class Constructor into child class constructor by using super()
method.
Ans:
class Parent:
def __init__(self):
self.a=int(input('Enter first inetger'))
self.b=int(input('Enter second integer'))
print('Addition',self.a+self.b)
print('Substraction',self.a-self.b)
class Child(Parent):
def __init__(self):
super().__init__()
print('Multiplication',self.a*self.b)
print('Division',self.a/self.b)
c=Child()

[Link] is inner class and how to implment it?


Ans:
A class existed in another class is called inner class or Nested class.
class Parent:
def __init__(self):
self.a=int(input('Enter first inetger'))
self.b=int(input('Enter second integer'))
print('Addition',self.a+self.b)
print('Substraction',self.a-self.b)
class Child(Parent):
def __init__(self):
super().__init__()
print('Multiplication',self.a*self.b)
print('Division',self.a/self.b)
c=Child()

[Link] to use tuple as keys in dictionary?


Ans:Tuple can use as a key in dictionary
Ex
---
>>> Dictionaries={1122:'Raju',2233:'Ravi',3344:'Rani',4455:'syama'}
>>> t1=(1122)
>>> d1={t1:'raju'}
>>> d1
{1122: 'raju'}

[Link] is tuple membership test?


Ans:
we can do Tuple membership test by using membership operator.
Ex
>>> Tuple=(10,20,30,40,50)
>>> 50 in Tuple
True
>>> 60 not in Tuple
True
>>> 20 not in Tuple
False

[Link] to find out min and max elements of tuple?


Ans:
min() function return the minimum elment of the tuple max function return the
maximum element of the tuple.
Ex:
>>> Employeesalary=(10000,20000,30000,40000)
>>> min(Employeesalary)
10000
>>> max(Employeesalary)
40000

[Link] to convert list collection into tuple collection?


Ans:we can convert the list collection into tuple collection by using tuple()
function.
Ex
----
>>> list=['Ram','Syam','Raju','Rani']
>>> t1=tuple(list)
>>> list=['Ram','rani','Raju','Ravi']
>>> type(list)
<class 'list'>
>>> t=tuple(list)
>>> type(t)
<class 'tuple'>
>>> t
('Ram', 'rani', 'Raju', 'Ravi')

[Link] to evaluate given input into tuple collection?


Ans:we caan evaluate or convert the given input into tuple by using eval()
function.

[Link] is a doted chart?


Ans:charts represent the data graphically

[Link] many types of error are existed in python and prove with diffrent examples?
Ans:Two type of Error occur in python
[Link] Error
[Link]-time Error
Syntax Error
----------------------
if Programmer write wrong syntax then Syntax Error occur.

Run-time Error
-----------------------
During the period of Execution if any Error occur is call Run-time Error
it may be
i)wrong input
ii)specified file may not be existed
iii)Database connection failure
iv)Network Error
v)Memory is not sufficient
Ex
---
print('Division',10/0)

output
----------
ZeroDivisionError
>>> print 'arjit'
SyntaxError: Missing parentheses in call to 'print'. Did you mean print('arjit')?
[Link] the operation of tuple by using tuple method?
Ans:

len():usinf len() function we can check the length of the tuple


Ex:
----
>>> Tuple=(10,20,30,40)
>>> len(Tuple)
4

count():it return the number of occurances


----------
>>> Tuple=(10,10,20,20,30,30)
>>> type(Tuple)
<class 'tuple'>
>>> [Link](30)
2

[Link] are the features of set?


Ans:
set is a collection objects or element

i)Duplicate elements are not allowed


Ex
-----
>>> set1={10,20,30,40,10,10,10,20}
>>> set1
{40, 10, 20, 30}

ii)Both homogenius and hetro-genius elment are allowed?


Ans:
>>> set1={'Ram','Syan',1,2,3,40}
>>> set1
{1, 2, 3, 40, 'Syan', 'Ram'}

iii)Slicing and indexing are not allowed?


Ex
--
>>> set1={'Ram','Syan',1,2,3,40}
>>> set1
{1, 2, 3, 40, 'Syan', 'Ram'}
>>> set1[0]
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
set1[0]
TypeError: 'set' object is not subscriptable

iv)insertion order is not preserved


Ex
----
>>> set1={10,20,30,40,50}
>>> [Link](60)
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
[Link](60)
AttributeError: 'set' object has no attribute 'insert'

v)set is mutable that data can be changed


Ex
---
>>> Product_Deatils={'Samsung','P0023',45000.00}
>>> Product_Deatils
{45000.0, 'P0023', 'Samsung'}
>>> Product_Deatils.add('Blue')
>>> Product_Deatils
{45000.0, 'P0023', 'Blue', 'Samsung'}

[Link] try "and" and "except" block?


Ans:
try:
----
try block is aslo called 'try' caluse
try block contain the program lines of raised Exception.

except block
----------------
except block is also call 'except' clause
except block contain the Exception handling code(i.e solution to the raised
program)

[Link] Some 5-6 pre-defined exception.


Ans:
-------
The predefined Exception are
[Link] Exception
[Link]
[Link]
[Link]
5KeyboardInterrupt
[Link]

[Link] the neccesity of Exception Handling.


Ans:
if Exception are not hndled properly then

[Link] is named except block.


Ans:the except block is having a name
Ex
---
except ZeroDivisionError:

except ValueError:

except typeError:

30)What is a set practically prove each feature of set?


Ans:
set is a collection ob object/element
set not allowed duplicate element
Both homoge and hetrogenius element are allowed
insertion order is not preserved
set is mutable

i)Duplicate elements are not allowed


Ex
-----
>>> set1={10,20,30,40,10,10,10,20}
>>> set1
{40, 10, 20, 30}

ii)Both homogenius and hetro-genius elment are allowed?


Ans:
>>> set1={'Ram','Syan',1,2,3,40}
>>> set1
{1, 2, 3, 40, 'Syan', 'Ram'}

iii)Slicing and indexing are not allowed?


Ex
--
>>> set1={'Ram','Syan',1,2,3,40}
>>> set1
{1, 2, 3, 40, 'Syan', 'Ram'}
>>> set1[0]
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
set1[0]
TypeError: 'set' object is not subscriptable

iv)insertion order is not preserved


Ex
----
>>> set1={10,20,30,40,50}
>>> [Link](60)
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
[Link](60)
AttributeError: 'set' object has no attribute 'insert'

v)set is mutable that data can be changed


Ex
---
>>> Product_Deatils={'Samsung','P0023',45000.00}
>>> Product_Deatils
{45000.0, 'P0023', 'Samsung'}
>>> Product_Deatils.add('Blue')
>>> Product_Deatils
{45000.0, 'P0023', 'Blue', 'Samsung'}
31)What is a frozenset explain it's feature with proves?
i)frozenset is a collection of object or element.
Ex
----
>>> f=frozenset({10,20,30,40})
>>> f
frozenset({40, 10, 20, 30})

ii)in frozenset duplicate element are not allowed


Ex
----
>>> f=frozenset({10,20,20,30,10})
>>> f
frozenset({10, 20, 30})

iii)Both homogenius and hetrogenius elment are allowed


Ex
----
>>> f=frozenset({'Samsung s7',53000,'P0023'})
>>> f
frozenset({53000, 'P0023', 'Samsung s7'})

iv)Insertion order is not preserved


Ex
----
>>> f=frozenset({'Samsung s7',53000,'P0023'})
>>> f
frozenset({53000, 'P0023', 'Samsung s7'})
>>> [Link](2,'Blue')
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
[Link](2,'Blue')
AttributeError: 'frozenset' object has no attribute 'insert'
v)frozenset is immutable object
Ex
----
>>> f=frozenset({'Samsung s7',53000.00,'Blue'})
>>> f
frozenset({53000.0, 'Blue', 'Samsung s7'})
>>> [Link](34)
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
[Link](34)
AttributeError: 'frozenset' object has no attribute 'add'

32)what are the diffrences between set and frozenset?


Ans:
Set frozenset
--------------------------------------------------------------------- ------
-------------------------
1)set is a collection of mutable object 1)frozenset is immutable
object i.e data cannot be canged
Ex EX:-
---- ----
>>> set={10,20,30,40,50} f=frozenset({'Samsung
s7',54000,'Blue'})
>>> [Link](34) [Link](34)
>>> set AttributeError:'frozenset' object has no
attribute 'add'
{34, 40, 10, 50, 20, 30}

Syntax Syntax
------------- -------------------------
set={element-1,element-2,.................,elment-n} f=({element-1,element-
2,........................,element-3})
33)what is the speciality of finally block explain with example?
Ans:The speciality of finally block is finally block excute always it means the
exception is raised or not raised (OR)The exception is handled or not handled
Ex
-----
Enter first integer:10
Enter second integer:0
Enter valid input
finally block is executed
PS D:\python\Coding> & C:/Python37/[Link] d:/python/Coding/[Link]
Enter first integer:10
Enter second integer:2
Multiplication: 5.0
finally block is executed
PS D:\python\Coding> & C:/Python37/[Link] d:/python/Coding/[Link]
Enter first integer:apple
Enter valid input
finally block is executed
PS D:\python\Coding>

34)what are the features of dictionary.


Ans:
i)Dictionary is a collection of key value pair
Ex
---
>>> Dictionary={1122:'Ravi',2233:'Raju',3344:'Rani',4455:'Syam'}
>>> Dictionary
{1122: 'Ravi', 2233: 'Raju', 3344: 'Rani', 4455: 'Syam'}

ii)Duplicate keys are not allowed but duplicate values are allowed.
>>> Mobile_Details={1122:'Samsung S7',2233:'Lenovo A6',1122:'Sony A6'}
>>> Mobile_Details
{1122: 'Sony A6', 2233: 'Lenovo A6'}

Duplicate values are allowed


>>> Mobile_Details={1122:'Samsung s7',2233:'Lenovo A6',3344:'Samsung S7'}
>>> Mobile_Details
{1122: 'Samsung s7', 2233: 'Lenovo A6', 3344: 'Samsung S7'}

iii)Both homogenius and hetrogenius elements are allowed


Ex
----
>>> Employee_Details={1122:'Ravi',2233:'Raju',3344:'Rani'}
>>> Employee_Details
{1122: 'Ravi', 2233: 'Raju', 3344: 'Rani'}

iv)Inssertion order is preserved.


>>> Employee_Details={1122:'Ravi',2233:'Raju',3344:'Rani'}
>>> Employee_Details
{1122: 'Ravi', 2233: 'Raju', 3344: 'Rani'}
>>> Employee_Details[5566]='Arjit'
>>> Employee_Details
{1122: 'Ravi', 2233: 'Raju', 3344: 'Rani', 5566: 'Arjit'}

v)indexing not allowed in Dictionary


Ex
----
>>> Employee_Details
{1122: 'Ravi', 2233: 'Raju', 3344: 'Rani', 5566: 'Arjit'}
>>> Employee_Details[0:2:1]
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
Employee_Details[0:2:1]
TypeError: unhashable type: 'slice'

vi)Dictionay mutable object


Ex
---
>>> Employee_Details
{1122: 'Ravi', 2233: 'Raju', 3344: 'Rani', 5566: 'Arjit'}
>>> Employee_Details[0:2:1]
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
Employee_Details[0:2:1]
TypeError: unhashable type: 'slice'

35)what is python hashing?


Ans:
------------
Hasing is a operation where unique id number id number is give to mutable object

python Hasing is done by hash() function

So,python hash() function produce 'Hash code (OR) unique id number' to an mutable
object

so,python Hshing means Producing 'Hash code' to an mutable object.

Ex
-----
>>> frozenset=frozenset({10,20,30,40})
>>> hash(frozenset)
-8101661640447970608
36)give 4 Real-time example of dictioonary?

37)give the examples for keys and values methods of dictionary?


Ans:
Keys():keys return the keys of the dictionary
Ex
----
>>> Employee_Details={1122:'Arjit',2233:'Ramesh',3344:'Suresh',4455:'Ranni'}
>>> Employee_Details.keys()
dict_keys([1122, 2233, 3344, 4455])

values():values return the value of the dictionary


-------------
>>> Employee_Details={1122:'Arjit',2233:'Ramesh',3344:'Suresh',4455:'Ranni'}
>>> Employee_Details.values()
dict_values(['Arjit', 'Ramesh', 'Suresh', 'Ranni'])

38)Named except block vs default except block?


Named Except Block: Default Exception
----------------------------- -------------------------------
[Link] handle only specified Exception i).it handle all type of
exception

ii)Individual message is given for named ii)Common message is given for


"Default except block"

iii)Syntax iii)Syntax
---------------- except:
except ZerodivisionError: print('Please enter valid
input')
print(''Divisible by zero is not possible)
except block.
39)How to handle multiple Exception?
To handle multiple exception we have 2 choice.
i)'try' and 'Named except block'
ii)'try' and 'Default except block'

Ex
----
here individual message given for diffrent Exception

try:
i=int(input('Enter first integer:'))
j=int(input('Enter second integer:'))
print('Division:',i/j)
print('********************************')
a=float(input('Enter first float:'))
b=float(input('Enter second float:'))
print('Multiplication:',a*b)
except ZeroDivisionError:
print('A Number is not divisible by zero')
except ValueError:
print('Please Enter valid input')

output:
----------
Enter first integer:10
Enter second integer:0
A Number is not divisible by zero
PS D:\python\Coding> & C:/Python37/[Link] d:/python/Coding/[Link]
Enter first integer:10
Enter second integer:2
Division: 5.0
********************************
Enter first float:apple
Please Enter valid input
PS D:\python\Coding>

Default except block


--------------------------------
try:
i=int(input('Enter first integer'))
j=int(input('Enter secon integer'))
print('Multiplication:',i/j)
print('*************************')
a=float(input('Enter first float'))
b=float(input('Enter second float'))
print('Division',a/b)
except:
print('Please Enter valid input')

output
-----------
Enter first integerapple
Please Enter valid input
PS D:\python\Coding>

39)write one Real-time example on Nested,try,except finally block?


try:
print('Outer try block is executed')
Mobile_number=int(input('Enter Mobile number:'))
try:
print('Inner try block is executed:')
Mobile_price=float(input('Enter Mobile Price:'))
except:
print('Inner except block is executed')
print('Please Enter valid input')
finally:
print('Inner finally block is executed')
del Mobile_price
except:
print('Outer Except block is executed')
print('Please Enter valid input')
finally:
print('Outer finally block is executed')
del Mobile_number

output
----------
Outer try block is executed
Enter Mobile number:112233
Inner try block is executed:
Enter Mobile Price:53000.00
Inner finally block is executed
Outer finally block is executed
PS D:\python\Coding> & C:/Python37/[Link]
d:/python/Coding/Nester_try_except_finally.py
Outer try block is executed
Enter Mobile number:Arjit
Outer Except block is executed
Please Enter valid input
Outer finally block is executed
Traceback (most recent call last):
File "d:/python/Coding/Nester_try_except_finally.py", line 18, in <module>
del Mobile_number
NameError: name 'Mobile_number' is not defined
PS D:\python\Coding> & C:/Python37/[Link]
d:/python/Coding/Nester_try_except_finally.py
Outer try block is executed
Enter Mobile number:9337984334
Inner try block is executed:
Enter Mobile Price:apple
Inner except block is executed
Please Enter valid input
Inner finally block is executed
Outer Except block is executed
Please Enter valid input
Outer finally block is executed

40)How to know the number of key-value-pairs in a dictionary?


Ans:
by using len() function we know the number key-value-pair in a dictionary
Ex
---
>>>
Employee_Details={'Employee_ID':11222,'Employee_name':'Arjit','Employee_Dept':'IT'}
>>> len(Employee_Details)
3

41)How to delete a key-value-pair from the dictionary by specifing the key?


Ans:
by using pop() (OR) del keword we can delete a key-value-pair
Ex
---
by using pop()
------------------------
>>> Employee_Details
{'Employee_ID': 11222, 'Employee_name': 'Arjit', 'Employee_Dept': 'IT'}
>>> Employee_Details.pop('Employee_name')
'Arjit'
>>> Employee_Details
{'Employee_ID': 11222, 'Employee_Dept': 'IT'}

by using del
------------------
>>> Fruit_Dictionary={1122:'Apple',2233:'Banana',3344:'pinaple'}
>>> del Fruit_Dictionary[1122]
>>> Fruit_Dictionary
{2233: 'Banana', 3344: 'pinaple'}

42)How to update the elements of one dictionary into another dictionary?


>>> MobileDictionary1={1001:'Apple',1002:'Lenovo','1003':'RealMe'}
>>> MobileDictionary2={2001:'XIOME',2003:'One plus',3344:'Infinix'}
>>> MobileDictionary1
{1001: 'Apple', 1002: 'Lenovo', '1003': 'RealMe'}
>>> MobileDictionary2
{2001: 'XIOME', 2003: 'One plus', 3344: 'Infinix'}
>>> [Link](MobileDictionary2)
>>> MobileDictionary1
{1001: 'Apple', 1002: 'Lenovo', '1003': 'RealMe', 2001: 'XIOME', 2003: 'One plus',
3344: 'Infinix'}
43)How to display key-value pair in the form of list of tuple
Ans:
by using items() function we can display key-value-pair in the form of list tuple

>>>
Employee_Details={'Employee_ID':1122,'Employee_Naame':'Arjit','Employee_Dept':'IT'}
>>> Employee_Details.items()
dict_items([('Employee_ID', 1122), ('Employee_Naame', 'Arjit'), ('Employee_Dept',
'IT')])
44)what is a Function ?
Ans:function is a set of instruction to perform some operation.

45)what are the diffrences between function and method?

46)How many type of functions are there in python?


Ans:
>There 2 type function are there in python
i)System-Defined function
ii)User-Defined function

System-Defined function:
------------------------------------
Python provide some ready-made function to perform operation,these ready-made
function are called 'System-defined function'
Example of "system-defined-function:print(),type(),id

User-defined-function:
--------------------------------
Ans:
Based on the business requirment,programmer give new function to perform
operation,these new function are called "User-defined-function".
In Banking application:Deposit(),Transfer(),cheque()

47)How many ways are existed to write function?


1)There are 4 ways are existed to write function.
i)Functtion with parameter,with return value.
ii)function with parameter,without return value.
iii)function without paraameter,with return value.
iv)function without parameter,without return value.
49)How many types of Exception are existed in python write two real-time example on
user-defined exception?
Ans:
Two type of Exception are existed in python.
i)System defined Exception.
ii)User-Defined Exception

System-Defined Exception
=======================
>python provide some built-in Exception class,This Exception is also called as pre-
defined Excption.
These pre-defined Exception are called System-Defined Exception.
Ex:ValueError,ZeroDivisionError,NameError

Ex
---
try:
i=int(input('Enter the first integer'))
j=int(input('Enter Seccond Integer'))
print('Division:',i/j)
print('****************************')
a=float(input('Enter first float value'))
b=float(input('Enter second float value'))
print('Multiplication',a*b)
except ZeroDivisionError:
print('Division by zero is not possible')
except ValueError:
print('Please Enter valid input')

output
---------
Enter the first integer10
Enter Seccond Integer0
Division by zero is not possible
>>>
=============== RESTART: D:\python\Coding\[Link] ===============
Enter the first integer10
Enter Seccond Integer2
Division: 5.0
****************************
Enter first float valueString
Please Enter valid input

User-Defined-Exception
=======================
Based on the application requirment,programmer give new Exception
this type of Exception are called User-Defined EXception
Example of user-defined
Exception:ValueNotFoundException,TooldException,ToyoungException
Ex
----
Enter your age18
you will get match detail by your email
>>>
===================== RESTART: D:\python\Coding\[Link] =====================
Enter your age19
you will get match detail by your email
>>>
===================== RESTART: D:\python\Coding\[Link] =====================
Enter your age65
Traceback (most recent call last):
File "D:\python\Coding\[Link]", line 11, in <module>
raise ToOldException('You to old to getting marriage')
ToOldException: You to old to getting marriage
50)in how many ways a function can be returned?
Ans

51)What is a n assert statement give 2 real time examples on assert statements?


Ans:
Bug means error

Debugging means rectifying the error or solving the error.

assertion are used for debugging.

genrally assert statement are used for Devlopment-time error.

so,for Debugging and Devlopment time error,programmer prefer assert statement.


Ex
------
def avg(marks):
assert len(marks)!=0;
return sum(marks)/len(marks)

output
---------
>>> marks=[91,92,89,76,56,67]
>>> avg(marks)
78.5

56)What is a parameter and How many types of Parameter are existed?


Parameter are used to pass the input to function.
1)Default-Parmeter
2)Non-default parameter
3)Keword Parameter
4)Non-Keyword Parameter
5)arbitary Parameter

57)write 4 Real-time examples with 4 ways of function.


1.)function with parameter with return value
here function takes the parameter
parameter take the input data
function perform operation on given input
once operation is done result is ready
result value is returned

Ex
---
def deposit(accoount_number,account_type,Deposit_amount):
if accoount_number==11223344 and account_type=='Saving':
account_balance=500000
account_balance=account_balance+Deposit_amount
return account_balance
else:
return ('Please Enter valid account Details')
output
--------------
>>> deposit(11223344,'Saving',12000)
512000

2)function with parameter withoout return value.


here function takes the parameter
function perform the operation on parameter
Once operation is done result will be ready
result is directly displayed within the function,result will not returned

Ex
-----
def deposit(accoount_number,account_type,Deposit_amount):
if accoount_number==11223344 and account_type=='Saving':
account_balance=500000
account_balance=account_balance+Deposit_amount
print('Account Balance',account_balance)
else:
return ('Please Enter valid account Details')
output
-------------
>>> deposit(11223344,'current',1200)
'Please Enter valid account Details'
>>> deposit(11223344,'Saving',2000)
Account Balance 502000

3)function without parameter with return value


--------------------------------------------------------------------
here function does not take parameter

so input directly take within the function

on given input function perform the operation

once operation is done result will be ready

the result will be returned

Ex
----
def deposit():
account_number=int(input('Enter account Number:'))
account_type=input('Enter account type:')
Withdraw_amount=float(input('Enter Withdraw amount'))
if account_number==1122334455 and account_type=='Saving':
account_balance=500000
account_balance=account_balance-Withdraw_amount
return account_balance
else:
return ('Please enter valid account details')

output
---------
>>> deposit()
Enter account Number:1122334455
Enter account type:Saving
Enter Withdraw amount12000
488000.0

58)what is a file and how many types of files are existed.


Ans:
files is use to store the data permanantly

There are two types


1)Text file
2)Binary file

Text file
------------
Text store the
1)Alphabet(a-z)
2)Number(0-9)
3)symbols(@#$)
->Text file is human understandable file

Binary file
-----------------
Audio,video,images and .Exe files are Binary file

->Binary files are not human understandable,i.e Machine understandbale file.

59)write data to Employee files and student files?


60)what is file handling?
Ans:Performing operation on file is called file handling

61)what is a directory?
Ans:
directory contains the file.

62)what operation we perform on directory?


63)Write a program to return multiple values.
64)write 2 exmple on passing collection to function?
Ans:
Ex
----
def Collection(list1):
sum=0
for i in list1:
sum=sum+i
print(sum)

output
----------
>>> marks=[91,92,93,94,56]
>>> Collection(marks)
426

Ex-2
----------
def Collection(tuple):
sum=0
for i in tuple:
sum=sum+i
print(sum)

output
-----------
>>> mmarks=(90,78,87,76,59)
>>> Collection(mmarks)
390

65)What are the diffrent type of parameter what are the function parametrs?
The following are the diffrent type of parameter

1)Default parameter
-----------------------------
When user does not pass any value then default value will be used.

Ex
----
def Arithmetic(a=10,b=20,c=30,d=40):
print('Addition',a+b+c+d)

output
----------
>>> Arithmetic()
Addition 100
>>> Arithmetic(100,200,300,400)
Addition 1000

Non-Default parameter:
----------------------------------
def Arithmetic(a,b=20,c=30,d=40):
print('Addition',a+b+c+d)

Ex
----
>>> Arithmetic(100)
Addition 190

Keyword Parameter
---------------------------------
Programmer can use parameter name as keyword at the time of function calling.

Ex
----

>>> PersonDetails('E0021','Arjit Biswal',100000,'[Link]@[Link]')


Dear Employee your ID: E0021 your Name: Arjit Biswal your Email: 100000
Employee_salary: [Link]@[Link]
>>> PersonDetails(Employee_ID='E0023',Employee_name='Arjit
Biswal',Employee_email='[Link]@[Link]',Employee_salary=100000)
Dear Employee your ID: E0023 your Name: Arjit Biswal your Email:
[Link]@[Link] Employee_salary: 100000

output
---------
def PersonDetails(Employee_ID,Employee_name,Employee_email,Employee_salary):
print('Dear Employee your ID:',Employee_ID,'your Name:',Employee_name,'your
Email:',Employee_email,'Employee_salary:',Employee_salary)

Arbitary parameter:
----------------------------
Arbitary paraameter is also called as variable length parameter

when user pass n number value to the variable then,we prefer aribitaary parameter.

Ex
---
def Addition(*n):
sum=0
for i in n:
sum=sum+i
print(sum)

output
---------
>>> Addition(1,2,3,4,5,6,7,8,9)
45
66)How to return the multiple values from a function?
Ans:
A function can return the values of another function by Handling function
A function can return the multiple values as possible
EX
-----
def AO(a,b):
return a+b,a-b,a*b,a/b
def display():
print(AO(20,2))

output
---------
>>> display()
(22, 18, 40, 10.0)
67)Diffrence between global variable and local variable?
Ans:

Global variable
-------------------
>Gobal variable accesed throughout the function
>Global variable Decalred Outside of the function

Global_Variable=1000
def function1():
print("In function()1,Global variable=",Global_Variable)
def function2():
print("In function()2,Global variable=",Global_Variable)

output
-------------
>>> function1
<function function1 at 0x0000014FAF82C8B8>
>>> function1()
In function()1,Global variable= 1000
>>> function2()
In function()2,Global variable= 1000

Local Variable
--------------------
Local variable declared within the function.
Local variable accesed within the function.

Ex
----
def Addition():
a=10
b=20
print('Addition:',a+b)
def Substraction():

print('Substraction:',a-b)

output
---------
>>> Addition()
Addition: 30
>>> Substraction()
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
Substraction()
File "D:\python\Coding\[Link]", line 7, in Substraction
print('Substraction:',a-b)
NameError: name 'a' is not defined

68)Write a program to pass Dictionary collection to a function?


Ans:
----
def Collection(Dictionary):
for i in Dictionary:
print(i)

output
------------
>>> marks={'Arjit':98,'Biswajit':67,'Ram':43,'Syam':89}
>>> Collection(marks)
Arjit
Biswajit
Ram
Syam

69)What is a lambda function?


Lambda function is use to reduce the function code

even bigger function can written in single statement by using lambda function

Ex
----
>>> sum=lambda a,b:a+b
>>> sum(100,200)
300

70)Write the program for filter(),map() and reduce operation?


Ans:

filter()
--------------
filter() is used to filter the required data froma group a of element.

Ex
---
>>> list1=[0,1,2,3,4,5,6,7,8]
>>> even=list(filter(lambda x:x%2==0,list1))
>>> even
[0, 2, 4, 6, 8]

map()
----------
mapping the same functionality to all element of the list

>>> list1=[100,200,300,400]
>>> list2=list(map(lambda x:x*x,list1))
>>> list2
[10000, 40000, 90000, 160000]
reduce()
------------
reduce multiple element into single element in a list

Ex
-----

71)what is a module and what are it's type?


72)Define two user ddefined modules and import those modules?
73)How to create alias name to module?
74)How to import our required function only from modle?

You might also like