exercise make a factorial function
n=int(input("no. "))
fact=1
while n>0:
fact=fact*n
n=n-1
print("factorial is",fact)
Exercise 1: Write a program which repeatedly reads numbers until
the user enters “done”. Once “done” is entered, print out the
total, count, and average of the numbers.
If the user enters anything other than a number, detect their
mistake using try and except and print an error message and skip
to the next number.
Sum=0
count=0
while True:
n=input("enter no,:")
if n=="done":
break
n=float(n)
Sum=Sum+n
count=count+1
print("total",Sum)
print("count",count)
print("avg",Sum/count)
exercise 2 comprehensive ( if else continue break while )MIX
#Bank for ATM
password = 5601
#print: "insert the card"
#print: "Enter your password"
# if password is correct: then ask for type of account (saving / current)
# if not correct: Ask for re-enter ( for 3 attempts)
# Your card is blocked
# ask for the amount to be withdrawn
# if amount is multiple of 100 and < 20,000
# if not: print: enter your amount in multiple of 100, (Maximum 5
times)
# if not: break and print: Please try after some time
# print: collect your cash
# print: Thank you for visiting the Branch
MY SOLUTION PRACTICE WALA
pswrd=5601
n=0
m=0
print("Insert the card")
p=int(input("Enter your password"))
if p==5601:
input("Type of account")
else:
while n<3:
input("re enter")
n=n+1
a=int(input("amt to be withdrwan"))
if a<20000 and a%100==0:
print("collect your cash")
else:
while m<7:
input("enter yr amt in multiple of 100")
m=m+1
print("try later")
print("ty for visiting")
sir
#ATM Problem
password = 1234
count = 1
count2 = 1
passw = int(input("Enter your password: "))
if passw != password:
while passw != password:
if count == 3:
print("Your card is blocked")
break
print("Incorrect Password")
passw = int(input("Enter your passowrd again: "))
count = count + 1
if passw == password:
amount = int( input("Please enter your transaction amount"))
if amount > 20000 or amount % 500 != 0:
while amount > 20000 or amount % 500 != 0:
if count2 == 5:
print("Try after some time")
break
amount = int( input("Please enter your transaction amount again: "))
count2 = count2 + 1
if amount < 20000 and amount % 500 == 0:
print("Please collect your cash")
print("Thank you for visiting the branch")
QUESTION
Write a Python program that prints all the numbers from 0 to 6
except 3 and 6.
Note : Use 'continue' statement.
Expected Output : 0 1 2 4 5
n=-1
while n<6:
n=n+1
if n==3 or n==6:
continue
print(n)
QUESTION
Write a python programme that returns square root of perfect square number.
perfect square = 1, 4, 9, 16, 25, 36, ...
You are required to do this using while. Do not use num ** 0.5 to directly get
square root. Further, check your programme for very large number like
100000000, and compare your computation time using num ** 0.5 or
math.sqrt. If number is not a perfect square, then your programme should
return the message, “Number is not a perfect square”.
Input = 0, 10, 100, 101, 100000000
sol method 1
num = float(input("Enter positive number: "))
sqrt = 0
error = num - sqrt * sqrt
while error != 0:
sqrt = sqrt + 1
if( sqrt * sqrt == num):
print(sqrt)
break
error = num - sqrt * sqrt
if sqrt * sqrt > num:
print("number is not a perfect square")
break
sol method 2
n=int(input("enter no."))
s=-1
a=1
while n>=s*s:
s=s+1
if n==s*s:
print(s)
break
if n<s*s:
print("not a perfect square")
break
if n==0:
print(a)
Write a python programme that returns square root of perfect square number. Include check for
followings:
1. Check for negative numbers and non-integers.
You are required to do this using while. Do not use num ** 0.5 to directly get square root.
Further, check your programme for very large number like 100000000, and compare your
computation time using num ** 0.5 or math.sqrt. If number is not a perfect square, then
your programme should return the message, “Number is not a perfect square”.
(modified hai upar wala ques thoda)
n=float(input("enter no."))
s=-1
a=1
while n>=s*s:
s=s+1
if n==s*s:
print(s)
break
if n<s*s:
print("not a perfect square")
break
if n==0:
print(a)
if n<0:
print("-ve nos. not allowed")
if n-int(n)!=0:
print("non integers not allowed")
other way..
num = float(input("Enter positive number: "))
sqrt = 0
error = abs(num - sqrt **2 )
while error != 0:
sqrt = sqrt + 1
if( sqrt * sqrt == num):
print(sqrt)
break
error = abs(num - sqrt **2)
if sqrt * sqrt > num:
print("number is not a perfect square")
break
if error>0.000001:
sqt=( sqrt + num / sqrt ) / 2
print(sqt)
break
ERRORS
#Exercise error in this program
print("Version 1: Incorrect")
num = input("Enter positive integer: ")
num = float(num)
if(num < 0) :
print("Number should be positive")
elif int(num) - num != 0 :
print("Please enter positive integer")
else:
sqrt = 0
error = sqrt ** sqrt - num
while abs(error) != 0:
if (sqrt ** sqrt) > num:
print("Number is not perfect square")
breaking
if (sqrt ** sqrt) - num == 0:
print("The square root of", num, "is ",sqrt)
break
sqrt = sqrt + 1
error = sqrt ** sqrt - num
#Version 2
print("Incorrect version 2.0")
num = input("Enter positive integer: ")
num = float(num)
if(num < 0) :
print("Number should be positive")
elif int(num) - num != 0 :
print("Please enter positive integer")
else:
sqrt = 0
error = sqrt * sqrt - num
while abs(error) != 0:
if (sqrt * sqrt) > num:
print("Number is not perfect square")
break
if (sqrt * sqrt) - num == 0:
print("The square root of", num, "is ",sqrt)
break
sqrt = sqrt + 1
error = sqrt * sqrt - num
#still not working
#Version 3
print(""Version 3.0-Incorrect")
num = input("Enter positive integer: ")
num = float(num)
if(num < 0) :
print("Number should be positive")
elif int(num) - num != 0 :
print("Please enter positive integer")
else:
sqrt = 0
error = sqrt * sqrt - num
while abs(error) != 0:
sqrt = sqrt + 1
error = sqrt * sqrt - num
if (sqrt **sqrt) > num:
print("Number is not perfect square")
break
if (sqrt * sqrt) - num == 0:
print("The square root of", num, "is ",sqrt)
break
sol
2
print("Incorrect version 2.0")
num = input("Enter positive integer: ")
num = float(num)
if(num < 0) :
print("Number should be positive")
elif int(num) - num != 0 :
print("Please enter positive integer")
else:
sqrt = 0
error = sqrt * sqrt - num
while abs(error) != 0:
sqrt = sqrt + 1
if (sqrt * sqrt) > num:
print("Number is not perfect square")
break
if (sqrt * sqrt) - num == 0:
print("The square root of", num, "is ",sqrt)
break
sqrt = sqrt + 1
error = sqrt * sqrt - num
rbi, sebi,prowess, bloomberg, moneycontrol. com, amfi website, BSE, NSE websites, wallstreet journal, IMF news
survey, reports of planning commission
1
print("Version 1: Incorrect")
num = input("Enter positive integer: ")
num = float(num)
if(num < 0) :
print("Number should be positive")
elif int(num) - num != 0 :
print("Please enter positive integer")
else:
sqrt = 0
error = sqrt * sqrt - num
while abs(error) != 0:
sqrt = sqrt + 1
if (sqrt * sqrt) > num:
print("Number is not perfect square")
break
if (sqrt * sqrt) - num == 0:
print("The square root of", num, "is ",sqrt)
break
sqrt = sqrt + 1
error = sqrt * sqrt - num
3
print("Version 3.0-Incorrect")
num = input("Enter positive integer: ")
num = float(num)
if(num < 0) :
print("Number should be positive")
elif int(num) - num != 0 :
print("Please enter positive integer")
else:
sqrt = 0
error = sqrt * sqrt - num
while abs(error) != 0:
sqrt = sqrt + 1
error = sqrt * sqrt - num
if (sqrt *sqrt) > num:
print("Number is not perfect square")
break
if (sqrt * sqrt) - num == 0:
print("The square root of", num, "is ",sqrt)
break
##Find the sum of all the positive numbers entered by the user. As soon
as the user enters a negative number, stop taking in any further input from
the user and display the sum .
s=0
while True: (iska mtlb system hmse baar baar puche input tabhi while ke
n=input("write pos no.") niche lagaya hai input function
if n=="done": ab ye kaise dala isko hmne baad mei float mei bhi convert kiya hai
break aur tabhi input wale fun mei input hi hai not combined with int.
n=float(n)
if n<0:
print("negative no aren't allowed")
break
s=s+n
print("sum",s)
q1 assignment bonus wali
n=int(input("enter n"))
seq=range(1,n+1)
total=0
for i in seq:
total=total+(1/i)**3
print(total)
new way of output..check
c="pratham"
gap=" "
for m in c:
print(gap,m)
gap=gap+" "
@no of vowels
name = input("Enter your name")
nvowels = 0
v = "aeioUAEIOU"
for i in name:
if i in v:
print("Number of vowelsin", name, "i
s", nvowels)
using without endswith
vohi kaam ho apna formula banao
def endswith():
word = input("Enter anyting: ")
find = input("Check for end with: ")
ln = len(find)
if word[-1:-ln-1:-1][::-1] == find:
return(True)
else:
return(False)
FUNCTIONS DISCUSSED FROM NCERT STRING OPTION ...lower ,
upper etc
to remove white space bw witout any function
n=input("enter any text/no.")
result=""
for i in n:
if i != " ":
result=result+i
print(result)
new problem @2
def numrem():
a=input("Enter any text:\n") do hw 2 ques in pic
b="0123456789"
c=a.find(".")
result=a[:c+1:1]
str=""
for i in a[c+1:len(a)+1]:
if i in b:
continue
str+=i
result+=str
return(result)
@hw of recordings sat
1 a= input("Enter any text: ")
tws=""
for i in a:
if i not in"!@#$%^&*":
tws= tws+i
print(tws)
2 a=input("Enter any name:")
r=0
f= len(a)-1
if a[r] == "a" and a[f] == "e":
print(True)
else:
print(False)
3 a=["ahubhae","aarte","anmaye"]
x=0
for i in a:
if i[0] == "a" and i[-1] == "e":
x=x+1
print(x)
pic in phone of ques fav pic
true false by sir....
def countif(word):
word = word.lower()
if word[0] == "a" and word[-1] == "e":
return(True)
else:
return(False)
a = ["anne", "beenee", "cheene", "Meene", "AnnE"]
count = 0
for i in a:
count += countif(i)
print(count)
LIST
a= range(12,101)
for x in a:
if x%2==0 and x%7!=0:
print(x)
@ 7 / 11 multiples by using list
a=range(1,201)
result=[]
for i in a:
if i%7==0 or i%11==0:
result.append(i)
print(i)
@ repeated remove kardegaaa
ls=[1,2,2,1,3,4,6,7,9,10,1,6]
a=[]
for i in ls:
if i not in a:
a.append(i)
print(i)
@ jo repeated nahi ho re unko likhegaaa
a=[1,1,2,3,2,5,6,4,3,7,11,3,9]
nd=[]
for i in a:
if a.count(i)==1 :
nd.append(i)
print(nd)
@ even highest
ls=[1,2,2,1,3,4,6,7,9,10,1,6]
ls.sort()
b=[]
for i in ls:
if i%2==0:
b.append(i)
print(b[-1],"is the even ")
#The record of a student (Name, Roll No., Marks in five subjects and percentage of marks) is
#stored in the following list:
# stRecord = ['Raman','A-36',[56,98,99,72,69],
# 78.8]
#Write Python statements to retrieve the following information from the list stRecord.
#a) Percentage of the student
#b) Marks in the fifth subject
#c) Maximum marks of the student
#d) Roll no. of the student
#e) Change the name of the student from
# ‘Raman’ to ‘Raghav’
ans
@@sir wala
a = [21, 34, 56, 76, 87, 12, 89]
even = []
for i in a:
if i % 2 == 0:
even.append(i)
if len(even) == 0:
print("There is no even number")
else:
print(max(even))
/\/\/\\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/
tuple
n=int(input("Enter the number of inputs you want to enter"))
a=1
tup=()
while a<=n:
b=int(input("Enter the number "))
a=a+1
tup=tup+(b,)
print(tup)
print("max of tuple is:\n",max(tup))
print("Min of tuple is:\n",min(tup))
a = tuple()
num = int(input("enter the number of elements:"))
for x in range (num):
t = int(input("enter the number:" ))
a = a + (t,)
print(a)
print("the maximum number is", max(a))
print("the minimum number is", min(a))
def r(): recording sat
a=input("enter mixdottext")
p=a.find(".")
sud=a[:p+1]
sad=a[p+1:]
sadwn=""
for i in sad:
if i not in "1,2,3,4,5,6,7,8,9":
sadwn=sadwn+i
return(sad + sadwn)
@@ to remove @#$%^&* same as of removing white space
a=input("enter text")
q=""
for i in a:
if i not in "!,@,,#,$,%,^,&,*" :
q=q+i
print(q)
dict
@@name in front of marks (( keys daalo value pao))
a = ["Ishika", "Navneet K", "Amanpreet", "Mansimar", "Sukriti"]
b = [18,19,20,20,20]
d={}
r=range(0,len(a))
for i in r:
d[a[i]]= b[i]
print(d)
@@key values alag without using a particular method
d={"s":"t","g":"d","p":"p"}
a= []
b= []
for i in d:
a.append(i)
b.append(d[i])
print(a)
print(b)
d.keys()
d.values()
@@ values daaalo keys paao
#key : #values {{org}}
d={"s":"t","g":"d","p":"p"}
l=list(d.values())
li=list(d.keys())
n= input("enter calue...")
a=li[l.index(n)]
print(a)
# # q1 part 2 TEST SATURDAY
ls = ["Mnsmr", "Grvmttl", "shIvani","gUneet", "jsmhR"]
count_dummy = 0#for vowels
count_con = 0# for constants
for i in ls:
i = i.lower()
for x in i:
if x in "aeiou":
count_dummy += 1
break
if count_dummy == 0:
count_con += 1
count_dummy=0
print(count_con)
import numpy as np
import pandas as pd
q2@
import math
def correlationCoefficient(ls1,ls2) :
sum_X = 0
sum_Y = 0
sum_XY = 0
squareSum_X = 0
squareSum_Y = 0
i=0
while i < n :
sum_X = sum_X + ls1[i]
sum_Y = sum_Y + ls2[i]
sum_XY = sum_XY + ls1[i] * ls2[i]
squareSum_X = squareSum_X + ls1[i] * ls1[i]
squareSum_Y = squareSum_Y + ls2[i] * ls2[i]
i=i+1
corr = (float)(n * sum_XY - sum_X * sum_Y)/(float)(math.sqrt((n *
squareSum_X - sum_X * sum_X)* (n * squareSum_Y - sum_Y *
sum_Y)))
return corr
ls1 = []
n = int(input("Enter number of elements you want : "))
for i in range(0, n):
ele = int(input("enter your next element= "))
ls1.append(ele)
print(ls1)
ls2 = []
m = int(input("Enter number of elements you want: "))
for j in range(0, m):
el = int(input("enter next element= "))
ls2.append(el)
print(ls2)
if n==m:
print (format(correlationCoefficient(ls1, ls2)))
else:
print("{corelation cant be found as the length of two lists provided
is not equal}")
@@corelation ques assignment ka sir ne short mei kraya
see fav of album
@@@numpy with bionomial dist.
import numpy as np
import math as m
X=np.array(range(0,11))
#P(X=x)=ncx*p^x*(1-p)^(n-x)
a=[]
for i in X :
a.append(m.comb(10,i)*(0.5**i)*(0.5**(10-i)))
a=np.array(a)
####one short formula
prob1 = np.array([math.comb(10, i) for i in X]) * (0.5 ** X) * (0.5 **
(10 - X))
.......................................
import math as m
>>> X=np.array(range(0,11))
>>> for i in X :
print(m.comb(10,i)*(0.5**i)*(0.5**(10-i)))
subsetting by logical value n indexation new cls
>>> import numpy as np
>>> m
>>> import pandas as pd
>>> import math
>>> import statistics as stat
>>> a[[2,2,2,2]]
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
a[[2,2,2,2]]
NameError: name 'a' is not defined
>>> b=a[[2,2,2,2]]
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
b=a[[2,2,2,2]]
NameError: name 'a' is not defined
>>> a=[[2,2,2,2]]
>>> a
[[2, 2, 2, 2]]
>>> a[2]
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
a[2]
IndexError: list index out of range
>>> a=array([2,4,8,10,23,45])
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
a=array([2,4,8,10,23,45])
NameError: name 'array' is not defined
>>> a=np.array([2,4,8,10,23,45])
>>> a=np.array([2,4,8,10,23,45])
>>> a
array([ 2, 4, 8, 10, 23, 45])
>>> a*2
array([ 4, 8, 16, 20, 46, 90])
>>> a>5
array([False, False, True, True, True, True])
>>> T=True
>>> F=False
>>> a[[T,F,F,T,T,F]]
array([ 2, 10, 23])
>>> a[1:]
array([ 4, 8, 10, 23, 45])
>>> a[1::1]
array([ 4, 8, 10, 23, 45])
>>> a[1::2]
array([ 4, 10, 45])
>>> #true false jo likha hai usse phele
>>> #subseting by logical values
>>> #t/f subsetting by indexing
>>>
>>>
>>>
>>> a
array([ 2, 4, 8, 10, 23, 45])
>>> a>5
array([False, False, True, True, True, True])
>>> a[a>5]
array([ 8, 10, 23, 45])
>>> a[a<20]
array([ 2, 4, 8, 10])
>>> a[[a<20]]
Warning (from warnings module):
File "<pyshell#32>", line 1
FutureWarning: Using a non-tuple sequence for multidimensional
indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In
the future this will be interpreted as an array index,
`arr[np.array(seq)]`, which will result either in an error or a different
result.
array([ 2, 4, 8, 10])
>>> #why error
>>> a
array([ 2, 4, 8, 10, 23, 45])
>>> a=a%2==0
>>> a
array([ True, True, True, True, False, False])
>>> a[a%2==0]
array([False, False])
>>> a
array([ True, True, True, True, False, False])
>>> a=array([ 2, 4, 8, 10, 23, 45])
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
a=array([ 2, 4, 8, 10, 23, 45])
NameError: name 'array' is not defined
>>> a=np.array([ 2, 4, 8, 10, 23, 45])
>>> a
array([ 2, 4, 8, 10, 23, 45])
>>> a[a%2=0]
SyntaxError: invalid syntax
>>> a[a%2==0]
array([ 2, 4, 8, 10])
>>> a[a%2==1]
array([23, 45])
>>> a[8<a<20]
Traceback (most recent call last):
File "<pyshell#45>", line 1, in <module>
a[8<a<20]
ValueError: The truth value of an array with more than one element
is ambiguous. Use a.any() or a.all()
>>> a[::2]
array([ 2, 8, 23])
>>> a[a>8]
array([10, 23, 45])
>>> a[a<20]
array([ 2, 4, 8, 10])
>>> b=a[a>8]
>>> b
array([10, 23, 45])
>>> b[b<20]
array([10])
>>> ###get only even values
>>> # get only odd values
>>> # get values greater than 8 and less than 20
>>> # get all aternate values, ie 1st, 3rd, ...
SyntaxError: invalid syntax
>>> #@ for above answers tis is the ques...
>>> lm=np.array([[1,2,3],[2,3,4],[3,4,5]])
>>> lm
array([[1, 2, 3],
[2, 3, 4],
[3, 4, 5]])
>>> lm.ndim
>>> lm.shape
(3, 3)
>>> lm.shape=(4,3)
Traceback (most recent call last):
File "<pyshell#58>", line 1, in <module>
lm.shape=(4,3)
ValueError: cannot reshape array of size 9 into shape (4,3)
>>> lm=np.array([[1,2,3],[2,3,4]])
>>> lm
array([[1, 2, 3],
[2, 3, 4]])
>>> lm.shape=(3,2)
>>> lm
array([[1, 2],
[3, 2],
[3, 4]])
>>> #changing the rows and colums to what we want
>>>
>>> #in these dimensions ques indexing starts from zero
>>> #so we can get the paricular element by following ways
>>>
>>> lm
array([[1, 2],
[3, 2],
[3, 4]])
>>> lm[1,1]
>>> lm[[0,1],2]
Traceback (most recent call last):
File "<pyshell#70>", line 1, in <module>
lm[[0,1],2]
IndexError: index 2 is out of bounds for axis 1 with size 2
>>> lm=np.array([[1,2,3],[2,3,4],[3,4,5]])
>>> lm
array([[1, 2, 3],
[2, 3, 4],
[3, 4, 5]])
>>> lm[[0,1],2]
array([3, 4])
>>> lm[[1,2],0]
array([2, 3])
>>> lm[2,2]
>>> lm[0,0]
>>> lm[1,[0,1]]
array([2, 3])
>>> lm[[0,1]]
array([[1, 2, 3],
[2, 3, 4]])
>>> lm[ ,[0,1]]
SyntaxError: invalid syntax
>>> lm[: ,[0,1]]
array([[1, 2],
[2, 3],
[3, 4]])
>>> lm[[0,1],:]
array([[1, 2, 3],
[2, 3, 4]])
>>> lm[[0,0,2,2],[0,2,0,2]]
array([1, 3, 3, 5])
>>> # ye ek trh se 0,0
>>> #0,2
>>> #2,0
>>> #2,2
>>> # hmne individually hr ek element bnawaya hai
PANDAS
>>> import pandas as pd
>>> import numpy as np
>>> b=pd.Series(data=[1,2,3,4,5],dtype=float)
>>> b
0 1.0
1 2.0
2 3.0
3 4.0
4 5.0
dtype: float64
>>>
IQ=pd.Series(data=[1,2,3,4,5],index=["yoyo","ravi","wwwww","aaaa"
,"zzzzz"])
>>> IQ
yoyo 1
ravi 2
wwwww 3
aaaa 4
zzzzz 5
dtype: int64
>>> IQ["aaaa"]
>>> IQ*2
yoyo 2
ravi 4
wwwww 6
aaaa 8
zzzzz 10
dtype: int64
>>> IQ["ravi"]
>>> IQ["ustaad"]=100
>>> IQ
yoyo 1
ravi 2
wwwww 3
aaaa 4
zzzzz 5
ustaad 100
dtype: int64
>>> data={"NAME":["ravi","shyam","ganu"],"AGE":
[18,19,20],"CLASS":["12th","1st yr","2nd yr"]}
>>> type(data)
<class 'dict'>
>>> #now converting it into DATAFRAMES 2DIMENSION wala
>>> df=pd.DataFrame(data=data)
>>> df
NAME AGE CLASS
0 ravi 18 12th
1 shyam 19 1st yr
2 ganu 20 2nd yr
>>> #df=pd.DataFrame(data=data).........data=kuch bhi ho sakta hai
jisse hmne apne data ko indicate kiya h
>>>
>>>
IQ=pd.DataFrame(data=[1,2,3,4,5],index=["yoyo","ravi","wwwww","
aaaa","zzzzz"])
>>> IQ
yoyo 1
ravi 2
wwwww 3
aaaa 4
zzzzz 5
>>>
IQ=pd.Series(data=[1,2,3,4,5],index=["yoyo","ravi","wwwww","aaaa"
,"zzzzz"],columns=["IQ LEVEL"])
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
IQ=pd.Series(data=[1,2,3,4,5],index=["yoyo","ravi","wwwww","aaaa"
,"zzzzz"],columns=["IQ LEVEL"])
TypeError: __init__() got an unexpected keyword argument
'columns'
>>> data={"NAME":
["AVI","JAPSAHEJ","LAKSH","SUKRITI","CHETNA"],"GENDER":
["MALE","MALE","MALE","FEMALE","FEMALE"],"AGE":
[21,17,13,8,13],"MARKS":[67,34,78,55,92]}
>>> data
{'NAME': ['AVI', 'JAPSAHEJ', 'LAKSH', 'SUKRITI', 'CHETNA'], 'GENDER':
['MALE', 'MALE', 'MALE', 'FEMALE', 'FEMALE'], 'AGE': [21, 17, 13, 8,
13], 'MARKS': [67, 34, 78, 55, 92]}
>>> datapd.DataFrame(data=data)
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
datapd.DataFrame(data=data)
NameError: name 'datapd' is not defined
>>> data=pd.DataFrame(data=data)
>>> data
NAME GENDER AGE MARKS
0 AVI MALE 21 67
1 JAPSAHEJ MALE 17 34
2 LAKSH MALE 13 78
3 SUKRITI FEMALE 8 55
4 CHETNA FEMALE 13 92
>>> data=pd.DataFrame(data=data)datapd.DataFrame(data=data)
SyntaxError: invalid syntax
>>> data=pd.DataFrame(data=data,columns=["sream"])
>>> data
sream
0 NaN
1 NaN
2 NaN
3 NaN
4 NaN
>>>
data=pd.DataFrame(data=data,columns=["sream":,"bcom","bcom","
bcom","bcom","bbe"])
SyntaxError: invalid syntax
>>>
data=pd.DataFrame(data=data,columns=["bcom","bcom","bcom","b
com","bbe"])
>>> data
bcom bcom bcom bcom bbe
0 NaN NaN NaN NaN NaN
1 NaN NaN NaN NaN NaN
2 NaN NaN NaN NaN NaN
3 NaN NaN NaN NaN NaN
4 NaN NaN NaN NaN NaN
>>> data
bcom bcom bcom bcom bbe
0 NaN NaN NaN NaN NaN
1 NaN NaN NaN NaN NaN
2 NaN NaN NaN NaN NaN
3 NaN NaN NaN NaN NaN
4 NaN NaN NaN NaN NaN
>>> data={"NAME":
["AVI","JAPSAHEJ","LAKSH","SUKRITI","CHETNA"],"GENDER":
["MALE","MALE","MALE","FEMALE","FEMALE"],"AGE":
[21,17,13,8,13],"MARKS":[67,34,78,55,92]}
>>> data
{'NAME': ['AVI', 'JAPSAHEJ', 'LAKSH', 'SUKRITI', 'CHETNA'], 'GENDER':
['MALE', 'MALE', 'MALE', 'FEMALE', 'FEMALE'], 'AGE': [21, 17, 13, 8,
13], 'MARKS': [67, 34, 78, 55, 92]}
>>>
data=pd.DataFrame(data=data,columns=["bcom","bcom","bcom","b
com","bbe"])
>>> data
Empty DataFrame
Columns: [bcom, bcom, bcom, bcom, bbe]
Index: []
>>> data={"NAME":
["AVI","JAPSAHEJ","LAKSH","SUKRITI","CHETNA"],"GENDER":
["MALE","MALE","MALE","FEMALE","FEMALE"],"AGE":
[21,17,13,8,13],"MARKS":[67,34,78,55,92]}
>>> ab={"NAME":
["AVI","JAPSAHEJ","LAKSH","SUKRITI","CHETNA"],"GENDER":
["MALE","MALE","MALE","FEMALE","FEMALE"],"AGE":
[21,17,13,8,13],"MARKS":[67,34,78,55,92]}
>>> data=pd.DataFrame(data=ab)
>>> data
NAME GENDER AGE MARKS
0 AVI MALE 21 67
1 JAPSAHEJ MALE 17 34
2 LAKSH MALE 13 78
3 SUKRITI FEMALE 8 55
4 CHETNA FEMALE 13 92
>>> ab["GENDER"]
['MALE', 'MALE', 'MALE', 'FEMALE', 'FEMALE']
>>> ab["GENDER","MARKS"]
Traceback (most recent call last):
File "<pyshell#42>", line 1, in <module>
ab["GENDER","MARKS"]
KeyError: ('GENDER', 'MARKS')
>>> ab["GENDER"]
['MALE', 'MALE', 'MALE', 'FEMALE', 'FEMALE']
>>> ab[["GENDER","MARKS"]]
Traceback (most recent call last):
File "<pyshell#44>", line 1, in <module>
ab[["GENDER","MARKS"]]
TypeError: unhashable type: 'list'
>>> ab["GENDER","MARKS"]
Traceback (most recent call last):
File "<pyshell#45>", line 1, in <module>
ab["GENDER","MARKS"]
KeyError: ('GENDER', 'MARKS')
>>> ab["course"]
Traceback (most recent call last):
File "<pyshell#46>", line 1, in <module>
ab["course"]
KeyError: 'course'
>>> ab["course":1,2,3,4,4]
Traceback (most recent call last):
File "<pyshell#47>", line 1, in <module>
ab["course":1,2,3,4,4]
TypeError: unhashable type: 'slice'
>>> data={"NAME":
["AVI","JAPSAHEJ","LAKSH","SUKRITI","CHETNA"],"GENDER":
["MALE","MALE","MALE","FEMALE","FEMALE"],"AGE":
[21,17,13,8,13],"MARKS":[67,34,78,55,92]}
>>> ab={"NAME":
["AVI","JAPSAHEJ","LAKSH","SUKRITI","CHETNA"],"GENDER":
["MALE","MALE","MALE","FEMALE","FEMALE"],"AGE":
[21,17,13,8,13],"MARKS":[67,34,78,55,92]}
>>> data=pd.DataFrame(data=ab)
>>> data
NAME GENDER AGE MARKS
0 AVI MALE 21 67
1 JAPSAHEJ MALE 17 34
2 LAKSH MALE 13 78
3 SUKRITI FEMALE 8 55
4 CHETNA FEMALE 13 92
>>> ab["course":1,2,3,4,5]
Traceback (most recent call last):
File "<pyshell#52>", line 1, in <module>
ab["course":1,2,3,4,5]
TypeError: unhashable type: 'slice'
>>> ab["course":"1","2","3","4","5"]
Traceback (most recent call last):
File "<pyshell#53>", line 1, in <module>
ab["course":"1","2","3","4","5"]
TypeError: unhashable type: 'slice'
>>> ab["course"]=[1,2,3,4,5]
>>> data
NAME GENDER AGE MARKS
0 AVI MALE 21 67
1 JAPSAHEJ MALE 17 34
2 LAKSH MALE 13 78
3 SUKRITI FEMALE 8 55
4 CHETNA FEMALE 13 92
>>> ab
{'NAME': ['AVI', 'JAPSAHEJ', 'LAKSH', 'SUKRITI', 'CHETNA'], 'GENDER':
['MALE', 'MALE', 'MALE', 'FEMALE', 'FEMALE'], 'AGE': [21, 17, 13, 8,
13], 'MARKS': [67, 34, 78, 55, 92], 'course': [1, 2, 3, 4, 5]}
>>> data=pd.DataFrame(data=ab)
>>> data
NAME GENDER AGE MARKS course
0 AVI MALE 21 67 1
1 JAPSAHEJ MALE 17 34 2
2 LAKSH MALE 13 78 3
3 SUKRITI FEMALE 8 55 4
4 CHETNA FEMALE 13 92 5
>>> ab["AGE"]
[21, 17, 13, 8, 13]
>>> data["AGE"]
0 21
1 17
2 13
3 8
4 13
Name: AGE, dtype: int64
>>> data["AGE"]+data["MARKS"]
0 88
1 51
2 91
3 63
4 105
dtype: int64
>>> #kisi ek individaul row chhiye hoo....
>>> ab.iloc(2)
Traceback (most recent call last):
File "<pyshell#63>", line 1, in <module>
ab.iloc(2)
AttributeError: 'dict' object has no attribute 'iloc'
>>> ab.iloc[2]
Traceback (most recent call last):
File "<pyshell#64>", line 1, in <module>
ab.iloc[2]
AttributeError: 'dict' object has no attribute 'iloc'
>>> data.iloc[2]
NAME LAKSH
GENDER MALE
AGE 13
MARKS 78
course 3
Name: 2, dtype: object
>>> data[data["GENDER"]=="MALE"]
NAME GENDER AGE MARKS course
0 AVI MALE 21 67 1
1 JAPSAHEJ MALE 17 34 2
2 LAKSH MALE 13 78 3
>>>
#FURTHER PANDAS
>>> import pandas as pd
>>>
>>> import numpy as n
>>> import numpy as np
>>> marks = pd.read_csv(r"C:\Users\HP\Desktop\DATA FOR
PYTHON.csv")
>>> marks
ROLL NO. NAME ASSIGNMENT TEST
0 1 Ravi 5 2
1 2 Shavi 6 10
2 3 Kavi 9 5
3 4 Savi 3 9
4 5 Mavi 4 8
5 6 Tavi 6 10
6 7 Ravi 6 4
7 8 Ravi 8 6
8 9 Shavi 7 7
9 10 Kavi 9 8
>>> marks[marks["NAME"]=="A"]
Empty DataFrame
Columns: [ROLL NO., NAME, ASSIGNMENT, TEST]
Index: []
>>> marks[marks["NAME"]=="R"]
Empty DataFrame
Columns: [ROLL NO., NAME, ASSIGNMENT, TEST]
Index: []
>>> marks[marks["NAME"]=="S"]
Empty DataFrame
Columns: [ROLL NO., NAME, ASSIGNMENT, TEST]
Index: []
>>> marks.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 10 entries, 0 to 9
Data columns (total 4 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 ROLL NO. 10 non-null int64
1 NAME 10 non-null object
2 ASSIGNMENT 10 non-null int64
3 TEST 10 non-null int64
dtypes: int64(3), object(1)
memory usage: 344.0+ bytes
>>> marks[marks["NAME"]=="Ravi"]
ROLL NO. NAME ASSIGNMENT TEST
0 1 Ravi 5 2
6 7 Ravi 6 4
7 8 Ravi 8 6
>>> marks[marks["ASSIGNMENT"]>5]
ROLL NO. NAME ASSIGNMENT TEST
1 2 Shavi 6 10
2 3 Kavi 9 5
5 6 Tavi 6 10
6 7 Ravi 6 4
7 8 Ravi 8 6
8 9 Shavi 7 7
9 10 Kavi 9 8
>>> marks[marks["ASSIGNMENT"]==10]
Empty DataFrame
Columns: [ROLL NO., NAME, ASSIGNMENT, TEST]
Index: []
>>> marks[marks["TEST"]==10]
ROLL NO. NAME ASSIGNMENT TEST
1 2 Shavi 6 10
5 6 Tavi 6 10
>>> marks
ROLL NO. NAME ASSIGNMENT TEST
0 1 Ravi 5 2
1 2 Shavi 6 10
2 3 Kavi 9 5
3 4 Savi 3 9
4 5 Mavi 4 8
5 6 Tavi 6 10
6 7 Ravi 6 4
7 8 Ravi 8 6
8 9 Shavi 7 7
9 10 Kavi 9 8
>>> #if by chance u put wrong data then how to edit that particular
value
>>> marks.iloc[0,3]
>>> ##or
>>> marks["TEST"]
0 2
1 10
2 5
3 9
4 8
5 10
6 4
7 6
8 7
9 8
Name: TEST, dtype: int64
>>> marks["TEST"][0]
>>> #now putting the desired value
>>> marks.iloc[0,3]=10
>>> marks
ROLL NO. NAME ASSIGNMENT TEST
0 1 Ravi 5 10
1 2 Shavi 6 10
2 3 Kavi 9 5
3 4 Savi 3 9
4 5 Mavi 4 8
5 6 Tavi 6 10
6 7 Ravi 6 4
7 8 Ravi 8 6
8 9 Shavi 7 7
9 10 Kavi 9 8
>>>
>>>
>>> asg=marks["ASSIGNMENT"]
>>> asg
0 5
1 6
2 9
3 3
4 4
5 6
6 6
7 8
8 7
9 9
Name: ASSIGNMENT, dtype: int64
>>> tst=marks["TEST"]
>>> tst
0 10
1 10
2 5
3 9
4 8
5 10
6 4
7 6
8 7
9 8
Name: TEST, dtype: int64
>>> b=asg+tst
>>> b
0 15
1 16
2 14
3 12
4 12
5 16
6 10
7 14
8 14
9 17
dtype: int64
>>> marks["b"]
Traceback (most recent call last):
File "C:\Users\HP\AppData\Local\Programs\Python\Python38-
32\lib\site-packages\pandas\core\indexes\base.py", line 2895, in
get_loc
return self._engine.get_loc(casted_key)
File "pandas\_libs\index.pyx", line 70, in
pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\index.pyx", line 101, in
pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\hashtable_class_helper.pxi", line 1675, in
pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas\_libs\hashtable_class_helper.pxi", line 1683, in
pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'b'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
marks["b"]
File "C:\Users\HP\AppData\Local\Programs\Python\Python38-
32\lib\site-packages\pandas\core\frame.py", line 2906, in
__getitem__
indexer = self.columns.get_loc(key)
File "C:\Users\HP\AppData\Local\Programs\Python\Python38-
32\lib\site-packages\pandas\core\indexes\base.py", line 2897, in
get_loc
raise KeyError(key) from err
KeyError: 'b'
>>> marks[b]
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
marks[b]
File "C:\Users\HP\AppData\Local\Programs\Python\Python38-
32\lib\site-packages\pandas\core\frame.py", line 2912, in
__getitem__
indexer = self.loc._get_listlike_indexer(key, axis=1,
raise_missing=True)[1]
File "C:\Users\HP\AppData\Local\Programs\Python\Python38-
32\lib\site-packages\pandas\core\indexing.py", line 1254, in
_get_listlike_indexer
self._validate_read_indexer(keyarr, indexer, axis,
raise_missing=raise_missing)
File "C:\Users\HP\AppData\Local\Programs\Python\Python38-
32\lib\site-packages\pandas\core\indexing.py", line 1298, in
_validate_read_indexer
raise KeyError(f"None of [{key}] are in the [{axis_name}]")
KeyError: "None of [Int64Index([15, 16, 14, 12, 12, 16, 10, 14, 14, 17],
dtype='int64')] are in the [columns]"
>>> marks["TOTAL"]=marks["ASSIGNMENT"]+marks["TEST"]
>>> marks
ROLL NO. NAME ASSIGNMENT TEST TOTAL
0 1 Ravi 5 10 15
1 2 Shavi 6 10 16
2 3 Kavi 9 5 14
3 4 Savi 3 9 12
4 5 Mavi 4 8 12
5 6 Tavi 6 10 16
6 7 Ravi 6 4 10
7 8 Ravi 8 6 14
8 9 Shavi 7 7 14
9 10 Kavi 9 8 17
>>> marks["TOTAL"]>10
0 True
1 True
2 True
3 True
4 True
5 True
6 False
7 True
8 True
9 True
Name: TOTAL, dtype: bool
>>> marks[marks["TOTAL"]>10]
ROLL NO. NAME ASSIGNMENT TEST TOTAL
0 1 Ravi 5 10 15
1 2 Shavi 6 10 16
2 3 Kavi 9 5 14
3 4 Savi 3 9 12
4 5 Mavi 4 8 12
5 6 Tavi 6 10 16
7 8 Ravi 8 6 14
8 9 Shavi 7 7 14
9 10 Kavi 9 8 17
>>> marks[(marks["NAME"]=="Ravi") & (marks["TOTAL"]>10)]
ROLL NO. NAME ASSIGNMENT TEST TOTAL
0 1 Ravi 5 10 15
7 8 Ravi 8 6 14
>>> marks.sort_values(by="TOTAL")
ROLL NO. NAME ASSIGNMENT TEST TOTAL
6 7 Ravi 6 4 10
3 4 Savi 3 9 12
4 5 Mavi 4 8 12
2 3 Kavi 9 5 14
7 8 Ravi 8 6 14
8 9 Shavi 7 7 14
0 1 Ravi 5 10 15
1 2 Shavi 6 10 16
5 6 Tavi 6 10 16
9 10 Kavi 9 8 17
>>> marks.sort_values(by="TOTAL",ascending=False)
ROLL NO. NAME ASSIGNMENT TEST TOTAL
9 10 Kavi 9 8 17
1 2 Shavi 6 10 16
5 6 Tavi 6 10 16
0 1 Ravi 5 10 15
2 3 Kavi 9 5 14
7 8 Ravi 8 6 14
8 9 Shavi 7 7 14
3 4 Savi 3 9 12
4 5 Mavi 4 8 12
6 7 Ravi 6 4 10
>>> marks.sort_values(by="TOTAL",inplace=True)
>>> marks
ROLL NO. NAME ASSIGNMENT TEST TOTAL
6 7 Ravi 6 4 10
3 4 Savi 3 9 12
4 5 Mavi 4 8 12
2 3 Kavi 9 5 14
7 8 Ravi 8 6 14
8 9 Shavi 7 7 14
0 1 Ravi 5 10 15
1 2 Shavi 6 10 16
5 6 Tavi 6 10 16
9 10 Kavi 9 8 17
>>> #bina variable diye wahi value assign karan is above question
>>>
>>> marks.sort_values(by=["TOTAL","ROLL NO."])
ROLL NO. NAME ASSIGNMENT TEST TOTAL
6 7 Ravi 6 4 10
3 4 Savi 3 9 12
4 5 Mavi 4 8 12
2 3 Kavi 9 5 14
7 8 Ravi 8 6 14
8 9 Shavi 7 7 14
0 1 Ravi 5 10 15
1 2 Shavi 6 10 16
5 6 Tavi 6 10 16
9 10 Kavi 9 8 17
>>> marks.sort_values(by=["TOTAL","ROLL
NO."],ascending=[True,False])
ROLL NO. NAME ASSIGNMENT TEST TOTAL
6 7 Ravi 6 4 10
4 5 Mavi 4 8 12
3 4 Savi 3 9 12
8 9 Shavi 7 7 14
7 8 Ravi 8 6 14
2 3 Kavi 9 5 14
0 1 Ravi 5 10 15
5 6 Tavi 6 10 16
1 2 Shavi 6 10 16
9 10 Kavi 9 8 17
>>> marks.sort_values(by=["TOTAL","ROLL
NO."],ascending=[True,False],inplace=True)
>>> marks
ROLL NO. NAME ASSIGNMENT TEST TOTAL
6 7 Ravi 6 4 10
4 5 Mavi 4 8 12
3 4 Savi 3 9 12
8 9 Shavi 7 7 14
7 8 Ravi 8 6 14
2 3 Kavi 9 5 14
0 1 Ravi 5 10 15
5 6 Tavi 6 10 16
1 2 Shavi 6 10 16
9 10 Kavi 9 8 17
>>> #above done is when something is coming twice thrice and we
want further conditions
>>>
>>>
>>> marks,head()
Traceback (most recent call last):
File "<pyshell#51>", line 1, in <module>
marks,head()
NameError: name 'head' is not defined
>>> marks.head()
ROLL NO. NAME ASSIGNMENT TEST TOTAL
6 7 Ravi 6 4 10
4 5 Mavi 4 8 12
3 4 Savi 3 9 12
8 9 Shavi 7 7 14
7 8 Ravi 8 6 14
>>> marks.tail(6)
ROLL NO. NAME ASSIGNMENT TEST TOTAL
7 8 Ravi 8 6 14
2 3 Kavi 9 5 14
0 1 Ravi 5 10 15
5 6 Tavi 6 10 16
1 2 Shavi 6 10 16
9 10 Kavi 9 8 17
>>> marks.mean()
ROLL NO. 5.5
ASSIGNMENT 6.3
TEST 7.7
TOTAL 14.0
dtype: float64
>>> marks.mean(axis=1)
6 6.75
4 7.25
3 7.00
8 9.25
7 9.00
2 7.75
0 7.75
5 9.50
1 8.50
9 11.00
dtype: float64
>>> marks[["TEST","ASSIGNMENT","TOTAL
SyntaxError: EOL while scanning string literal
>>> marks[["TEST","ASSIGNMENT","TOTAL"]]
TEST ASSIGNMENT TOTAL
6 4 6 10
4 8 4 12
3 9 3 12
8 7 7 14
7 6 8 14
2 5 9 14
0 10 5 15
5 10 6 16
1 10 6 16
9 8 9 17
>>> marks
ROLL NO. NAME ASSIGNMENT TEST TOTAL
6 7 Ravi 6 4 10
4 5 Mavi 4 8 12
3 4 Savi 3 9 12
8 9 Shavi 7 7 14
7 8 Ravi 8 6 14
2 3 Kavi 9 5 14
0 1 Ravi 5 10 15
5 6 Tavi 6 10 16
1 2 Shavi 6 10 16
9 10 Kavi 9 8 17
>>> marks[["TEST","ASSIGNMENT","TOTAL"]].mean(axis=1)
6 6.666667
4 8.000000
3 8.000000
8 9.333333
7 9.333333
2 9.333333
0 10.000000
5 10.666667
1 10.666667
9 11.333333
dtype: float64