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

Python Notes (Mphasis Mail)

Uploaded by

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

Python Notes (Mphasis Mail)

Uploaded by

Santhosh Pa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 138

1.

python intro
2. history
3. install python

4. basics:
data type, identifiers, function,
Q: complex data type,type conversion , exponential variable , string data type and string
operations,slice operator ,index type in python , operators

5. data type (list,touple,set,dictionary)


6. input output operations
7. loops and control
8. modules
9. packages
10. Exceptions

11. The Object-Oriented Approach:


Classes, Methods, Objects, and
the Standard Objective
Features; Exception Handling,
and Working with Files

12. Regular expressions


• regex Functions
• Regex Methods
• Regex Metacharacters

13. external libraries


Requests Library (For Rest API Automation)
• Subprocess
• Time
• Powershell script(basic)

14. testing framework


Robotframework
• Robotframework-sshlibrary
• Robotframework-seleniumLibrary

15. data serialization


Parse JSON - Convert from JSON to Python
• Python read JSON file
• Convert from Python to JSON
• Writing JSON to a file
To Do :(duration 10-12 min )
1. Str into
2. String operations(concatenation,repetition,in/ not in)
3. String special characters(\n,\t,\r,\\,\’,\”)
4. Python Builtin function(print,type,id)

str: represent string data type


collection of words,In Python n sequence of characters
>>> p=demo
Traceback (most recent call last):
File "<pyshell#102>", line 1, in <module>
p=demo
NameError: name 'demo' is not defined
>>> p='demo'
>>> p
'demo'
>>> p="demo"
>>> p
'demo'
>>> p="'demo'"
>>> p
"'demo'"
>>> type(p)
<class 'str'>

Note:
in String ',",''',""" quotes are allowed, But '' single quotes are recommended to use.

Q:can we use
p="demo
class"
sol: yes but quotes need to be like multiline (''',""")
demo:
>>> p="demo
SyntaxError: EOL while scanning string literal
>>> class"
SyntaxError: EOL while scanning string literal
>>> p='''demo
class'''
>>> p
'demo\nclass'
>>> p="""demo
class"""
>>>
demo:
-- to print : Hi this "Python" is strong language
>>> x='Hi this "Python" is strong language'
>>> x
'Hi this "Python" is strong language'
>>> "Hi this "Python" is strong language"
SyntaxError: invalid syntax

>>> '''Hi this "Python" is strong language'''


'Hi this "Python" is strong language

In Python strings, the backslash "\" is a special character, also called the "escape"
character. It is used in representing certain whitespace characters.

Exercise:
x=('Hi this is ist character sign\'s example')
y=("Hi this is \\2nd character sign \"example")
z=("""Hi this is 3rd character sign\""" example""")
p=90

print (x)
print (y)
print (z)
print ("Length of x is :" + str(len(x)))

Now TRY TO MODIFY YOUR PROGRAM


import math
x=('Hi this is ist character sign\'s example')
y=("Hi this is \\2nd character sign \"example")
z=("""Hi this is 3rd character sign\""" example""")
p=90
q=("Hi class")
print (x)
print (y)
print (z)
print ("Length of x is :" + str(len(x)))
print ("Square root of " +str(p)
+ "is" + str(math.sqrt(p)))
print (q*3)

Q: how to print q*3 in next line?


@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

Python In Built functions:


Python provides in built function
>>> print(i)-- to print the value of object
>>>type(i) -- to find type of object
>>>id(i)-- to find address of object
Q: Among all data type ,which data type represents objects?
Sol: Everything is an object.

x=10 (internally 10 value is refer to an object,x is the reference var which points to the
object)

Q:what is the address of object 10?In Memory,where this object saved?


sol: >>>id(a)

EXERCISE:
class Example
{
psvm(String[] ar)
{
int p=90 ;
Example e =Example(); }}
Q: What is the size of int ?
sol: 4 bytes
Q: what is the size of object e?
sol: can't define ,because the size of objects depends upon the value given at run time .
Note:
we Can find primitive size ,but object size can't be fixed.

But in python ,everything is an object ,


Int ,float .....all are object ,that’s what size ,range kind of concept is not applicable to
python .

p=90
in python now one object is created with value 10 and p is the reference var for this
object
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@

Exercise:
-- to give value to var:
>>>firstVar=90
>>>firstVar
>>>FirstVar (will show error as its case sensitive )
>>>firstVar=67
>>>firstVar+89
Note:
follow camel case for defining var.
Python is case sensitive

-- to give input at runtime


firstVar=input("Enter First Value")
in cmd mode:
firstVar +90 (will give error as in this fomat var. is automatically convert into string)
note:
but it works directly in GUI mode

----built in fUNCTIONs-------------:
A piece of code which execute some logic.
>>>5**3
or
>>>pow(5,3)

-- to know all built in functions in python :


>>>dir(__builtins__)

-- To know the functionality of each function:

>>>abs (15.567)
>>>len("word length")
>>>max(67,6576,54,2,9898)
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

Q: splitting of string : (need to add in string operations)


x.split(separator)

Example
x="this is Python demo"
y=x.split()
print(y)
for i in y:
print(i)

Q: Try the following :


Quiz:1:
x="20-Jul-2018"
y=x.split('-')
print(y)
for i in y:
print(i)

Quiz:2
x="This is Python Demo class"
y=x.split(3)
print(y)
for i in y:
print(i)
Quiz 3 :
x="This is Python Demo class"
y=x.split(' ',3)
print(y)
for i in y:
print(i)

Quiz 4:
items='marker,board,projector,student,course'
print(items.rsplit(',',2))
print(items.rsplit(',',1))
print(items.rsplit(',',5))
print(items.rsplit(',',0))

Quiz:5difference between split and rsplit


(need to search)...................
items='marker,board,projector,student,course'
y=items.split(',',3)
for i in y:
print(i)
print()
items1='marker,board,projector,student,course'
y=items.rsplit(',',-1)
for i in y:
print(i)
Quiz 6: what is join in python
items=('marker','board','projector','student','course')
x=':'.join(items)
print(x)

Quiz: 7: How to change of a string ?


upper()---> to convet in upper case
lower()
swapcase()
title() ---
capitalize()
Example :
x="This is Pyhon change case understanding"
print(x.upper())
print(x.lower())
print(x.swapcase())
print(x.title())
print(x.capitalize())

Quiz 8: how to check starting and ending part of the string ?


x="This is Pyhon change case understanding"
print(x.startswith('this'))
print(x.endswith('understanding'))

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Escape characters:(\n \t)
----------------------------
>>> s="sumedha\nsaran"
>>> s
'sumedha\nsaran'
>>> print(s)
sumedha
saran
>>> s="sumedha \n saran"
>>> print(s)
sumedha
saran
>>>
>>> s="sumedha\tsaran"
>>> print(s)
sumedha saran
>>>
In python,escape charaters are :
\n \t (horizontal tab)
\r-- go the first position of line
\b \f \' \" \\ \v (vertical tab)

example:
>>> s="Python by "Sumedha saran" is Good"
SyntaxError: invalid syntax
>>>
>>> s="python ny \"sumedha saran\" is good"
>>> print(s)
python ny "sumedha saran" is good
>>> s='python by "Sumedha saran" is good'
>>> print(s)
python by "Sumedha saran" is good
>>> s="python by 'Sumedha saran' is good"
Q: How to resolve this?
>>> s=python by 'ss' is good and his "notes" also good
SyntaxError: invalid syntax
sol: by 2 ways:
way1:
>>> s='''python by 'ss' is good and his "notes" also good'''
way2:
>>> s="""python by 'ss' is good and his "notes" also good"""
>>> print(s)
python by 'ss' is good and his "notes" also good
>>>
also one way is there :
>>> s="""python by 'ss' is good and his "notes" also good"""
>>> print(s)
python by \'ss\' is good and his \"notes\" also good
>>>

but always recommend to go with ''' or """ quotes

Q: what ''(single quotes) invalid?


>>> s='python by '\ss\' is good and his \"notes\" also good'
SyntaxError: invalid syntax
>>> s="python by '\ss\' is good and his \"notes\" also good"
>>> print(s)
python by '\ss' is good and his "notes" also good
>>>
sol>: here all single quotes in middle treated as "symbols only"
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Input and output statement :
Q: read the dynamic data (runtime) from keyboard?
sol: 2 functions are available:(in python2)
1.a= raw_input("Enter input")
2. b=input("Enter number")

NOTE:
raw_input data treated as string type only.we required to use typecasting functions
input data type not considered str type what every type provided we are not required
typecasting.

--->raw_input is not available in python3,only input() function is available

example:
>>> type(input("Enter value"))
Enter value20
<class 'str'>
>>> type(input("Enter value"))
Enter value10.34
<class 'str'>
>>>

Note: input() is always going to take string type only.

example:
x=input("Enter first value")
y=input("Enter second value:")
a=int(x)
b=int(y)
print("sum of ",a ,"and" ,b,"is" ,a+b)

OR

x=int(input("Enter first value"))


y=int(input("Enter second value:"))
print("sum of ",x ,"and" ,y,"is" ,x+y)

The Special advantage in python (The complete program can be written in a single line)
print("Sum =",int(input("Enter first value"))+int(input("Enter second number")))

Q: how to convert the following :


a=input("Enter value")
10
>>>type(a)
<class 'str'>
sol: by using related type conversion function:
int(), float(), bool()

Example:
To read Students details from runtime and print the data:
sid=int(input("Enter Student Enrolment-Id :"))
sname=input("Enter Student Name :")
ssem=input("Enter semester :")
sadd=input("Enter Address :")
marks=float(input("Enter marks :"))
project=bool(input("Enter course status:[True| False]" :))
print("------Student Details----")
print("Student Id :",sid)
print("Student Name :",sname)
print("Student Semester :",ssem)
print("Student Address :",sadd)
print("Student Marks :",marks)
print("Student Project submition status ?",project)

Q: How to read multiple values from runtime in a single line:


input("Enter 2 numbers")
20 40 (these numbers will be separated by space)

Example:
>>> a,b=[int(x) for x in input("Enter 2 Numbers").split()]
Enter 2 Numbers20 80
>>> print(a,b)
20 80
>>>
Note:
By default it split with "space"

Q: How to read 2 float value and separated by , comma


>>> a,b=[float(x) for x in input("Enter 2 Numbers").split(',')]
Enter 2 Numbers60.4,89.88
>>> print("Calculation= ",a*b)
Calculation= 5428.7519999999995
>>>

Q: Enter 4 values and separated by : colon


>>> a,b,c,d=[int(x) for x in input("Enter 4 Numbers").split(':')]
Enter 4 Numbers20:89:67:88
>>> print(a,b,c,d)
20 89 67 88
>>>

@@@@@@@@@@@@@@@@--------------------------------------------------------------
eval()
It evaluate the type on the basis of the values
>>> x=eval("10+20+30")
>>> print(x)
60
>>>

Example :

a=input("Enter value")
print(type(a))

>>>
==== RESTART: C:/Users/dell/AppData/Local/Programs/Python/Python36/pp.py
====
Enter value88
<class 'str'>
>>>

Example:
a=eval(input("Enter value"))
print(type(a))

==== RESTART: C:/Users/dell/AppData/Local/Programs/Python/Python36/pp.py


====
Enter value88
<class 'int'>
>>>

Example:
a=eval(input("Enter value"))
print(type(a))

==== RESTART: C:/Users/dell/AppData/Local/Programs/Python/Python36/pp.py


====
Enter value80.33
<class 'float'>
>>>

Example:
a=eval(input("Enter value"))
print(type(a))
==== RESTART: C:/Users/dell/AppData/Local/Programs/Python/Python36/pp.py
====
Enter valueTrue
<class 'bool'>
>>>

Example:
a=eval(input("Enter value"))
print(type(a))

==== RESTART: C:/Users/dell/AppData/Local/Programs/Python/Python36/pp.py


====
Enter value[20,20,40]
<class 'list'>
>>>

Example:
a=eval(input("Enter value"))
print(type(a))
print(a)

==== RESTART: C:/Users/dell/AppData/Local/Programs/Python/Python36/pp.py


====
Enter value(20,60,56,77,88)
<class 'tuple'>
(20, 60, 56, 77, 88)
>>>

Q: How to print the touple elements one by one?


a=eval(input("Enter value"))
print(type(a))
for p in a:
print(p)

==== RESTART: C:/Users/dell/AppData/Local/Programs/Python/Python36/pp.py


====
Enter value(66,89,90,45,666)
<class 'tuple'>
66
89
90
45
666
>>>

Q: How to read the different types of values in the same line?


x,y,z=[eval(a) for a in input("Enter 3 Numbers separated by comma :").split(",")]
print(type(x))
print(type(y))
print(type(z))

==== RESTART: C:/Users/dell/AppData/Local/Programs/Python/Python36/pp.py


====
Enter 3 Numbers separated by comma :33,"ss",33.3
<class 'int'>
<class 'str'>
<class 'float'>
>>>

Q: What can be the answer?


x,y,z=[eval(a) for a in input("Enter 3 Numbers separated by 3 :").split(3)]
print(type(x))
print(type(y))
print(type(z))

sol;
==== RESTART: C:/Users/dell/AppData/Local/Programs/Python/Python36/pp.py
====
Enter 3 Numbers separated by 3 :66378399
Traceback (most recent call last):
File "C:/Users/dell/AppData/Local/Programs/Python/Python36/pp.py", line 1, in
<module>
x,y,z=[eval(a) for a in input("Enter 3 Numbers separated by 3 :").split(3)]
TypeError: must be str or None, not int
>>>

Q: x,y,z=[eval(a) for a in input("Enter 3 Numbers separated by 3 :").split('3')]


print(type(x))
print(type(y))
print(type(z))

==== RESTART: C:/Users/dell/AppData/Local/Programs/Python/Python36/pp.py


====
Enter 3 Numbers separated by 3 :22324366
<class 'int'>
<class 'int'>
<class 'int'>
>>>
slice operator :
x="Python"
Q: how many characters are in x?
sol:6
Note:
Index starts from 0
so here characters are like -->p(0)y(1)t(2)h(3)o(4)n(5)
demo:
x="Python Practice class"
>>> x="Python Practice class"
>>> x[0]
'P'
>>> x[1]
'y'
>>> x[3]
'h'
>>> x[5]
'n'

--> Index type in Python


Positive(left to right)
negative(right to left)

By default left to right


0 1 2 3 4 5
p y t h o n
-6 -5 -4 -3 -2 -1

>>> x="python"
>>> x[1]
'y'
>>> x[-1]
'n'
>>>
>>> x[10]
Traceback (most recent call last):
File "<pyshell#136>", line 1, in <module>
x[10]
IndexError: string index out of range
Q: why -ve index in Python?
sol: To provide flexibility to the programmer.
e.g: in a room if we have 2 doors so can maintain for in and out way:

slice operator:
--------------
to extract the string with the given range:
x[begin:end]
x="PythonLanguage"
x[1:4]--> this is going to extract from index 0 to 2
Note:
Returns Substr from begin index to end-1index
>>> x="PythonLanguage"
>>> x[1:4]
'yth'
>>> x[0:6]
'Python'
>>> x[1:]
'ythonLanguage'
Note: End range is optional
>>> x[4:]
'onLanguage'
>>> x[:]
'PythonLanguage'
>>> x[-1:-4]
''
>>> x[-5:4]
reason:Begin value should be lower and end value should be higher
>>> x[-4:-1]
'uag'

>>> x[90]
Traceback (most recent call last):
File "<pyshell#149>", line 1, in <module>
x[90]
IndexError: string index out of range

syntax:
x[begin:end]
x[begin:end:step]
>>> x='sumedhasaran'
>>> x[0:8:2]
'smda'
>>> x[0:10:2]
'smdaa'
>>> x[0:10:3]
'sear'

demo:
to repeat the string
>>> x='Python'
>>> x*5
'PythonPythonPythonPythonPython'
>>> len(x)
6
summary:
-----------
str,index,slice,*,len(string)

Note:
Q: What are the fundamental data type of python?
sol: int,float,complex,bool,str(these 5 type are fundamental data type in python)
Q: Is there any explicit "char" data type available inpython ?
SOl: no ,char values are represent by "str"

Q: is "long" data type available in python?


sol: in python2 yes,not in python3
Q: is insertion order preserved?
sol: yes
Q: is duplicates allowed in list?
SOl: yes
Q: hetrogenous(different types) objects are allowed?
Q: null is allowed or not ?
Sol: null is not applicable in python
Q: is the List object growable or not
sol: yes ,increase and decrease , both options are applicable in python
Q: List values can be access by index values and slice operator ?
sol: yes
>>> i[0]
20
>>> i[-1]
>>> i[1:5]
[200, 20, 'ss', None]
>>> j=i*3
>>> j
[20, 200, 20, 'ss', None, 20, 200, 20, 'ss', None, 20, 200, 20, 'ss', None]
note: the above i*3 is not available in java)
>>> type(j)
<class 'list'>
>>> i*i
Traceback (most recent call last):
File "<pyshell#53>", line 1, in <module>
i*i
TypeError: can't multiply sequence by non-int of type 'list'
Note:
the second operand should be number like(i*3)

Q: can list store Huge amount of data?


Sol: yes, but this is not recommended to store crores of data in list because list data
store in python memory,so there should be some limitations,its always
recommended to store data in database persistent storage.

Q: Apart all features of "list" data type, how to use immutability?


sol: touple

Q: diff. b/w list and touple ?


sol:
--List is immutable whereas touple is immutable.
-- representation of data
list=[10,20,30]
touple=(10,20,30)
-- we can't modify the touple
-- 0-256 range limitation not applied for collections(list,touple)

Q: how to represent touple:


sol: ()
x=(20,90,80)

======================================

Q:
list1=[1,2,3,4,5,6,7,8,9]
for x in list1:
if x%2==0:
print(x)

Q:
list1=["p","q","r","s"]
i=len(list1)
for x in range(i):
print(list1[x]," is available at position index :",x, " and -ve index : ",x-i)

Q: important functions of list:


methods

functions

Example:
def fun1():
print("Hi This is fun1() function")
class stu:
def info(self):
print("it's method ,here is differnce between method and function")
fun1()
x=stu()
x.info()

Q: Important functions and methods of List:

1. len(list1) -- > in built function, this function is not present in any class
2. count( ) ---> method
3. index() ---> function (always shows the first occurance)
4. append() --- method
5. insert ()--method
insert(index,element)
6. extend()----- method
7. remove() and pop() --> function
8. reserve()
9. sort()
10. clear() --method

Q: difference len() and count()


Example ;
x=[10,90,30,90,10,89,30,50]
print(len(x))
print(x.count(90))

Q: Examine the code:


x=[10,90,30,90,10,89,30,50]
print(x)
print(len(x))
print("90 is available :",x.count(90)," times")
print("The first occurance of 10 is ",x.index(10))
print(x.index(110))

Q: check the code:


x=[10,90,30,90,10,89,30,50]
y=int(input("Enter the value to search: "))
if y in x:
print(y," is Available and the first occurance is at position :",x.index(y))
else:
print(y," is not available")

Q: How to manipulate a list >


sol: append(element)

Example:
x=[]
x.append(20)
x.append(30)
x.append(50)
print(x)

Q:WAP to add all the lements uptp 200 whichc are divisible by 10
x=[]
for i in range(0,201,10):
x.append(i)
print(x)

Q: Examine the code:


x=[]
for i in range(0,201,10):
x.append(i)
print(x)
x.insert(2,900)
print(x)

Q: What happen :
x=[]
for i in range(0,201,10):
x.append(i)
print(x)
x.insert(400,900)
print(x)

Q: what will be the index value of element "900"


If the specified index is bigger than maxindex then the element "900" will be added
at the end .
if the specified index is smaller than minimum index,then the element 100 will be
added at the begining only
Example:
x=[]
for i in range(0,201,10):
x.append(i)
print(x)
x.insert(400,900)
print(x)
x.insert(-10,100)
print(x)
print("900 element index position is :" ,x.index(900))

Q:
x=[10,20,30]
y=[50,90,100]
x.extend(y)
print(x)
print(y)
p=['a','b','c']
q=['d','e','f']
r=p+q
print()
print(p)
print(q)
print(r)

==================================
Q: Howto traverese in the elements of the list :

Q: differnce between remove() and pop(index) in list?

Q: example on reverse() and sort()


Note:
sort works for unicode in case of alphabate

Q: which mathematical operators can be used in list


+ operator (both should be list objects)
* operator (one should n int)

Q: How to compare list objects:


x=["Aman","Binny","Cia"]
y=["Aman","Binny","Cia"]
z=["AMAN","BINNY","CIA"]
print(x==y)
print(x==z)
print(y==z)
print(x!=z)

NOte :
-- The no. of elements must be equal
-- The order should be same
-- The contents should be same (including case)

Q:
x=["Aman","Binny","Cia"]
y=["Aman","Binny","Cia"]
z=["AMAN","BINNY","CIA"]
print(id(x))
print(id(y))
print(x is y)
print(x[2] is y[2])

Q: examine
x=[90,200,400]
y=[90,80,110,340]
print(x>=y)
Here all elements in x is grater than y (positionwise)

Q:
x=["a","b","c"]
y=["a","b","c"]
print(x>=y)

Q: How to use membership operators in list?


x=[10,30,90,900]
print(10 in x)
print(130 in x)
print(900 in x)
print(103 in x)

Q: x=[10,30,90,900]
print(x)
x.clear()
print(x)

Q: what is nested list >(not working)(28:19)


x=[10,30,40,90,110,[40,80]]
print(x)
print(x[0])
print(x[2][0])
print(x[2][1])

Q: ways to represent a list


x=[[10,20,30],[30,90,400],[490,800,40]]
print(x)
print("Elements row wise: ")
for i in x:
print(i)
print()
print("Elements in Matrix presentation")
for n in range(len(x)):
for m in range(len(x[n])):
print(x[n][m],end=' ')
print()

Q: what is list comprehensions:


list= [expression for x in sequence]
list=[x*x for x in range(1,11)]
list=[expression for x in sequence if condition]

Example: Squares of first 10 numbers?


x=[]
for i in range(1,11):
x.append(i*i)
print(x)

OR
x=[i*i for i in range(1,11)]
print(x)

Q: Examine
x=[i*i for i in range(1,21)]
y=[i for i in x if i%2==0]
print(x)
print(y)

Q: x=[i**2 for i in range(1,21) if(i**2)%2==0]


print(x)

Q: How to find only odd number from list in squareroot


x=[i*i for i in range(1,21)]
y=[i for i in x if i%2!=0]
print(x)
print(y)

OR
x=[i**2 for i in range(1,11) if(i**2)%2!=0]
print(x)

Q:
x=['Delhi','punjab','gujarat','hyderabad','chennai']
i=[y for y in x if len(y)<7]
print(i)

Q:
x=[10,20,30,40]
y=[30,90,20,900]
z=[i for i in x if i not in y]
print(z)
Q:
x="This list topic is very inetersting".split()
print(x)
y=[[i.upper(),len(i)] for i in x]
print(y)

=============================
Q: to check type of character present in the string
isalnum(), isalpha(), isdigit(), islower(), isupper(), istitile(), isspace()

Example:
x=input("Enter any character")
if x.isalnum():
print("This is Numeric number")
if x.isalpha():
print("This is Alphabet character")
if x.islower():
print("This is lower case character")
else:
print("This is upper case character")
else:
print("Its a digit")
elif x.isspace():
print("its a space character")
else:
print("No space special character")
------------------------------------------------------------------------
Q: How to acces elements of tuple :
sol; index or slice

Q: mathematical operator allowed in tuple


sol: + *

Q: tuple imp. functions


count,len,index,sorted,min,max,cmp
Note:
cmp is only applicable in python2

Example
t=(10,20,90,60,90,200,90,10,67)
print(t)
print("90 exist ",t.count(90)," times")
print("Index of first 90 is :",t.index(90))
print(len(t))
y=sorted(t)
print('Sorted tuple:',y)
print("Minimum tuple value is :",min(t))
print("maximum value in tuple :" ,max(t))

Q: Why sort method is not avaialble for tuple:


sol: tuple is immutable
by using sorted() method,tuple sorts the elements into list

reason: to sort element based on natural sorting order

Q: what is tuple packing and unpacking?


packing -> grouping intob single
Q:
x=90
y=89
z=20
t=x,y,z
print(t)

Q:
t=(20,60,80,900)
p,q,r,s=t
print("p=",p,"q=",q,"r=",r,"s=",s)

Q:
t='abcd'
p,q,r,s=t
print("p=",p,"q=",q,"r=",r,"s=",s)

Q:
a=90
b=89
c=100
d=67
t={a,b,c,d}
print(type(t),t)
y=(a,b,c,d)
print(type(y),y)
z=[a,b,c,d]
print(type(z),z)

a=10
b=30
c=90
t=a,b,c
print(t)

Q: tuple comprehension:
Example
x=(i*i for i in range(1,11))
for i in x:
print(i)

QWAP to take tuple of numbers from the keyboard and print sum and square?
t=eval(input("Enter somple tuple of numbers:"))
l=len(t)
sum=0
for x in t:
sum=sum+x
print("The sum =",sum)
print("The Average=",sum/l)

result:
C:\Users\dell\AppData\Local\Programs\Python\Python36>py v18.py
Enter somple tuple of numbers:(10,78,89,90)
The sum = 267
The Average= 66.75

list: tuple
1. [10,20,30] mandatory 1. (10,20,90) brackets are not
mandatory
2. objects are mutable 2. objects are immutable
list[2]=90 t[2]=900 Value Error

Q: difference b/w set,list and tuple

set: (data type)


-- no insertion order
-- no duplicates
-- hetrogenous
-- no index
-- no slicing
-- immutable
-- growable(can increase and decrease based on req.)
Q: diff b/w list and set:
sometimes prog. req. to repersent a group of objects as a single entity ,where duplicates
are allowed but order is imp.

Q: when to choose set data type:


-- when you don't need:
duplicate,order (its not imp. in set)
-- to represent a group of objectsBY USING {}(curly bracket)
-- indexing and slicing is not applicable in set (set internally don't maintain order)
-- mutable
list :
--insertion order preserve
-- duplicates allowed
-- elements represent by [] (square bracket)
-- append method only applicable in list
Example:
>>> S={10,20,30,10,20,30}
>>> S
{10, 20, 30}
Note: set don't allow duplicates
example:
>>> s={10,20,30}
>>> s
{10, 20, 30}
>>> s[0]
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
s[0]
TypeError: 'set' object does not support indexing
Note: internally how elements are stured,there is no guarantee,so order is not importanat
example:
>>> s[1:]
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
s[1:]
TypeError: 'set' object is not subscriptable
Note: slicing not applicable
Q: indexing and slicing is applicable for :
range-- valid
list -- valid
set -- invalid

example
>>> s.add('dhruv')
>>> s
{ dhruv ', 10, 20, 30}
>>> s.remove(20)
>>> s
{' dhruv’, 10, 30}
>>>
Note:
set elements can be increased and decreased based on the requirement.

Q: does set always print orderwise?


sol: no guarantee
>>> s=set()
>>> for i in range(10):
s.add(i)
print(s)
{0}
{0, 1}
{0, 1, 2}
{0, 1, 2, 3}
{0, 1, 2, 3, 4}
{0, 1, 2, 3, 4, 5}
{0, 1, 2, 3, 4, 5, 6}
{0, 1, 2, 3, 4, 5, 6, 7}
{0, 1, 2, 3, 4, 5, 6, 7, 8}
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
>>> May be internally int data type values hashing.
example:
>>> s=('mukesh','ss','kinnu','annu')
>>> s
('mukesh', 'ss', 'kinnu', 'annu')
here this is touple

example:
in case of set :
>>> s={'mukesh','ss','kinnu','annu'}
>>> s
{'annu', 'kinnu', 'mukesh', 'ss'}
operators:
1. Arithmetic operators
2. Relational operators or Comparision operators
3. Logical operators
4. Bitwise operators
5. Assignment operators
6. Special operators
----------------------------
1. Arithmetic operators
(+ - * / % //--floor division operator,**(exponential/power))
Note:
division opertor always generate float value
floor division can work for both int,floor(is the arg are int type so result always be int type)

2. Relational operators or Comparision operators


3. Logical operators
4. Bitwise operators
5. Assignment operators
6. Special operators
example:
>>> a=10
>>> b=2
>>> a+b
12
>>> a-b
8
>>> a*b
20
>>> a/b
5.0
>>> a//b
5
>>> a%b
0
>>> a**b
100
>>>
>>> a=10.5
>>> b=2
>>> a/b
5.25
>>> a//b
5.0
>>>
>>> 10/3
3.3333333333333335
>>> 10//3
3
>>>
Note:
* operator for str type (string multiplication operator)
*one arg must be int type (mandatory)
- (minus operator) is not applicable for string
+ operator applicable for str type also (string concatination operator)
>>> 'sumedha'+3
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
'sumedha'+3

if you want to apply +with string arg., both arg. must be of string type

>>> 'sumedha'+str(10)
'sumedha10'
>>> 'sumedha'+'10'
'sumedha10'
>>> 'sumedha'-10
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
'sumedha'-10
TypeError: unsupported operand type(s) for -: 'str' and 'int'
>>> 'sumedha'*3
'sumedhasumedhasumedha'
>>>
>>> 'sumedha'*'4'
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
'sumedha'*'4'
TypeError: can't multiply sequence by non-int of type 'str'
>>>
exercise:
>>> 'sumedha'*9.3 ---invalid
>>> 3*'ss' -- valid
>>> 10** -2-- valid
>>> (10+3j) **2 -- valid
>>> (10+3j)** (10+4j) --valid
>>> (10+4j)** 10.3-- valid
>>> 5/0-- error
>>> 5%0-- error
>>> 10.9/0--error
>>> 10**0--valid
>>> 0/0-error
>>> 0.0/0--erorr
note:
x/o,x%0,x//0 --- always zero divide error
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@2
relational operators:
<,>,<=,>=
example:
>>> a=10
>>> b=20
>>> print("a>b is",a>b)
a>b is False
>>> print("a>=b is",a>=b)
a>=b is False
>>> print("a<b is",a<b)
a<b is True
>>> print("a<=b is",a<=b)
a<=b is True
>>>
>>> a='sumedha'
>>> b='mukesh'
>>> print("a>b is",a>b)
a>b is True
>>> print("a>=b is",a>=b)
a>=b is True
>>> print("a<b is",a<b)
a<b is False
Note:
its going to consider on the basis of alphabetical order
>>> a='sumedha'
>>> b='sUmedha'
>>> print("a>b is",a>b)
a>b is True
>>> print("a<b is",a<b)
a<b is False
>>> b='sumedha'
>>> print("a>b is",a>b)
a>b is False
>>> print("a<b is",a<b)
a<b is False
>>> its comparing with second character
Note:
Phython can use relational operators with string,it not possible in java.

exercise:
in case of boolean true(1),false(0)
>>> a=True
>>> b=False
>>> print("a>b is",a>b)
a>b is True
>>> print("a<b is",a<b)
a<b is False
>>>
example:
>>> a='True'
>>> b='False'
>>> print("a>b is",a>b)
a>b is True
>>> print("a<b is",a<b)
a<b is False
>>>
example:
>>> a='True'
>>> b=False
>>> print("a>b is",a>b)
Traceback (most recent call last):
File "<pyshell#80>", line 1, in <module>
print("a>b is",a>b)
TypeError: '>' not supported between instances of 'str' and 'bool'
>>>
example:
>>> if(a>b):
print("a is grater than b")
else:
print("a is not greater than b")

a is not greater than b


q: WHY :is used?
sol: its syntax part, to represent the block is started now.as there is no {} or something else

Q: what is block ?
sol: after "if" condition,5 print commands are given ,this is completely comsidered as a
block

if(a>b):
print("a is grater than b")
print("a is grater than b")
print("a is grater than b")
print("a is grater than b")
print("This is separate statement")
else:
print("a is not greater than b")
print("a is not greater than b")
print("a is not greater than b")
print("a is not greater than b")

Q: what is indentation in python?


sol:
if(a>b):
print("a is grater than b")
print("a is grater than b")
print("a is grater than b")
print("a is grater than b")
print("This is separate statement")
else:
print("a is not greater than b")
print("a is not greater than b")
print("a is not greater than b")
print("a is not greater than b")

SyntaxError: invalid syntax


example:
>>> if(a>b):
print("a is grater than b")
print("a is grater than b")
No output after this code

example
>>>if(a>b):
print("a is grater than b")
print("another statement")
---syntax error
to do : as this should give the second statement independenty

example:
>>> if(a>b):
print("a is grater than b")
print("another statement")

SyntaxError: unexpected indent


>>>

--------------
python also follow chaining of relational operators
example
>>> 10<20
True
>>> 10<20<30
True
>>> >>> 10<20<30<40<50>70
False
Note:
in chaining relational operators,if all operators return true,then only the result will be True.

>>> 10<20<35>3
True
-------------------------------------
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
video:13
equality oprator :
==,!=
10==20--false
10 !=20---true
False==False--true
'ss'=='ss'--true
10=='ss'---false(as contents are not same)
Note:
Chaining concept is also applicable with "equality"operator
>>>10==20==30==40---false
>>>10==5+5==3+7==9+1-- true
>>>'a'==97-- false(as char type is not in python
>>>(10+2j)==(10+2j)--true
>>>(10+2j)=='ss'
Q: diff b/w = and ==
a=10(assignment operator)
a==10(comparision operator)
10==10.0---True(here 10 is smaller type,and smaller type is always promoted to bigger
type)
--In case of imcompatible type ...result will be false
>>> 10=='10'---False
>>>1==True-- true as boolean is compatible to int
>>> 'ss'=='SS'---False(CASE sensitive)
>>10.10==10.1 --true(

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@2
logical operator :
and ,or ,not

in case of boolean:
>>True and False ----->False
>>True or False--- True
>>not True-- False

for Non -Boolean type


0 means False,
Non-zero means --true
empty string--false

example:

x and y
if x evaluates to false then result is x otherwise return to y
>>> 0 and 200---0
>>> 10 and 20----20
>>> 1 and 'ss'----'ss'
>>> 0 and 'ss'---0(if the first one is false,then return the first expression)

-------------------------------
x or y
if x is evaluates to true ..returns true otherwise return y

10 or 20 ---10
0 or 20--20
0 or 0 --- 0
---------------------
not x: return only the boolean value.
>>> not 10
False
>>> not 0
True
>>>
>>> not ''
True
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@2

video 14:
shift operator:
<< ---- left shift operator
>> ----- Right shift operator
>>> ------ unsigned right shift operator (this is only in java not in python)

>>> print(10<<2)
40
in Binary format 10 is --> 0000... 0001010
10<<2 means starting 2 zero will be removed
and new 2 place vacant at the end of binary disgits(it will filled with 0)
00010101... .....
now it will be: 000101000
if we convert it in decimal ----32+8=40
NOTE:
left hand side vacant cells sign bit:
+ve numbers ==> 0
-ve numbers --> 1

Q: 10>>2
Q: print(True<<2)
1<<2
in Binary
1= 00000...0001
000...000100

Q: print(True>>2)
1>>2

Q: print(True>>2)
00000...001
0000000
------------------------------------------------------------
Assignment operators:
--------------------------------------------------------------
Assign value to the var.
x=90
assign 90 value to x

x,y,z=10,30,90 (Only in Python)

Q: x,y,z= 10,20( invalid)


because every variable must be initialized in this case.

-----compound operator----------
x+=10 (assignment with some other operator is called compound operator)

example:
>>> p=90
>>> p+=20
>>> p
110
>>> p++
SyntaxError: invalid syntax
>>> ++p
110

++ is not applicable in python ,its treated as (not increment) operator


Note:
Increment and decrement operators are not available in python

Q: compund operators in Python


+=
-=
*=
/=
%=
//=
**=
&=
|=
^=
>>=
<<=
------------------------------------------------
Ternary opertaor
---------------------------------------------------
syntax:
?:
p=(condition)>first value:second value
p=(10<20):30:40

Note :
Ternary operator is available but syntax is different

The right pattern is :


p=firstvalue if condition else second value
p=90 if 20<30 else 40
>>> print(p)
90
>>>
-----------------------------------------------------------------
>>> a=input("Enter First Number:")
By default this is treated as string
typecasting is used :
int(str)
>>> a=int(input("Enter First Number:"))
example
a=int(input("Enter First Number:"))
b=int(input("Enter First Number:"))
min=a if a < b else b
print("minimum value is :",min)

==== RESTART: C:/Users/dell/AppData/Local/Programs/Python/Python36/p11.py ====


Enter First Number:78
Enter First Number:90
minimum value is : 78

SYNTAX:
x=first value if condition1 else second value if condition2 else third value
>>> x=90 if 20>30 else 40 if 50<60 else 70
>>> print(x)
40
>>>
Example:
----------------
a=int(input("Enter First Number:"))
b=int(input("Enter Second Number:"))
c=int(input("Enter Third Number:"))
d=a if a > b>c else b if b>c else c
print("Higest value is :",d)

Example:
a=int(input("Enter First Number:"))
b=int(input("Enter Second Number:"))
c=int(input("Enter Third Number:"))
d=a if a > b and a>c else b if b>c else c
print("Higest value is :",d)

Example:
a=int(input("Enter First Number:"))
b=int(input("Enter Second Number:"))
print("Both are equal" if a==b else "First Number is greater "
if a>b else "Second Number is greater")

----------------------Special Operator ------------------------------


1. identity operators (is /is not)
2. membership operators

Q: What is purpose of identity operators?


sol: For address
x=90
y=90
Q: are these x and y belongs to the same address or not?
sol: only one object "90" is available and x and y both are pointing to the same object.

Example
>>> x=90
>>> y=90
>>> print(x is y)
True
>>>

Example
>>> x=90
>>> y=80
>>> print(x is y)
False
>>>
example:
>>> x="python"
>>> y="java"
>>> print(id(x))
2107313410712
>>> print(id(y))
2107304109872
>>> print(x is y)
False
>>>
Example:
>>> l1=[10,80,90]
>>> l2=[10,80,90]
>>> print(id(l1))
2107314400200
>>> print(id(l2))
2107314400392
>>> print(l1 is l2)
False
>>>
Q: how to check content comparision?
>>> print(l1==l2)
True
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@
Membership operator (in/ not in)
>>> s="Hello Everyone ,This is operators learniing"
>>> print("Hello" in s)
True
>>> print("hello" in s)
False
>>>
>>> print("PYTHON" not in s)
True
>>>
>>> print(" " in s)
True
>>>
Q: How to check multiple things:
sol: with Regular expression
Q: can we use ' ' (single quotes)?
sol:
yes
>>> print('o' in s)
True
>>>
-----------------------------------------------------
Operator precedence
----------------------------------------------------------
() paranthesis
** exponential operator
~,- unary operator
*,/,%,//
+,-
<<,>>
&
^
|
>,<,>=,<=,==,!=
=,+=,-=,*=....
is,is not
in, not in
and
or
>>> 20+3*4
32
>>> (20+3)*4
92
>>>
Q: Highest priority operators:
Unary operators ~p
binary operators p+q
ternary operators 3 arguments
assignment operator
p=90+3/6*7
here all the calculation will go to p ,but after completing the complete calculation.
so assigment operator has the least priority.
example:
>>> p=30
>>> q=20
>>> r=10
>>> s=5
>>> print((p+q)*r/s)
100.0
>>> print((p+q)*(r/s))
100.0
>>> print(p+(q*r)/s)
70.0
>>>
Q: difference between / and //
Q: How python is written is small code compare to java?
sol: because of library(everyting is available in library)
1. Flow controls----------
if
if --- else
if--elif---else
if--elif

-----------------------------------if else statement-------

demo:
import math
x=int(input("Enter the Number: "))
if x<9:
print("Factorial of ",x,"is:",math.factorial(x))
else:
print(x,"is greater than 9")
print("Factorial of ",x,"is:",math.factorial(int(x)))
c=90+90
print("value of ",c,"is",c)

demo:
x=input("ENTER NAME:")
if x=="Ramya":
print("input value is:",x)
elif x=="Mohit":
print("input value is:",x)
elif x=="Smith":
print("input value is:",x)
else:
print("input value is not valid")

Q: how to take inputof 2 values in a single var.

demo:
job=input("Enter Job")
Name=input("Enter Employe Name")
if job=="Manager":
if Name=="Smith":
print("Valid Employee")
else:
print("Employee Name is invalid")
print("Employee Name is: ",Name)
else:
print("Job is invalid")
---------------SYNTAX-----------------------------------
if condition:
statement
else
statement

Example
x=input("Enter your name ")
if x=="python":
print("Good morning ,Welcome in",x,"class")
else:
print("Hi This is not valid name ")
print("Good Bye")

--->if-elif-else
if(x)
{
}
else if(y)
{
}
else if(z)
{
}

Example:
c=input("Enter your course")
if c=="course A":
print("Its IT course")
elif c=="course B":
print("This is Course B")
elif c=="course C":
print("This is Course C")
else:
print("This course is not valid")

----------------------------------------------------------------
video19

Example:
x=eval(input("Enter first value: "))
y=eval(input("Enter Second value: "))
z=eval(input("Enter Third value: "))
if x>y and x>z:
print("highest value is :",x)
elif y>z:
print("highest value is :",y)
else:
print("highest value is :",z)

Note:
Main advantage is that ,this program can take any type of input (because of eval)

Q: WAP to check even or odd


hint: if x%2==0

Example:
WAP to check whether the given number is in between 1 and 1000
x=int(input("Enter your Number ;"))
if x<=1 and x<=1000:
print("The number: ",x ,"is in between 1 and 1000")
else:
print("The number: ",x ,"is in not between 1 and 1000")
Q:
x=int(input("Enter your Number range from 0 to 5"))
if x==0:
print("You have print ZERO")
elif x==1:
print("You have print ONE")
elif x==2:
print("You have print TWO")
elif x==3:
print("You have print THREE")
elif x==4:
print("You have print FOUR")
elif x==5:
print("You have print FIVE")
else:
print("Please enter valid number next time")

Q: How to print a random input into characters:


120 -->one hundred twenty

-------------------------------------------------------------------
Iterative statements :

for loop
while
SYNTAX:

Example:
x="Language"
y=0
for i in x:
y+=1
print(i)
print("Total characters in ",x," = ", y)

Example:
x=input("Enter a string")
y=0
for i in x:
print("The total character in ",y,"index is ",i)
y+=1

Q: can we take y++ instead of y+=1


sol: no, pre/post increment/decrement operators are not available

Q: what will be the output


x=input("Enter a string")
y=0
for i in x:
if y!=0:
print("The total character in ",y,"index is ",i)
y+=1

Q: To print numbers from 0 to 10


for i in range(11):
print(i)

Q: To display even number from 0 to 30


for i in range(31):
if i%2==0:
print(i)

OR
for i in range(0,31,2):
print(i)

OR
---for odd number
for i in range(1,31,2):
print(i)

Q: how to print 20 to1 (descending order)

for i in range(20,0,-1):
print(i)

Q: What can be the output:


i=eval(input("Enter some list elements"))
x=0
for y in i:
x=x+y
print("Total= ",x)

Result:
C:\Users\dell\AppData\Local\Programs\Python\Python36>py v17.py
Enter some list elements(67,89,89)
Total= 245

Q: how to print natural number using WHILE loop


x=1
while x<=10:
print(x)
x+=1

Q: How to find sum of first n number?


x=int(input("Enter some numbers"))
y=0
i=1
while i<=x:
y=y+i
i+=1
print("The sum of first",x,"Numbers is :" ,y)
Q: Examine the code:
x=""
while x!="ss":
x=input("Enter name ")
print("hello ",x,"Welcome to session!!")

Q: make differnce b/w codes


code1:
x=""
y=""
while x!="ss" and y!="saran":
x=input("Enter name ")
y=input("Enter Password ")
print("hello ",x,"Welcome to session!!")

code2:
x=""
y=""
while (x!="ss") or (y!="saran"):
x=input("Enter name ")
y=input("Enter Password ")
print("hello ",x,"Welcome to session!!")

Q: What is infinite loop


x=0
while True:
x=x+1
print("Welcome!!")

Q: what would be the answer


x=0
while False:
x=x+1
print("Welcome!!")

Q: What is nested loop:

for x in range(5):
for y in range(5):
print("x={} and y={}".format(x,y))

Q: Examine the code:


x=int(input("Enter max rows"))
for i in range(1,x+1):
for j in range(1,i+1):
print("*",end=' ')
print()

Note:
Here i represents numbers of rows
j represents the number of *
Q: examine the code:
x=int(input("Enter max rows"))
for i in range(x):
for j in range(x):
print("*",end=' ')
print()

q: Check the code:


y=7
for x in range(y):
print("*"*x,end='\n')
print()

Q: what is code impact:


for x in range(6):
for y in range(x):
print("*"*x)
print()

Q:
x=int(input("Enter the No. of rows :"))
for i in range(1,x+1):
print("*"*x)
Q: x=int(input("Enter the No. of rows :"))
for i in range(1,x+1):
for j in range(1,x+1):
print(j,end=" ")
print()

Q:
x=int(input("Enter the No. of rows :"))
for i in range(1,x+1):
for j in range(1,x+1):
print(i,end=" ")
print()

Q:
x=int(input("Enter the No. of rows :"))
for i in range(1,x+1):
for j in range(1,x+1):
print(chr(65+x-j),end=" ")
print()

Q:
x=int(input("Enter the No. of rows :"))
for i in range(1,x+1):
print(" "*(x-i),(chr(64+i)+" ")*i)
print()

Q:
x=int(input("Enter the No. of rows :"))
for i in range(1,x+1):
print(" "*(x-1),end="")
for j in range(65,64+x+i):
print(chr(j),end=" ")
print()

Q:
x=int(input("Enter the No. of rows :"))
for i in range(1,x+1):
print(" "*(x-i),"*"*(2*i+1))

Q
x=int(input("Enter the No. of rows :"))
for i in range(1,x+1):
print(" "*(x-i),(str(chr(64+i)+" "))*(2*i-1))

Q:
x=int(input("Enter the No. of rows :"))
for i in range(1,x+1):
print(" "*(x-i),(str(chr(64+2*i-1)+" "))*(2*i-1))

Q:
x=int(input("Enter the Number:"))
for i in range(1,x+1):
print(" "*(i-1),end="")
for j in range(1,x+2-i):
print(chr(65+x-i),end=" ")
for k in range(2,x+2-i):
print(chr(65+x-i),end=" ")
print()

Q:
x=int(input("Enter the Number:"))
for i in range(1,x+1):
print(" "*(i-1),end="")
for j in range(0,i):
print(x+j-i,end=" ")
print()
for k in range(1,x):
print(" "*k,end="")
for l in range(1,x+1-k):
print(l+k-1,end=" ")
print()

Q:
x=int(input("Enter the Number:"))
for i in range(1,x+1):
for j in range(1,i+1):
print(x-j,end=" ")
print()
for k in range(1,x+1):
for l in range(1,x+1-k):
print(x-l,end=" ")
print()
Q:
x=int(input("Enter the Number:"))
for i in range(1,x+1):
for j in range(1,i+1):
print(x-i+j-1,end=" ")
print()
for k in range(1,x+1):
for l in range(0,x-k):
print(l+k,end=" ")
print()

Q:
x=int(input("Enter the Number:"))
for i in range(1,x+1):
for j in range(1,i+1):
print(chr(65+x-i),end=" ")
print()
for k in range(1,x+1):
for l in range(0,x-k):
print(chr(65+k),end=" ")
print()

Q:
x=int(input("Enter the Number:"))
for i in range(1,x+1):
for j in range(1,i+1):
print(chr(65+x-j),end=" ")
print()
for k in range(1,x+1):
for l in range(x-k,0,-1):
print(chr(64+l+k),end=" ")
print()

Q:
x=int(input("Enter the Number:"))
for i in range(1,x+1):
for j in range(1,i+1):
print(chr(64+x-i+j),end=" ")
print()
for k in range(1,x+1):
for l in range(1,x-k+1):
print(chr(64+l+k),end=" ")
print()

Q:
x=int(input("Enter the Number:"))
for i in range(1,x+1):
print(" "*(x-i),end="")
for j in range(1,i+1):
print("*",end=" ")
print()

Q:
x=int(input("Enter the Number:"))
for i in range(1,x+1):
print(" "*(x-i),end="")
for j in range(1,i+1):
print(i,end=" ")
print()

Q:
x=int(input("Enter the Number:"))
for i in range(1,x+1):
print(" "*(x-i),end="")
for j in range(1,i+1):
print(j,end=" ")
print()

Q:
x=int(input("Enter the Number:"))
for i in range(1,x+1):
print(" "*(x-i),end="")
for j in range(1,i+1):
print(chr(64+j),end=" ")
print()

Q:
x=int(input("Enter the Number:"))
for i in range(1,x+1):
print(" "*(x-i),end="")
for j in range(1,i+1):
print(j,end=" ")
print()
for p in range(1,x):
print(" "*p,end="")
for q in range(1,x+1-p):
print(q,end=" ")
print()

Q:
while True:
x=int(input("Enter the Number:"))
for i in range(1,x+1):
print(" "*(x-i),end="")
for j in range(1,i+1):
print(x+1,end=" ")
print()
for i in range(1,x+1):
print(" "*i,end="")
for j in range(1,x+1-i):
print(x+1-j,end=" ")
for k in range(2,x+1-i):
print(i+k,end=" ")
print()

Q;
while True:
x=int(input("Enter the Number:"))
for i in range(1,x+1):
print(" "*(x-i),end="")
for j in range(1,i+1):
print(x+1-j,end=" ")
for k in range(2,i+1):
print(x-i+k,end=" ")
print()
for i in range(1,x+1):
print(" "*i,end="")
for j in range(1,x+1-i):
print(x+1-j,end=" ")
for k in range(2,x+1-i):
print(i+k,end=" ")
print()

Q:
x=int(input("Enter a Number"))
for i in range(1,x+1):
print(" "*(x-i),end="")
for j in range(i,i+1):
print(chr(64+i),end=" ")
if i>=2:
print(" "*(2*i-4),end=" ")
for k in range(i,i+1):
print(chr(64+i),end=" ")
print()

Q:
x=int(input("Enter a Number"))
for i in range(1,x+1,2):
for j in range(1,x+1):
print(" "*(2*x-i-j),end="")
for k in range(1,i+j):
print("*",end=" ")
print()
for b in range(1,x+1):
print(" "*(x-2),end="")
print("*"*3)

----------------------------------------------------------
Q: what is transfer statement?
1. break
2. continue
3. pass

---break:
based on some condition if we want to break loop execution.,..
Example:
for x in range(10):
if x==6:
print("some issues.....take a pause!!")
break
print(x)

Example:
x=[10,800,788,90,70]
for i in x :
if i>1000:
print("Sorry its out of your range now !!")
break
print("Ok ,Please process !!",i)

Example:
for x in range(10):
if x%2==1:
continue
print(x)

Q: find the difference between code1 and code2?


-------code1:-----------------
x=[10,800,788,90,70]
for i in x :
if i>700:
print("Sorry ",i," out of your range now !!")
continue
print("Ok ,Please process !!",i)

--------- code2:---------------
x=[10,800,788,90,70]
for i in x :
if i>700:
print("Sorry ",i," out of your range now !!")
break
print("Ok ,Please process !!",i)

Q:
x=[10,20,0,7,30,0,60]
for i in x:
print("100/{}={}".format(x,100/x))

issue:
Error raised due to "Divided by 0"

solution:
x=[10,20,0,7,30,0,60]
for i in x:
if i==0:
print("can't divide with 0")
continue
print("100/{}={}".format(i,100/i))

----------------------syntax---------------------
loop(while or for loop)
st1
st2
..
.
stn
break
st-1
else:
st
Note:
If "break" is not working then some "else" part should take place
(else means loop witout break)

Example:
x=[10,20,70,700,30,0,60]
for i in x:
if i>6000:
print("Sorry..",i,"Can't be processed")
break
print("Process the item ",i)
else:
print("Wooow....All the Items succesfully processed")

Q: what would happen if the following applied ?


1.. if i>600:
2. continue instead of break

Q: difference between for loop and while loop?


execute body for every item in the given sequence: ----> for loop
for x in range(20):
body
execute body as long as some condition is true---> while loop

while condition:
body

Q: How to exit from loop?


sol; break statement

Q: How to skip current iteration and continue for the next iteration?
sol: continue

Q: When else part will be executed?


sol: if loop executed without break.
=============================
Example:
if True:
else:
print("Welcome to session")

---> error will come


Whereever a block required where i dont need to do anything the "pass" statement is
required

Q: What is pass statement?


1. Its and empty statement
2. Its a null statement (;) in java
3. It won't do anything
Example:
def fun1():
print("Hi Everyone")

def fun2():
print("Hi this is fun2")

fun1()
fun2()

Q: what will be the output?


def fun1():
print("Hi Everyone")

def fun2():

fun1()
fun2()

C:\Users\dell\AppData\Local\Programs\Python\Python36>py v17.py
File "v17.py", line 7
fun1()
^
IndentationError: expected an indented block

NOTE:
fun2() is expecting a block .

---> To define "empty block,pass statements is used :


def fun1():
print("Hi Everyone")

def fun2():
pass

fun1()
fun2()

Example:
In java,
class parent{
public void total_courses();
}
class child extends parent
{
}

Q: here we dont know total courses of each student , so this "total_courses() method can't
be implemented here.
This is the reason to use "abstract" functionality in this method.
In java,
class parent{
public abstract void total_courses();
}
Q: Who is going to provide functionality for method "total_courses"?
class parent{
public void total_courses();
}
class child extends parent
{
public int total_courses(){
return 3;
}
}

NOW IN PYTHON:
----------------------------
class a:
def fun1():pass
class b(a):
def fun1():
statment 1
statement .....

Example;
for x in range(100):
if x%10==0:
print(x)
else: pass

Q: what will be the impact ?


for x in range(100):
if x%10==0:
print(x)
else:

Note :
In a loop if we are using an empty block,so "pass" statement is mandatory to complete the
syntax

Q: what is del statement?


del is a keyword in python:

s1='aditya'
s2='tanya'
............slakh='sss'
Q: what can be the impact?
sol: if we keep on creating object like above,a certain point of memory issues will come.
in real time, all the objects will never use ,
Q: can garbage collection manage the remainingobjects?
sol: yes ,by usin "del" keyword.
if any object is no longer required then use "del sn" for making the object garbage
collection.
once garbage collection will come, this object will be immediately destroy.

NOTE:
If u want to delete a variable permanently so that the corresponding object immediately
comes under garbage collection.(use del keyword)
Its highly recommended to use del keyword after variable usage if its not later on required.
Q: How to implement del keyword?
x=10
print(x)
del x

Q: is it possible to use the following


x=10
print(x)
del x
print(x)

sol: it will throw "nameError"

Q: is it valid or not
x=10
y=90
del x,y
print(x)

Q: how to remove particular index


s1="sumedha"
del s[2]
Is it valid or not?

Q: del vs. None

Assume we have string si='AA' and s2='bb' along with their ccorresping referenvce objects
"AA" and'BB", Now this s1 variable and its corresponding object is also not required?
then use --> del s1 (means s1 is not required and corresponding object is also not required)
print(s1) ---error
But if you have requirement to use s1 in future though the corresponding object is not
required.
s1=none

Q: What would be the output


x=10
y=90
del x
y=None
print(y)

SOl: None

Q: What would the output:

x=10
y=10
z=10
del x
print(y,z)

Note:
x,y,z are pointing to the same object in memory.
Q: if you delete on var(del x) ,is the object eligible for garbage collection or not?
sol: if you remove only x ,the corresponding object will not go for garbage collection ass this
object is used by y and z also.
x="AA"
y="AA"
z="AA"
print(id(x),id(y),id(z))
del x
print(id(y),id(z))

Q: what would heppen if we add the line at the end ?


print(id(x),id(y),id(z))

Q: Python flow control related concept :


if
if --else
if--elif--else
if --elif
while
for
break
continue
pass
del

Q: control flow:
1. conditional statement (if ,if--elif, if --elif--else
2. Transfer statement (break,continue,pass)
3. Iterative statement (for,while)
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@
Q: What data type is commonly used in any language frequently>
sol: string
Note:
if there are 100 objects , out of the 80-90% are string objects and 10-20% are non-string
objects
Example :
In an application (voter registration)
Name
Age
DOB
Father Name
Mother Name
Address:
Hno:
street
district
state
Adhaar No:
Identity mark1:
Identity mark2:
Q: How many string and non string object in the voter application?

Q: x='a'
in c ,java,the type of x===> char
in Python (char is not available)
a single character with single character also treated as "str" type only.

Example:
x='a'
print(type(x))

Q: what would the output


x='Hi ,it's a demo session'
print(x)
sol: Invalid syntax
The right way is as follows:

x="Hi ,it's a demo session"


print(x)

OR
x='Hi ,it\'s a demo session'
print(x)

Q: try to do:
x="Hi ,it's a demo session"
print(x)
x='Hi ,it\'s a demo session'
print(x)
x="Hi ,it\"s a demo session"
print(x)
x='Hi ,it\"s a Theory \' and " practice session '
print(x)
x='''Hi ,it\"s a Theory \' and " practice session '''
print(x)

Q: How to access charcters of the string?


sol: by using index
by using slice operator

Example:
x="python"
print(x[0])
print(x[1])
print(x[-1])

Q: what would the output


print(x[9])

Q: WAP to accept a string at runtime and print all the characters along wih their index
values

x=input("Enter any string ")


n=0
for i in x:
print("The character present at positive index: {} and the negative index:{} is
:{}".format(n,n-len(x),i))
n=n+1

Q: what will be the impact if we dont give input string at runtime ?


sol: now x will be null , and nithing will go to for loop so that (n=n+1) will not procvesss
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Example
x='0123456789000'
print(x[0:7:1])
print(x[0:7:2])
print(x[0:7])
print(x[0:])
print(x[::])
print(x[:: -1])

NOTE:
from begin index to end -1 index and everytime increment by 1

Summary:
x[begin:end:step]
steps value can be either +ve or -ve
if +ve then it should be forwrd direction(left to right)
if -ve then it should be backward direction(Right to left)

if +ve forward direction from begin to end-1


if -ve backward direction from egin to end+1

Q: Examine the following


x='01234567890'
print(x[2:8:1]) --> 2 to 7
print(x[2:8:-1])
print(x[-1:-6:-1])
print(x[-1:-6:+1])
print(x[2:-5:1])
print(x[ :-0:-1])-- what is the default value for begin?

x[begin:end:step]
step---> +ve forward direction from begin to end -1
-ve backward direction from begin to end +1
In Forward Direction:
--------------------------
default value for begin :0
default value for end: length of the string
default value for step: 1

In Backward Direction :
------------------------------
default value for begin index: -1
default value for end: -(length of string +1)

print(x[-1:6:-1])

print(x[ :0:-1])

Q: what is the output:


print(x[: 0:-1])
x='0123456789' ---> from 9 to 1

NOTE:
step is in -ve --> direction will be backward (it should move from begin to end+1)
there is no begin value ---> so default begin value is -1
what is end index: 0
-1 to 0+1---> -1 to 1
sol: 987654321

Q:
print(x[-5:0:-9])

step is -ve ---> backward direction (begin to end+1)


backward direction from -5 index to 1 index and everytime it will be increment by 9
characters:
here if we start from -5 to left direction and jumps 9 stpes so all the characters are
completed.
in that case,5 is only the answer

Q:
print(x[2:-1:-1])
steps will be backward
begin to end+1
2 to 0 (-1+1=0)
sol ' '
print(x[2:-4:-1])
sol ' '

------------while loop
>>> x=10
>>> while x<15:
print(x)
x=x+1
10
11
12
13
14
>>>

demo:
import math
a=1
s=0
print('ENter any Number to add the sum')
print('Enter 0 to exit from Program')
while a!=0:
print('current value ',s)
a=float(input('Enter any value: '))
s =math.sqrt(a)
print('Square root of ',a,"is",s)

demo:
>>> x=[2,9,8,12,89,76,22,88]
>>> for y in x:
print(y)

2
9
8
12
89
76
22
88
>>>
Q: difference between while and for loop

common activity

1. WAP to find area of circle , take radius at runtime.


2. Calculate the multiplication and sum of two numbers,Take input values
at runtime
3. craete a function named "fun1" which takes 2 parameters at execution time
Given two integer numbers return their "Addition" only if the product is greater
than 500, else return their "product".

4. do the following step by step


Hint: import random package
a. print a random number between 0 to 1
b. print a random number between 0 to 20
c. Generate n random numbers between 10 and 30 ad also mention "n"
Note:
how many number to generate, mention in place of "n"

5. Write a program to iterate the first 10 numbers and in each iteration, print the
sum of the current and previous number.

Hint :
expected solution
--->result number added with previous number
Current Number 0 Previous Number 0 Sum: 0
Current Number 1 Previous Number 0 Sum: 1
Current Number 2 Previous Number 1 Sum: 3
Current Number 3 Previous Number 2 Sum: 5
Current Number 4 Previous Number 3 Sum: 7
Current Number 5 Previous Number 4 Sum: 9
Current Number 6 Previous Number 5 Sum: 11
Current Number 7 Previous Number 6 Sum: 13
Current Number 8 Previous Number 7 Sum: 15
Current Number 9 Previous Number 8 Sum: 17

6. how to clear screen of IDLE environment

Activity-1
group-1
bytearray(),bytearray() with no arguments,startswith(),swapcase()
encode() ,expandtabs(),replace(),rfind(),rindex(),translate()
String partition(),split(),splitlines()
group-2
disalnum() ,zfill(),join(),maketrans(),partition()
len(),ascii(),isnumeric(),isspace(),istitle(),swapcase()
group-3
bytearray() with string and mutability,bytearray() with iterable
,index(),isidentifier(),islower()
String bool(),rpartition(),find(),format(),format_map(),rstrip()
group-4
capitalize(),casefold(),center(),endswith(),expandtabs()
String casefold(), count(),rjust(),rpartition(),rsplit()
group5:
what is module
how to create a new module in python
how to use module in a python program
hint:
https://www.youtube.com/watch?v=sKYiQLRe254
https://www.programiz.com/python-programming/modules

demo1: creating array


import array as arr
# creating an array with integer type
a = arr.array('i', [1, 2, 3])

# printing original array


print("The new created array is : ", end=" ")
for i in range(0, 3):
print(a[i], end=" ")
print()

# creating an array with float type


b = arr.array('d', [2.5, 3.2, 3.3])

# printing original array


print("The new created array is : ", end=" ")
for i in range(0, 3):
print(b[i], end=" ")

Q: What is NumPy?
NumPy is a Python library used for working with arrays.

It also has functions for working in domain of linear algebra, fourier transform, and
matrices.

NumPy was created in 2005 by Travis Oliphant. It is an open source project and you
can use it freely.

NumPy stands for Numerical Python.

Q: Why Use NumPy?


In Python we have lists that serve the purpose of arrays, but they are slow to
process.

NumPy aims to provide an array object that is up to 50x faster than traditional
Python lists.
The array object in NumPy is called ndarray, it provides a lot of supporting functions
that make working with ndarray very easy.

Arrays are very frequently used in data science, where speed and resources are very
important.

Data Science: is a branch of computer science where we study how to store, use and
analyze data for deriving information from it.

Q: Why is NumPy Faster Than Lists?


NumPy arrays are stored at one continuous place in memory unlike lists, so
processes can access and manipulate them very efficiently.

This behavior is called locality of reference in computer science.

This is the main reason why NumPy is faster than lists. Also it is optimized to work
with latest CPU architectures.

Q: Which Language is NumPy written in?


NumPy is a Python library and is written partially in Python, but most of the parts
that require fast computation are written in C or C++.

Q: how to install numpy ?


C:\Users\GS>py -m pip install numpy

C:\Users\GS>py -m pip install numpy --upgrade pip

C:\Users\GS>py -m pip --version

C:\Users\GS>py -m pip install pandas

C:\Users\GS>py -m pip install matplotlib


Q: how to install numpy in pycharm?
file --settings --python project--interpreter--install nupy package

demo:
import numpy

arr = numpy.array([1, 2, 3, 4, 5])

print(arr)
=========================================
Q: NumPy Array Indexing
Access Array Elements
Array indexing is the same as accessing an array element.

You can access an array element by referring to its index number.

The indexes in NumPy arrays start with 0, meaning that the first element has index 0,
and the second has index 1 etc.

import numpy as np

arr = np.array([1, 2, 3, 4])

print(arr[0])
print(arr[2])
print(arr[2] + arr[3])

Q: how to access 2D array :


demo:
import numpy as np

arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])

print('2nd element on 1st dim: ', arr[0, 1])


#to find 5th element
print('5th element on 2nd dim: ', arr[1, 4])

Q: 3D array
import numpy as np

arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])

print(arr[0, 1, 2])

Q: Print the last element from the 2nd dim:

import numpy as np

arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])

print('Last element from 2nd dim: ', arr[1, -1])

======================================================
==
Q: NumPy Array Slicing

Slicing arrays
Slicing in python means taking elements from one given index to another given
index.

We pass slice instead of index like this: [start:end].

We can also define the step, like this: [start:end:step].

If we don't pass start its considered 0

If we don't pass end its considered length of array in that dimension

If we don't pass step its considered 1


demo:
import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])

print(arr[1:5])
#Slice elements from index 4 to the end of the array:
print(arr[4:])

#Slice elements from the beginning to index 4 (not included):


print(arr[:4])
#Slice from the index 3 from the end to index 1 from the end:
print(arr[-3:-1])

#Return every other element from index 1 to index 5:


print(arr[1:5:2])

#Return every other element from the entire array:


print(arr[::2])
==========================slicing
2D==========================
Q: From the second element, slice elements from index 1 to index 4 (not included):
import numpy as np

arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

print(arr[1, 1:4])
#From both elements, return index 2:
print(arr[0:2, 2])
#From both elements, slice index 1 to index 4 (not included), this will return a 2-D
array:
print(arr[0:2, 1:4])

======================================================
==================
=================================================
Q: Iterating Arrays
Iterating means going through elements one by one.

As we deal with multi-dimensional arrays in numpy, we can do this using basic for
loop of python.

If we iterate on a 1-D array it will go through each element one by one.

import numpy as np

arr = np.array([1, 2, 3])

for x in arr:
print(x)

Q: 2D iterating
import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])

for x in arr:
print(x)

Q: Iterate on each scalar element of the 2-D array:


import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])

for x in arr:
for y in x:
print(y)

Note:
If we iterate on a n-D array it will go through n-1th dimension one by one.
To return the actual values, the scalars, we have to iterate the arrays in each
dimension.

Q: In a 3-D array it will go through all the 2-D arrays.


import numpy as np

arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])

for x in arr:
print(x)

Note:
To return the actual values, the scalars, we have to iterate the arrays in each
dimension.

Q: Iterate down to the scalars:


import numpy as np

arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])

for x in arr:
for y in x:
for z in y:
print(z)

===================================================
Q: Shape of an Array
The shape of an array is the number of elements in each dimension.

Get the Shape of an Array


NumPy arrays have an attribute called shape that returns a tuple with each index
having the number of corresponding elements.

demo: Print the shape of a 2-D array:


import numpy as np

arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])


print(arr.shape)

Note:
returns (2, 4), which means that the array has 2 dimensions, and each dimension has
4 elements.

Q: Create an array with 5 dimensions using ndmin using a vector with values 1,2,3,4
and verify that last dimension has value 4:

import numpy as np

arr = np.array([1, 2, 3, 4], ndmin=5)

print(arr)
print('shape of array :', arr.shape)

Q: Reshaping arrays
Reshaping means changing the shape of an array.

The shape of an array is the number of elements in each dimension.

By reshaping we can add or remove dimensions or change number of elements in


each dimension.

Reshape From 1-D to 2-D

Q: Convert the following 1-D array with 12 elements into a 2-D array.

The outermost dimension will have 4 arrays, each with 3 elements:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

newarr = arr.reshape(4, 3)
print(newarr)

Q: Convert the following 1-D array with 12 elements into a 3-D array.

The outermost dimension will have 2 arrays that contains 3 arrays, each with 2
elements:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

newarr = arr.reshape(2, 3, 2)

print(newarr)

Q: Can We Reshape Into any Shape?(this program is only for understanding)


Yes, as long as the elements required for reshaping are equal in both shapes.

We can reshape an 8 elements 1D array into 4 elements in 2 rows 2D array but we


cannot reshape it into a 3 elements 3 rows 2D array as that would require 3x3 = 9
elements.

Try converting 1D array with 8 elements to a 2D array with 3 elements in each


dimension (will raise an error):

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])

newarr = arr.reshape(3, 3)

print(newarr)

Q: return copy or view


import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])

print(arr.reshape(2, 4).base)
sol: returns the original array, so it is a view.

Q: Unknown Dimension
You are allowed to have one "unknown" dimension.

Meaning that you do not have to specify an exact number for one of the dimensions
in the reshape method.

Convert 1D array with 8 elements to 3D array with 2x2 elements:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])

newarr = arr.reshape(2, 2, -1)

print(newarr)
Note: We can not pass -1 to more than one dimension.

Activity :
try the link:
https://www.geeksforgeeks.org/how-to-convert-images-to-numpy-array/
https://www.pluralsight.com/guides/importing-image-data-into-numpy-arrays

Activity:
https://www.geeksforgeeks.org/python-broadcasting-with-numpy-arrays/

Exception Handling
When an error occurs, or exception as we call it, Python will normally stop and
generate an error message.

The try block lets you test a block of code for errors.

The except block lets you handle the error.

The finally block lets you execute code, regardless of the result of the try- and except
blocks.

demo1:
a = [1, 2, 3]
try:
print("Second element = %d" % (a[1]))

# Throws error since there are only 3 elements in array


print("Fourth element = %d" % (a[3]))

except:
print("An error occurred")

Q: Catching Specific Exception


A try statement can have more than one except clause, to specify handlers for
different exceptions.
Syntax:
try:
# statement(s)
except IndexError:
# statement(s)
except ValueError:
# statement(s)

demo:
# Program to handle multiple errors with one
# except statement
# Python 3
def fun(a):
if a < 4:
# throws ZeroDivisionError for a = 3
b = a / (a - 3)

# throws NameError if a >= 4


print("Value of b = ", b)

try:
fun(3)
fun(5)

# note that braces () are necessary here for


# multiple exceptions
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
except NameError:
print("NameError Occurred and Handled")

Q: Try with Else Clause


In python, you can also use the else clause on the try-except block which must be
present after all the except clauses. The code enters the else block only if the try
clause does not raise an exception.

def AbyB(a, b):


try:
c = ((a + b) / (a - b))
except ZeroDivisionError:
print("a/b result in 0")
else:
print(c)

# Driver program to test above function


AbyB(2.0, 3.0)
AbyB(3.0, 3.0)

Q: Finally Keyword in Python


Python provides a keyword finally, which is always executed after the try and except
blocks. The finally block always executes after normal termination of try block or
after try block terminates due to some exception.
Syntax:

try:
# Some Code....

except:
# optional block
# Handling of exception (if required)

else:
# execute if no exception

finally:
# Some code .....(always executed)

demo:
try:
k = 5//0 # raises divide by zero exception.
print(k)

# handles zerodivision exception


except ZeroDivisionError:
print("Can't divide by zero")

finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
Q: Raising Exception
The raise statement allows the programmer to force a specific exception to occur.
The sole argument in raise indicates the exception to be raised

demo:
try:
raise NameError("Hi there") # Raise Error
except NameError:
print ("An exception")
raise # To determine whether the exception was raised or not

demo:
x = -1

if x < 0:
raise Exception("Sorry, no numbers below zero")

demo:
x = "hello"
if not type(x) is int:
raise TypeError("Only integers are allowed")

demo:
try:
age= 10
print("Age is:")
print(age)
if age<0:
raise ValueError
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)
except ValueError:
print("Input Correct age.")

-->self reference
https://www.programiz.com/python-programming/exception-handling

https://www.pythonforbeginners.com/exceptions/user-defined-exceptions-in-
python

--> inbuilt exception


https://www.python-ds.com/python-3-built-in-exceptions

-->argparse
https://zetcode.com/python/argparse/
to do:
1. dictionary
2. constant var
3. eval

constants:
-------------
the fixed value, never change
in java:
final int x=10;
x=100;-- compiler will show error

in plsql
v1 constant number:=10;

In Python:
>>> const x=10
SyntaxError: invalid syntax
>>> constant var is not applicable in python

==================================
Q: when to go for dictionary :

Note :
List ,tuple ,set ---> only hold the individual object

our requirement is to get a (key-value) pairs---- then to choose dictionary


example:
rollno-name
mobile-address
adhaarNo-- address

Note:
duplicate values are not allowed in keys ,duplicates are allowed in values
101- richa
102-ss
103- richa

In Hetrogenous order,key and value can have duplicate values

Insertion order is not preserve

dictionary is mutable (can add or remove)


dictionary is dynamic( can be increase or decrease as per requirement)
Indexing,slicing is not applicable with dictionary

Q: set vs. dict

Q: How to create dict?


-- to create empty dictionary --> d={} or d=dict()
-- how to add key values in empty dictionary?
d[key]=value

Example;
d={}
type(d)
d[101]='python'
d[102]='smith'
d[103]='john'
d[104]='jim'
print(d)

Q:
d={'x':'richa','y':'diya','c':'tia','d':'rima'}
print(d)

Q: How to access elements from the dictionary?


d={'x':'richa','y':'diya','c':'tia','d':'rima'}
print(d[p])

Note: error will be there

In python2:
-------
d.hash_key ---> it returns boolean
but not available in python 3

Q: WAP to enter name and name %in dictionary and display info.
rec={}
n=int(input("Enter number of Students:"))
i=1
while i<=n:
name=input("Enter Student Name :")
marks=input("Enter % of marks:")
rec[name]=marks
i=i+1
print("Name of Student","\t","% of Marks")
for x in rec:
print("\t",x,"\t\t",rec[x])

========================

Example:
a=eval(input("Enter dictionary"))
b=sum(a.values())
print("The total of all values in Dictionary;",b)

C:\Users\dell\AppData\Local\Programs\Python\Python36>py v18.py
Enter dictionary{'1':200,'2':700,'3':600,'4':290}
The total of all values in Dictionary; 1790

Q:
list1=[10,20,30,90]
a=sum(list1)
print(type(list1))
print(list1)
print("The total of list1 is ",a)
print()
t=(10,20,30,90)
a=sum(t)
print(type(t))
print(t)
print("The total of Tuple is ",a)

s={10,20,30,90}
print()
print(type(s))
print(s)
print("The total of Set is ",a)

Q: WAP to find no. of occurences of each letter in the string given at runtime:

x=input("Enter the String")


y={}
for i in x:
y[i]=y.get(i,0)+1
for k,v in y.items():
print("{} occured {} items".format(k,v))

Q
x=input("Enter the String")
y={}
for i in x:
y[i]=y.get(i,0)+1
print(y)
print(sorted(y))
for k,v in y.items():
print("{} occured {} items".format(k,v))

Q:
x=input("Enter the String")
v={'a','e','i','o','u'}
y={}
for i in x:
if i in v:
y[i]=y.get(i,0)+1
for k,v in y.items():
print("{} occured {} items".format(k,v))
Q: take student details at run time and display result in dictionary format

x=int(input("Enter the no. of Students: "))


y={}
for i in range(x):
name=input("Enter Student Name:")
marks=int(input("Enter Student Marks:"))
y[name]=marks
print(y)

Q: Examine the code:


x=int(input("Enter the no. of Students: "))
y={}
for i in range(x):
name=input("Enter Student Name:")
marks=int(input("Enter Student Marks:"))
y[name]=marks
print(y)
while True:
name=input("Enter Student name to get Marks: ")
marks=y.get(name,-1)
if marks==-1:
print("Student Record not found")
else:
print("The marks of {}:{}".format(name,marks))
option=input("Do you want to find another student marks[yes/no]")
if option=="no":
break
print("Thanks for using this application")
======================
Q: what is eval
https://www.programiz.com/python-programming/methods/built-in/eval

Q: dictionary
https://towardsdatascience.com/15-things-you-should-know-about-dictionaries-in-
python-44c55e75405c
Q: what is pandas:
Pandas is a Python library.
Pandas is used to analyze data.
pandas is a fast, powerful, flexible and easy to use open source data analysis and
manipulation tool,
built on top of the Python programming language.

Pandas is an open-source, BSD-licensed Python library providing high-performance,


easy-to-use data structures and data analysis tools for the Python programming
language. Python with Pandas is used in a wide range of fields including academic and
commercial domains including finance, economics, Statistics, analytics, etc.

Pandas is a Python library used for working with data sets.

It has functions for analyzing, cleaning, exploring, and manipulating data.

The name "Pandas" has a reference to both "Panel Data", and "Python Data Analysis"
and was created by Wes McKinney in 2008.

Q: key Features:
Fast and efficient DataFrame object with default and customized indexing.
Tools for loading data into in-memory data objects from different file formats.
Data alignment and integrated handling of missing data.
Reshaping and pivoting of date sets.
Label-based slicing, indexing and subsetting of large data sets.
Columns from a data structure can be deleted or inserted.
Group by data for aggregation and transformations.
High performance merging and joining of data.
Time Series functionality.

Q:Why Use Pandas?


Pandas allows us to analyze big data and make conclusions based on statistical
theories.

Pandas can clean messy data sets, and make them readable and relevant.

Relevant data is very important in data science.

Q: What Can Pandas Do?


Pandas gives you answers about the data. Like:

Is there a correlation between two or more columns?


What is average value?
Max value?
Min value?
Pandas are also able to delete rows that are not relevant, or contains wrong values, like
empty or NULL values. This is called cleaning the data.

Q: pandas installation
way -1 : C:\Users\GS>py -m pip install pandas

way-2 : in pycharm
file --setting --project interpreter -->+--> pandas
note:
install panda3 also

demo:
import pandas

mydataset = {
'cars': ["BMW", "Volvo", "Ford"],
'passings': [3, 7, 2]
}

myvar = pandas.DataFrame(mydataset)

print(myvar)

note:
import pandas
import pandas as pd

Q: how to check pandas version:


way1 : using pycharm
import pandas as pd

print(pd.__version__)

way2: c:\> py -m pandas --version

======================================
Q: What is a Series?
Pandas Series is a One Dimensional indexed array. It is most similar to the NumPy
array. pandas.Series is a method to create a series.

A Pandas Series is like a column in a table.

It is a one-dimensional array holding data of any type.

demo:
import pandas as pd

a = [1, 7, 2]

#myvar = pd.Series(a)

#print(myvar)
#adding labels
myvar = pd.Series(a, index = ["x", "y", "z"])
print(myvar)

demo:
list_1 = [1, 2, -3, 4.5, 'indian']
print(list_1)

demo:
import pandas as pd
list_1 = [1, 2, -3, 4.5, 'indian']
series1 = pd.Series(list_1)
print(series1)
a=type(series1)
print(a)

Note:
Here it is showing 0 1 2 3 4 is index and 1 2 -3 4.5 Indian are data values.

pandas.core.series.Series means series is a one-dimensional array, which can store


indexed data

Q: create empty series:


import pandas as pd
empty_s = pd.Series([])
print(empty_s)
#a=type(empty_s)
#print(a)

Q: list inside series:


import pandas as pd
series2 = pd.Series([1,2,3,4,5])
print(series2)
note:
in index parameter, default index is start from 0 to n (0,1,2,….n) when index is not
identified
Here we are creating series with the index parameter
Index length should have equal to the number of data values, otherwise, it shows error

Q:
import pandas as pd

series2 = pd.Series([1,2,3,4,5], index = ['a', 'b', 'c', 'd', 'e'])


print(series2)

note:
We can change index to any numbers, alphabates, names etc.

---error raised
import pandas as pd

series2 = pd.Series([1,2,3,4,5], index = ['a', 'b', 'c'])


print(series2)

note:
ValueError: Length of passed value is 5, index implies 3
We got an error because we passed 3 indexes for 5 data values

Q: generate series of scalar values:


Creating series from scalar values
scalar values means single value

demo:
import pandas as pd
s3_scalar = pd.Series(2)
print(s3_scalar)

Q: for more scalar values


import pandas as pd
s3_scalar = pd.Series(2, index = [1,2,3,4,5])
print(s3_scalar)

Note:
for more data values index should be needed.

Q: Creating series from python dictionary


import pandas as pd
s4_dict = pd.Series({'eid':101, 'name':'smitha', 'age':35})
print(s4_dict)

Q: adding series
import pandas as pd
s5 = pd.Series([1, 2, 3, 44, 5])
s6 = pd.Series([1, 5, 7, 4, 56])
a = s5 + s6
print(a)

Q: use "add,min,max,drop"function
import pandas as pd
s5 = pd.Series([1, 2, 3, 44, 5])
s6 = pd.Series([1, 5, 7, 4, 56])
a=s5.add(s6)
print(a)
b=min(a)
print(b)
c=max(a)
print(c)
#d=a.drop(2)
#print(d)

note:
Using drop() function we can eliminate any index value

Q: add unequal series

import pandas as pd
s5 = pd.Series([1, 2, 3, 44, 5])
s6 = pd.Series([1, 5, 7, 4])
a=s5.add(s6)
print(a)

############################################################
##33
############################################################
##3
############################################################
###
Q: What is a DataFrame?
A Pandas DataFrame is a 2 dimensional data structure, like a 2 dimensional array, or a
table with rows and columns.

demo: empty dataframe


import pandas as pd
a = pd.DataFrame()
print(a)

demo:
import pandas as pd

data = {
"calories": [420, 380, 390],
"duration": [50, 40, 45]
}

#load data into a DataFrame object:


df = pd.DataFrame(data)

print(df)

Q: create dataframe from list


import pandas as pd
lst = ['a', 'b', 'c'] # First creating a list
print(lst)
df1 = pd.DataFrame(lst) # Creating dataframe from above list
print(df1)

note:
Here first row(0) is data values column index/label and first column is index (which is
start from 0) and second column have data values.

Q: Creating dataframe from list of list

import pandas as pd
ls_of_ls = [[1,2,3], [2,3,4], [4,5,6]] # Creating list of list
print(ls_of_ls)
df2 = pd.DataFrame(ls_of_ls)
print(df2)

note:
Here first row (0,1,2) is column index/label and three data values columns

Q: Creating dataframe from dict or dictionary or python dictionary

import pandas as pd
dict1 = {'ID': [11,22,33,44]} # Creating dict
df3 = pd.DataFrame(dict1)
print(df3)
print('\n more data value columns ')
dict2 = {'ID': [11,22,33,44], 'SN': [1,2,3,4]}
df4 = pd.DataFrame(dict1)
print(df4)

Q:
import pandas as pd
ls_dict = [{'a':1, 'b':2}, {'a':3, 'b':4}] # Creating list of dict
df5 = pd.DataFrame(ls_dict)
print(df5)

print('\n now next ')


ls_dict = [{'a':1, 'b':2}, {'a':3, 'b':4, 'c':5}]
df6 = pd.DataFrame(ls_dict)
print(df6)

note:
Here in first dictionary ‘c’ is not defined but that command not gives error because
pandas has function to handle missing values (which is shown by NaN)
NaN means not a number

Q: Creating dataframe from dict of series

import pandas as pd
dict_sr = {'ID': pd.Series([1,2,3]), 'SN': pd.Series([111,222,333])}
df7 = pd.DataFrame(dict_sr)
print(df7)

Activity -4
group-1
Q: pandas visualization
https://www.youtube.com/watch?v=vlRGoTjYL4A
https://realpython.com/pandas-plot-python/

Q: import excel sheet in pandas


https://www.youtube.com/watch?v=hT4b9vFZRB0
https://www.youtube.com/watch?v=r0s4slGHwzE

group-2
Q: time series "date range"
https://www.youtube.com/watch?v=A9c7hGXQ5A8&t=467s
https://www.youtube.com/watch?v=ZyhVh-qRZPA

Q: mongodb connectivity with python

group-3
Q: time series "shifting and lagging"
https://www.youtube.com/watch?v=0lsmdNLNorY
https://www.geeksforgeeks.org/difference-between-pandas-vs-numpy/

Q: sql server connection with python

group-4
Q:panel in pandas
https://www.youtube.com/watch?v=vhlp7yegSlU
https://www.tutorialspoint.com/python_pandas/python_pandas_panel.htm

Q: mysql connectivity with python


Q:
Q: import excel sheet in pandas
https://www.youtube.com/watch?v=hT4b9vFZRB0
https://www.youtube.com/watch?v=r0s4slGHwzE

group-5
Q: matplotlin in python and usage (installation and one basic example)
https://www.geeksforgeeks.org/python-introduction-matplotlib/
https://matplotlib.org/stable/tutorials/introductory/pyplot.html

Q: seaborn in poython (intro +install+small example)


https://www.youtube.com/watch?v=vaf4ir8eT38
https://towardsdatascience.com/seaborn-python-8563c3d0ad41
File handling is an important part of any web application.

Python has several functions for creating, reading, updating, and deleting files.

File Handling
The key function for working with files in Python is the open() function.

The open() function takes two parameters; filename, and mode.

There are four different methods (modes) for opening a file:


"r" - Read - Default value. Opens a file for reading, error if the file does not exist

"a" - Append - Opens a file for appending, creates the file if it does not exist

"w" - Write - Opens a file for writing, creates the file if it does not exist

"x" - Create - Creates the specified file, returns an error if the file exists
"t" - Text - Default value. Text mode

"b" - Binary - Binary mode (e.g. images)

Syntax
f = open("demofile.txt")

demo1:
1. create a file named ------->C:\Users\GS\PycharmProjects\pythonProject\a.txt
Hi
This is file handling concept
Welcome everyone!!

2. follow the code :


file = open('c:\demo\aa.txt', 'r')
for each in file:
print (each)

Note : ' or " quotes are applicable


file = open('c:\\demo\\a.txt', 'r')
for each in file:
print (each)

demo:
file = open('a.txt', "r")
for each in file:
print (file.read(5))

demo:

file = open('a.txt','w')
file.write("This is the write command")
file.write("It allows us to write in a particular file")
file.close()

Note: file is overwritten

demo:

file = open('a.txt','a')
file.write("This is append command")
file.write("It allows us to write in a particular file")
file.close()

demo: converting python objects in JSON


import json

# custom class
class Student:
def __init__(self, roll_no, name, batch):
self.roll_no = roll_no
self.name = name
self.batch = batch

class Car:
def __init__(self, brand, name, batch):
self.brand = brand
self.name = name
self.batch = batch

# main function
if __name__ == "__main__":
# create two new student objects
s1 = Student("85", "Swapnil", "IMT")
s2 = Student("124", "Akash", "IMT")

# create two new car objects


c1 = Car("Honda", "city", "2005")
c2 = Car("Honda", "Amaze", "2011")

# convert to JSON format


jsonstr1 = json.dumps(s1.__dict__)
jsonstr2 = json.dumps(s2.__dict__)
jsonstr3 = json.dumps(c1.__dict__)
jsonstr4 = json.dumps(c2.__dict__)

# print created JSON objects


print(jsonstr1)
print(jsonstr2)
print(jsonstr3)
print(jsonstr4)
Q: import object into csv

https://www.onlinetutorialspoint.com/python/how-to-convert-python-list-of-
objects-to-csv-file-example.html

import csv

class Items(object):

def __init__(self, id, name, category):


self.__id = id
self.__name = name
self.__category = category
self.__index = -1

@property
def id(self):
return self.__id

@property
def name(self):
return self.__name

@property
def category(self):
return self.__category

if __name__ == '__main__':
filename = 'items.csv'
items = [Items(100, 'iPhone 10', 'Mobiles'), Items(200, 'Lenovo', 'Laptops')
, Items(300, 'Java in Action', 'Books'), Items(400, 'Python', 'Books')]
try:
with open(filename, 'w') as f:
writer = csv.writer(f)
for item in items:
writer.writerow([item.id, item.name, item.category])
except BaseException as e:
print('BaseException:', filename)
else:
print('Data has been loaded successfully !')

Q: what is property
Python property() function returns the object of the property class and it is used to
create property of a class.
Syntax: property(fget, fset, fdel, doc)

Parameters:

fget() – used to get the value of attribute


fset() – used to set the value of attribute
fdel() – used to delete the attribute value
doc() – string that contains the documentation (docstring) for the attribute

Return: Returns a property attribute from the given getter, setter and deleter.
note:
If no arguments are given, property() method returns a base property attribute that
doesn’t contain any getter, setter or deleter.
If doc isn’t provided, property() method takes the docstring of the getter function.

Python property Using Decorator


The main work of decorators is they are used to add functionality to the existing
code. Also called metaprogramming, as a part of the program tries to modify
another part of the program at compile time.

class Alphabet:
def __init__(self, value):
self._value = value

# getting the values


@property
def value(self):
print('Getting value')
return self._value
# setting the values
@value.setter
def value(self, value):
print('Setting value to ' + value)
self._value = value

# deleting the values


@value.deleter
def value(self):
print('Deleting value')
del self._value

# passing the value


x = Alphabet('Peter')
print(x.value)

x.value = 'Diesel'

del x.value

note:
Using @property decorator works same as property() method.

First, specify that value() method is also an attribute of Alphabet then, we use the
attribute value to specify the Python property setter and the deleter. Notice that the
same method value() is used with different definitions for defining the getter, setter,
and deleter. Whenever we use x.value, it internally calls the appropriate getter,
setter, and deleter.
function: A function is a group of statements that together perform a specific task:

def functionname (arg1,arg2....)


statement1
statement2
statement...n

>>> print("hello Everyone")


hello Everyone
>>>

>>> def fun1(x):


print("hi ",x)

>>> fun1("ss")
hi ss
>>>
Q: if we open new session ,fun1 not working?>

demo:
>>> def fun1(x,y):
return(x+y)

>>> fun1(100,2)
102
>>> fun1(12,89898)
89910
>>> c=fun1(23,90)
>>> print(c)
113
>>>
>>> c
113
>>>
---default and multiple parameter in functoin arguments
>>> def stu(name,marks):
print(name," scored ",marks," Marks")

>>> stu("divya",99)
divya scored 99 Marks
>>>
---------------------------
>>> def stu(name="Divya",marks=0):
print(name," scored ",marks," Marks")

>>> stu
<function stu at 0x000001A30307FA60>
>>> stu()
Divya scored 0 Marks
>>> stu("ss",90)
ss scored 90 Marks
>>> stu("marks",89)
marks scored 89 Marks
>>> stu(marks=66)
Divya scored 66 Marks
---------------------------
--passing multiple parameter :

>>> def stu(name,*marks):


print(name)
print(marks)

>>> stu("Divya",89,67,67,33)
Divya
(89, 67, 67, 33)
>>>
Note:
you can pass one or more than one parameter in "marks"

>>> def stu(*marks):


print(marks)

>>> stu(23,98,33,78)
(23, 98, 33, 78)
>>>
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@2

Q: what is function;
a group of statement which is repeatedly required,these statement must put inside a
function and wherever this code is required,just call the function
Advantage:
write once ---> code repeatedly
Example:
def fun1(a):
print("Hi :",a)
print("Hi :",a)
print("Hi :",a)
print("Hi :",a)
fun1("Akshit")
fun1("Anushka")
fun1("Glory")

Q: purpose to create function :


def emp(eid,name,age,sal,ph):
#this is required for every new employee
insert into employee table
insert into account table
insert into project table
insert into admin table
#empl is colleaction group
for e in empl:
emp(data)

Q: types of function
sol: in build, user defined

Q:name some in built functions in python

Note:
pop and count are not functions:

Q: where is "append" function available


sol: class List
def append()

Q: types of parameters in function


sol: 4 types
positional
keyword
default
var

Q: can we pass parameter to function?


yes

Q: can we return from function in python


yes

Q: how python function is differ from other lang functions?


In other lang,only one value can be return,\
in python, function can return more tham one value
return x,y,z

Q: if we don't define return type in python function, what will be the return value?
sol: none
Example:
def fun1():
print("Welcome ")
print(fun1())

but in java :
class Demo{
public static void fun1(){
System.out.println("Hi this is fun1");
}
public static void main(String[] ar)
{ fun1();
}}
here fun1() function is not returning so that "void" need to write along with it.

--- to print the same code:


class Demo{
public static void fun1(){
System.out.println("Hi this is fun1");
}
public static void main(String[] ar)
{ System.out.println( fun1());
}}
if you run it,compile time error will come (void type not allowed)

But in Python, there is no much complexity ,if there is no return type mentioned,it will by
default become "none"

Example:
def fun2(x,y):
sum=x+y
sub=x-y
mul=x*y
div=x/y
return sum,sub,mul,div
t=fun2(200,80)
for i in t:
print(i)

Note: x and y are positional arguments

Q: How to change the order of positional parameter ?


t=fun2(x=900,y=30)
t=fun2(y=30,x=900)

Q:
fun2(200,y=90) ---valid
fun2(b=90,200) --- invalid (you should not take positional arg. after keyword arg)
Note: positional arg follow keyword arg
fun2(90,x=900) --- invalid (90 is considered for x and next x=900) a can't have multiple
values
def fun2(x=10,y):pass-- invalid (if you have default arg,it should be last
def fun2(x,y=90):pass ---- valid

Example;
def fun2(x,y):pass

fun2(90,x=900)

Example:
def fun2(x,y=10):pass
Q: why to use pass?
sol: as we not defining body for the function and this is required,so alternate we can use
pass(to keep empty block)

Q; what is use for var in function ?


variable length argument: (common in java and python)

To get the sum(10,20) , you declare


def sum(a,b):
print(a+b)
assume after some time the requirement is more than 2 arguments :
so to pass variable length arg :
def sun(*x):

Example:
def fun1(*n):
print("var-arg function")
fun1()
fun1(10)
fun1(10,90)
fun1(10,100,900,80)

Q: what is n in fun2(*n)
sol: tuple

Q: WAP to take different argument for calculation

def fun1(*n):
r=0
for i in n:
r=r+i
print("The sum if values :",r)

fun1()
fun1(10)
fun1(10,90)
fun1(10,100,900,80)

Q: if you are going to take positional arg and var-arg arguments, is there any order
problem?
sol: no

Example:
"name" is positional arg and "n" is avr-arg.

def fun1(name,*n):
r=0
for i in n:
r=r+i
print("The sum of values by ",name," : ",r)

fun1("Kriti")
fun1("ss",10)
fun1("hari",10,90)
fun1("Swapnil",10,100,900,80)

Q:
def fun2(*n,name): --- invalid
in java, there is strict rule (var arg should be the last parameter )
def fun2(*n,name): -- valid in python but with one rule(prefix the arg name )
Example:
def fun1(*n,name):
r=0
for i in n:
r=r+i
print("The sum of values by ",name," : ",r)

fun1(name="Kriti")
fun1(name="ss",10)
fun1(name="hari",10,90)
fun1(name="Swapnil",10,100,900,80)

Still there is one issue


keyword arg always follow positional argument

fun1(name="Kriti")
fun1(10,name="ss")
fun1(10,90,name="hari")
fun1(10,900,390,80,name="Swapnil")

Q: def fun2(name,*n)--- valid and no rule


Q: def fun2(n* ,name)--- valid but along with the rule

Q: what is keyword variable length argument


x=(name="sri",marks=200,age=20,ph=8990998)
x=(name="rai",sub="eng",sub2="maths",sub3="cs")

Now the function should access all the key-values and has to store in the form of
dictionary.

JAVA will not support


in Python : Keyword variable length argument will support this .

Example:
def fun1(**x):
print("Students Details : ")
for k,v in x.items():
print(k,"----------",v)

fun1(name="sri",marks=200,age=20,ph=8990998)
fun1(name="rai",sub="eng",sub2="maths",sub3="cs")
fun1(name="rhh",addr="delhi",PH=989890,AGE=90)
Summary:
in a function ,the arguments types are as follows:
positional
default
keywords
variable length
keyword variable

Exercise:
def fun1(a1,a2,a3=90,a4=800):
print(a1,a2,a3,a4)
fun1(90,80,70,200) #valid
fun1(28,80,a4=77) #valid
#fun1(a4=88) #invalid
fun1(a4=8,a1=3,a2=4) #a3=90 valid
#fun1() #invalid
#fun1(a3=88,a4=2,78,22) invalid positional arg follows keyword arf
fun1(8,5,7,a4=9) #valid
fun1(2,9,a4=66) #valid
fun1(3,6,a3=6,a9=88) #invalid a9 is not existing arg.

-------------------------------------------------------------------------
Q: what is anonymous function :
sol: without name ...nameless function
when you need instant use(one time usage)
thenanonymous function is best option

Q: Why anonymous function is required in python

Example :people use to talk in journey , they share their things ,but dont chnage their
number usually (just for that tympass)
They all know i m never going to communicate that person in future,so why to take ph no.

we go to pizza , everytime a new person is serving ,we never look for the contact details .
such type of instant use of function is called anonymous function

Note:
By using lambda function , we can write very concise code .

Example :

def s(n):
return n*n
OR

s=lambda x:x*x
print(s(2))
print(s(4))
print(s(8))
print(s(3))

Q:
s=lambda x,y:x+y
print("the sum of {} and {} is:{}".format(12,8,s(12,8)))
print("the sum of {} and {} is:{}".format(10,80,s(10,80)))
print("the sum of {} and {} is:{}".format(120,88,s(120,88)))

Q;
s=lambda x,y: x if x>y else y
print("the biggest of {} and {} is:{}".format(12,8,s(12,8)))
print("the biggest of {} and {} is:{}".format(888,8022,s(888,8022)))

Q/: how to pass a function as an argument to another function


sol: yes
by using
filter(), map(), reduce()

Q: can i depend our function in another function


sol: yes ,these function call nested function

Q: can we call a function in another function


sol: yes

Q: how to filter only even number from a group


example:
there are 100 students but only 20% respond remaining are silent.here i want to goft to
topper . i want to select only topper .

if i m project manager ,there are 40 people,there is on-sight requirement , we will filter


based on so many things(2-3) people

filter() ---syntax:
filter(function,list/tuple)
for every element, it wil apply this function. true values will be selected ,false values will be
ignore.
Example:
def fun1(x):
if x%2==0:
return True
else:
return False
list1=[0,2,9,33,89,44,20]
list2=list(filter(fun1,list1))
print(list2)

OR

list1=[0,2,9,33,89,44,20]
list2=list(filter(lambda x:x%2==0,list1))
print(list2)

OR
list1=[0,2,9,33,89,44,20]
list2=list(filter(lambda x:x%2==0,list1))
print(list2)
list3=list(filter(lambda x:x%2!=0,list1))
print(list3)

Q: difference between map and filter


Q: when to apply map or filter function

Example
list1=[1,2,3,4]
list2=[10,20,30,40]
list3=list(map(lambda x,y:x*y,list1,list2))
print(list3)

Q: evaluate
list1=[1,2,3,4]
list2=[10,20,30,40,90]
list3=list(map(lambda x,y:x*y,list1,list2))
print(list3)

Q: evaluate :
list1=[1,2,3,4,6]
list2=[10,20,30,40,90]
list3=list(map(lambda x,y:x*y,list1,list2))
print(list3)
Summary :
filter()
map()
reduce()
function aliasing
nested function
-----------------------------------------------------
Q: what is nested function and usage practically

Q: How to make inner function


def fun1():
def fun1_inner(x,y):
print("The sum :",x+y)
print("Average : ",(x+y)/2)
fun1_inner(10,90)
fun1_inner(20,80)
fun1_inner(78,77)
fun1_inner(80,200)

print(fun1())
# print(fun1_inner()) ---invalid

Example:

def outer():
print("This is outer function ")
def inner():
print("This is inner function call")
print("outer function returning inner function")
return inner
f1=outer()
f1()
f1()
f1()
f1()

here
fi=outer() ---> means we are alling outer function , outer function is calling inner
function and inner function i am going to assign with f1.
next time, if you want to call inner function , directly you can call f1
Automatically inner function is going to be executed

Q: are both same ?


f1=outer()
f1=outer
sol: no,
in f1=outer()--> is a function call,function is going to execute the return valueis assigned
with f1.
f1=outer--> for outer functiion , we are giving another name .

Note:
whenever we return something, we don't need to execute the function (return <function
name> is enough

Q:
return inner --- valid
return inner()-----valid but inner funtion is going to return something that return value will
be assigned to f1.

f1()=outer() --- invalid , you can assign ti a name (not to a function like f1())

Q: examine the code


def outer():
print("This is outer function ")
def inner():
print("This is inner function call")
print("outer function returning inner function")
return inner()
f1=outer()
print(f1)

Q: how to print of address of inner fucntion


print(id(f1))

Q: examine the code


def outer():
print("This is outer function ")
def inner():
print("This is inner function call")
print("outer function returning inner function")
return inner
f1=outer()
note: if you want to call inner function (inner functionis assigned with f1)
QL how to call inner function
sol; f1()

Q: What is function decorator ?


this takes some input function and return output functions with extra added functionality
girl--parlour----beautiful bride

input-> girl , decorator-- parlour , output-beautiful bride

here decorator itself a function.

Advantage:
you can access input and output function without extend the functionality . if you want to
generate extended functionality , then to go for decorator function
decorators help to make our code shorter and more pythonic

example:
i want to add a new functionality which may require 10000 lines of code. ..and for this
,already function exists but only one feature is missing then we are not required tio defined
brand new function .
we can take input of the existing function --- and add the new functionality =--then
generate the output.

Q: how many line we required with the decorated code?


sol: few lines
Q: can i use existing function
yes

Q: pythonic means
more shorter , more functionality in compact format
Example:
we have one existing function :
-----------------------------------------
def fun1(x):
print("Hi ",x," Welcome to class")
fun1("Aditya")
fun1("Shreya")
fun1("Geetika")

Q: how to add extra functionality into this ?


def decor(f1):
def inner(x):
if x:="Aditya":
print("Hello",x,'" this is new session for you")
else:
f1(x)
return inner

def fun1(x):
print("Hi ",x," Welcome to class")
fun1("Aditya")
fun1("Shreya")
fun1("Geetika")

Note:
we are getting same output
isssue:
we didn't link both functionality

Q: how to link it
sol: @<name of function>
Example

def decor(f1):
def inner(x):
if x=="Aditya":
print("Hello this is new session for you")
else:
f1(x)
return inner
@decor #annotation
def fun1(x):
print("Hi ",x," Welcome to class")
fun1("Aditya")
fun1("Shreya")
fun1("Geetika")

Now we are able to access its fuctionality


after using @ this annotation is going to perform .python itself going to take care.

Q: if "Aditya" is not in my parameter then what would be the output ?


Sol:
def decor(f1):
def inner(x):
if x=="Aditya":
print("Hello this is new session for you")
else:
f1(x)
return inner
@decor #annotation
def fun1(x):
print("Hi ",x," Welcome to class")
fun1("raman")
fun1("Shreya")
fun1("Geetika")

Q: how to call a function with or without decorator


def decor(f1):
def inner(x):
if x=="Aditya":
print("Hello this is new session for you")
else:
f1(x)
return inner

def fun1(x):
print("Hi ",x," Welcome to class")
decorfunction=decor(fun1)
fun1("raman")
fun1("Shreya")
fun1("Geetika")

Now inner function is defined with decorator


Q: how to call it individual

def decor(f1):
def inner(x):
if x=="Aditya":
print("Hello this is new session for you")
else:
f1(x)
return inner

def fun1(x):
print("Hi ",x," Welcome to class")
decorfunction=decor(fun1)
fun1("Aditya")
decorfunction("Aditya")

Q: examine the code?


def decor(f1):
def inner(x):
if x=="Aditya":
print("Hello this is new session for you")
else:
f1(x)
return inner

def fun1(x):
print("Hi ",x," Welcome to class")
decorfunction=decor(fun1)
fun1("Aditya")
decorfunction("Aditya")
fun1("Sunita")
decorfunction("Sunita")

Q: how to modify decor function ?

Q: how to call fun1 function along with decorator


sol: by using @

Note:
whenever if you define a decorator function,if you want you can call decorator function or
call the normal function (depends upon the requirement )

Example
def div(x,y):
return x/y
print(div(10,5))
print(div(3890,5))

Q: can you do decoration without change in existing code>(not completed, 1:11:39)

def div1(f1):
def inner(x,y):
#x snd y name can be change but the no. of arg will be same
if y==0:
print("can't divide with 0")
return
else:
return f1(x,y) #this f1 name must be same as parameter in div1
return inner #mandatory

@div1
def div(x,y):
return x/y

print(div(10,5))
print(div(3890,5))
print(div(3890,0))

You might also like