Python Notes (Mphasis Mail)
Python Notes (Mphasis Mail)
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
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
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)))
x=10 (internally 10 value is refer to an object,x is the reference var which points to the
object)
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.
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
----built in fUNCTIONs-------------:
A piece of code which execute some logic.
>>>5**3
or
>>>pow(5,3)
>>>abs (15.567)
>>>len("word length")
>>>max(67,6576,54,2,9898)
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Example
x="this is Python demo"
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))
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@
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
>>>
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.
example:
>>> type(input("Enter value"))
Enter value20
<class 'str'>
>>> type(input("Enter value"))
Enter value10.34
<class 'str'>
>>>
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
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")))
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)
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"
@@@@@@@@@@@@@@@@--------------------------------------------------------------
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))
Example:
a=eval(input("Enter value"))
print(type(a))
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))
Example:
a=eval(input("Enter value"))
print(type(a))
print(a)
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
>>>
>>> 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:
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)
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()
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
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: What happen :
x=[]
for i in range(0,201,10):
x.append(i)
print(x)
x.insert(400,900)
print(x)
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 :
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: x=[10,30,90,900]
print(x)
x.clear()
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)
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
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:
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
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.
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)
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")
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")
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")
--------------
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
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
-----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
Note :
Ternary operator is available but syntax is different
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")
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
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")
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)
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")
-------------------------------------------------------------------
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
OR
for i in range(0,31,2):
print(i)
OR
---for odd number
for i in range(1,31,2):
print(i)
for i in range(20,0,-1):
print(i)
Result:
C:\Users\dell\AppData\Local\Programs\Python\Python36>py v17.py
Enter some list elements(67,89,89)
Total= 245
code2:
x=""
y=""
while (x!="ss") or (y!="saran"):
x=input("Enter name ")
y=input("Enter Password ")
print("hello ",x,"Welcome to session!!")
for x in range(5):
for y in range(5):
print("x={} and y={}".format(x,y))
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:
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)
--------- 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")
while condition:
body
Q: How to skip current iteration and continue for the next iteration?
sol: continue
def fun2():
print("Hi this is fun2")
fun1()
fun2()
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 .
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
Note :
In a loop if we are using an empty block,so "pass" statement is mandatory to complete the
syntax
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 valid or not
x=10
y=90
del x,y
print(x)
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
SOl: None
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: 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))
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)
Example:
x="python"
print(x[0])
print(x[1])
print(x[-1])
Q: WAP to accept a string at runtime and print all the characters along wih their index
values
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)
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])
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])
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
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
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
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 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.
This is the main reason why NumPy is faster than lists. Also it is optimized to work
with latest CPU architectures.
demo:
import numpy
print(arr)
=========================================
Q: NumPy Array Indexing
Access Array Elements
Array indexing is the same as accessing an array element.
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
print(arr[0])
print(arr[2])
print(arr[2] + arr[3])
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])
import numpy as np
======================================================
==
Q: NumPy Array Slicing
Slicing arrays
Slicing in python means taking elements from one given index to another given
index.
print(arr[1:5])
#Slice elements from index 4 to the end of the array:
print(arr[4:])
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.
import numpy as np
for x in arr:
print(x)
Q: 2D iterating
import numpy as np
for x in arr:
print(x)
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.
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.
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.
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
print(arr)
print('shape of array :', arr.shape)
Q: Reshaping arrays
Reshaping means changing the shape of an array.
Q: Convert the following 1-D array with 12 elements into a 2-D array.
import numpy as np
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
newarr = arr.reshape(2, 3, 2)
print(newarr)
import numpy as np
newarr = arr.reshape(3, 3)
print(newarr)
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.
import numpy as np
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 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]))
except:
print("An error occurred")
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)
try:
fun(3)
fun(5)
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)
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
-->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
Note:
duplicate values are not allowed in keys ,duplicates are allowed in values
101- richa
102-ss
103- richa
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)
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:
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
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.
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.
Pandas can clean messy data sets, and make them readable and relevant.
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
print(pd.__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.
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.
Q:
import pandas as pd
note:
We can change index to any numbers, alphabates, names etc.
---error raised
import pandas as pd
note:
ValueError: Length of passed value is 5, index implies 3
We got an error because we passed 3 indexes for 5 data values
demo:
import pandas as pd
s3_scalar = pd.Series(2)
print(s3_scalar)
Note:
for more data values index should be needed.
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
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:
import pandas as pd
data = {
"calories": [420, 380, 390],
"duration": [50, 40, 45]
}
print(df)
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.
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
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)
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
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/
group-2
Q: time series "date range"
https://www.youtube.com/watch?v=A9c7hGXQ5A8&t=467s
https://www.youtube.com/watch?v=ZyhVh-qRZPA
group-3
Q: time series "shifting and lagging"
https://www.youtube.com/watch?v=0lsmdNLNorY
https://www.geeksforgeeks.org/difference-between-pandas-vs-numpy/
group-4
Q:panel in pandas
https://www.youtube.com/watch?v=vhlp7yegSlU
https://www.tutorialspoint.com/python_pandas/python_pandas_panel.htm
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
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.
"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
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!!
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()
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()
# 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")
https://www.onlinetutorialspoint.com/python/how-to-convert-python-list-of-
objects-to-csv-file-example.html
import csv
class Items(object):
@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:
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.
class Alphabet:
def __init__(self, value):
self._value = 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:
>>> 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 :
>>> stu("Divya",89,67,67,33)
Divya
(89, 67, 67, 33)
>>>
Note:
you can pass one or more than one parameter in "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: types of function
sol: in build, user defined
Note:
pop and count are not functions:
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.
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)
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)
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
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)
fun1(name="Kriti")
fun1(10,name="ss")
fun1(10,90,name="hari")
fun1(10,900,390,80,name="Swapnil")
Now the function should access all the key-values and has to store in the form of
dictionary.
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
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)))
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)
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
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
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())
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: 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")
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")
def fun1(x):
print("Hi ",x," Welcome to class")
decorfunction=decor(fun1)
fun1("raman")
fun1("Shreya")
fun1("Geetika")
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")
def fun1(x):
print("Hi ",x," Welcome to class")
decorfunction=decor(fun1)
fun1("Aditya")
decorfunction("Aditya")
fun1("Sunita")
decorfunction("Sunita")
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))
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))