Python Codings
Python Codings
ans:190
ans:5
ans:23,45,67
4. #user input
a=int(input("enter the number"))
print(a)
ans:
5.#Multiple user input taken at a time in a same line with different datatypes
a,b=int(input("enter the a value:")),float(input("enter the b value:"))
print(a,b)
ans:
ans:
ans:
8.
a,b,c=int(input("enter the a value:")),float(input("enter the b value")),str(input('enter the c val
ue'))
print(a,b,c)
ans:
9. a,b,c=90,45,78
print(a,b,c)
ans: 90,45,78
ans:
ans:
ans:
14. out=[1,23.4,'hai',"gh",45,78]
print(out)
ans:
If loop:
Ex1: Give the number of units consumed as static input and store it in a variable.
The requirements are as follows:
If the number of units less than or equals 100, the cost per unit is Rs 3.46.
If the number of units used is greater than 101 and less than 300, the cost per unit is Rs 7.43.
If you consume more than 301 units and less than 500 units, the cost per unit is Rs 10.32.
If the number of units consumed exceeds 501, the cost per unit is Rs 11.71.
The monthly line rent is Rs 1.45 per unit.
The additional fixed meter rent is Rs 100.
The tax on the bill is 16%, which is equal to 0.16.
Using If Else statements check the conditions and calculate the cost per unit.
After Calculating cost per unit multiply the number of units by 1.45 and add it to the bill
#static
units=800
if units<=100:
amount= cost=3.468*units+1.45*units+100+0.16*units
if units>=101 and units<=300:
amount= cost=7.43*units+1.45*units+100+0.16*units
if units>=301 and units<=500:
amount = cost=10.32*units+1.45*units+100+0.16*units
if units>501:
amount = cost=11.71*units+1.45*units+100+0.16*units
print(amount)
ans:
ex: Give the number of units consumed as user input using int(input()) and store it in a
variable.
Calculate the bill using the above method.
Using If Else statements we check the conditions and calculate the cost per unit.
After Calculating cost per unit we multiply the number of units by 1.45 and add it to the
bill(Adding monthly line rent to the bill)
Add Rs 100 to the bill as additional fixed meter rent.
Multiply the present bill amount by 0.16 (Adding the tax) and add this bill to the past bill.
Print the Final Electricity Bill.
The Exit of the Program.
#user input
units=int(input("enter the number of units"))
if units<=100:
amount= cost=3.468*units+1.45*units+100+0.16*units
if units>=101 and units<=300:
amount= cost=7.43*units+1.45*units+100+0.16*units
if units>=301 and units<=500:
amount = cost=10.32*units+1.45*units+100+0.16*units
if units>501:
amount = cost=11.71*units+1.45*units+100+0.16*units
print(amount)
ans:
ex: simple function
def wel():
print("welcome to python")
print(wel())
ans:
ans:
return True
# Driver code
string = 'the quick brown fox jumps over the Lazy dog'
if(ispangram(string) == True):
print("Yes")
else:
print("No")
ans:
ex:Functions:
#without argument without reutrn
def abc():
a=10
b=20
c=a+b
print(c)
abc()
ans:
ans:
Note: values inside the codes can be consider as multi line command line.
#with argument no return
def abc(a=10,b=20):
#a=10
#b=20
#c=a+b
print(a+b)
abc()
ans:
#local variable
print(a+b)
abc()
#global variable
print(a+b)
ans:
ans:
ans:
def max(a,b,c):
if(a>b) and (a>c):
print("a is bigger")
elif(b>c) and (b>a):
print("b is the biggest number")
else:
print("c is the biggest number")
max(12,13,45)
ans:
ans:
Ex: #max of three numbers
#user input global variable
a=int(input("enter the a value"))
b=int(input("enter the b value"))
c=int(input("enter the c value"))
def max():
if(a>b) and (a>c):
print("a is bigger")
elif(b>c) and (b>a):
print("b is the biggest number")
else:
print("c is the biggest number")
max()
ans:
ans:
def max( x, y ):
if x > y:
return x
return y
#max(,-45)
def maxx(x,y,z):
return max(z,max( x, y ))
maxx(23,-45,67)
#print(maxx( 23, -45 ,67))
Ans:
def max_of_two( x, y ):
if x > y:
return x
return y
def max_of_three( x, y, z ):
return max_of_two( x, max_of_two( y, z ) )
print(max_of_three(3, 6, -5))
def sum(numbers):
sum = 0
for x in numbers:
sum=sum+ x
return sum
sum((8, 2, 3, 0, 7)) #input in tuple inside the function
l=[34,45,67,89]
def sum():
sum = 0
#l=[34,45,67,89]
for x in l:
sum=sum+ x
return sum
sum()
l=[12,13,15,78,90,87]
def mul():
mul=1
for x in l:
mul=mul*x
return mul
mul()
l=[12,13,15,78,90,87]
def mul():
mul=1
for x in l:
mul*=x
return mul
mul()
def sum(numbers):
sum=0
for i in numbers:
sum+=i
return sum
ans:
ans:
def sum(numbers):
total = 0
for x in numbers:
total += x
return total
print(sum((8, 2, 3, -1, 7)))
ans:
ex:#general formula factorial
#FAC(5)
5*(5-1)!
5*4!
5*4(4-1)!
5*4(3)!
5*4*3(3-1)!
5*4*3*2*1
ans:
def multiply(numbers):
total = 1
for x in numbers:
total *= x
return total
print(multiply((8, 2, 3, -1, 7)))
ex:#for loop
for i in range(10):
print(i)
ex:#while loop
i=1
while i<=10:
print("hai")
pass
break
ex:'''Write calculations using functions and get the results. Let's have a look at some exa
mples:
seven(times(five())) # must return 35
four(plus(nine())) # must return 13
eight(minus(three())) # must return 5
six(divided_by(two())) # must return 3
Conditions:
● There must be a function for each number from 0 ("zero") to 9 ("nine")
● There must be a function for each of the following mathematical operations: plus,
minus, times, divided_by
● Each calculation consist of exactly one operation and two numbers
● The most outer function represents the left operand, the most inner function
represents the right operand
● Division should be integer division. For example, this should return 2, not
2.666666...:
eight(divided_by(three()))'''
ex.#multiply two numbers using python using function
a=7
def mul():
b=5
return a*b
print(mul())
ans:
ans:
ans:
if loop:
Problem 1
Print (“Question 1”)
ENTER a number.
Write if statements to determine:
• Is the number 0
o If true, print the number is 0
• Is the number 13
o If true, print the number is 13
• Is the number -13
o If true, print the number is -13
Problem 2
Write Python code that asks a user for what town Kean University is located in. If the user
enters “Union”, print correct.
What happens if you type “union” instead? (This is for your own knowledge)
Problem 3
Write Python code that asks a user for the amount (price) of a pack of gum. What data type is
the price?
If the amount is less than 1, print "I think this is a good price". If the amount is greater than or
equal to 1, print "I think this is expensive".
Problem 4
Create a variable named bills and ask the question, “What president is on the banknote?”
Print the name of the President according to the chart:
Amount
1
George Washington
2
Thomas Jefferson
5
Abraham Lincoln
10
Alexander Hamilton
20
Andrew Jackson
50
Ulysses S. Grant
100
Benjamin Franklin
Problem 5
Many people say that one human year is equivalent to seven dog years. Ask the user
how old is the dog.
Human=x
Dog=7x
If the user enters less than 2, print the dog is a baby.
If the user enters 2 or more, print the dog's age in human years.
Age=int(input(“enter the age”)
If(age<=2)
{
Print(“”);
}
Else
{
Age=age*7
}
Print(age)
baby
Calculate dog’s age.
Problem 6
Write Python code that asks:
• x1
• x2
• y1
• y2
Calculate the slope of the line.
Slope1=y2−y1/ x2−x1 , slope2 = frac{y2 - y1}/{x2 - x1} ,slope3=(x2−x1)/(y2−y1)
• If the slope is positive, print positive slope.
• If the slope is negative, print negative slope.
• If the slope is zero, print horizontal line.
• If the the denominator is 0, print vertical line.
Problem 7
Ask the user, do you hear Laurel or Yanny?
If the user enters “Laurel”, print “doesn’t it sound like Yanny?”.
If the user enters “Yanny”, print “doesn’t it sound like Laurel?”
Problem 8
Ask the user to enter an abbreviation.
• If the user enters "lol", print "laughing out loud".
• If the user enters "rofl", print "rolling on the floor laughing".
• If the user enters "lmk", print "let me know".
• If the user enters "smh", print "shaking my head".
Problem 9
Ask the user, what is the net worth of Mark Zuckerberg. (do not enter commas when entering
the number)
If the user enters 54500000000, print “yes and that’s a 54.5 billion”. If the user enters less
than 54500000000, print “that's not much”. If the user enters more than 54500000000, print
“I'll make more when I graduate”.
Problem 10
Ask the user, who bought Minecraft for 2.5 billion dollars?
If the user enters “Microsoft”, print “correct”. If the user does not enter “Microsoft”, print
“incorrect”.
Use if else for Problems 11 - 20
Problem 11
Write Python code that asks a user for two numbers. Print the number that is the greatest.
Print the number that is the least. Assume the numbers are not the same.
Problem 12
Write Python code that asks a user for their password. If the user enters “1234567890”, print
“that password is really easy to guess”.
Else print “good enough, I guess”.
Problem 13
Write Python code that asks a user for their temperature. If the temperature is 100.4 or more,
print “you have a fever”.
Else print “normal temperature”
Problem 14
Write Python code that asks a user how many degrees is it in the Building. If the temperature
is less than or equal to 70, print “feels chilly”.
Else print “comfy”.
Problem 15
The USEPA developed the Air Quality Index (AQI) to report daily air quality to the public.
The AQI tells you how clean your local air is, and what associated health effects might be a
concern in your area. Think of the AQI as a yardstick that runs from 0 to 300. The higher the
AQI value, the greater the level of air pollution and the greater the health concern.
Write Python code that asks a user what the AQI is today. If the user enters, 50 or less, print
“Air Quality is Good”. Else print, “Air Quality is Moderate or Unhealthy”.
Problem 16
Write Python code that asks a user how many pizza slices they want. The pizzeria charges
$1.25 a slice if you order 10 slices or less and $1 a slice if you order more than 10 slices.
Print the total price depending on how many slices you order.
(Note: do not use the $ when assigning the price in your Python code)
Problem 17
Write Python code that asks a user how many Youtube videos they watch per day. The
average video is 7 minutes. If the user enters 5 or more, print “you watch a lot of videos”.
Else print “good job!”.
Print the total number of minutes the user watches videos.
Problem 18
Write Python code that asks a user do you have a ShopRite card? Next, ask how many Apple
or Pumpkin pies do they want to buy.
If the user enters “yes”, print "2.99 per pie". Else, print "4.99 per pie".
Print the total price.
Problem 19
Write Python code asks the user for a number. If the number is divisible by 5, print the
number if it is divisible by 5. Else print the number is not divisible by 5.
The % (modulo) operator yields the remainder from the division of the first argument by the
second.
Problem 20
Write Python code that asks a user for a number. Print if the number is even or odd.
Solution:
For---loop:
Questions:
[Link] i in range (10):
print (hari)
ans:1----hello
2---hello
3---hello
print (i)
print (wacky_name)
12. Write a program that outputs 100 lines, numbered 1 to 100, each with your name on it.
The
output should look like the output below.
1 Your name
2 Your name
3 Your name
4 Your name
...
13. Write a program to print the series 100, 98, 96, . . . , 4, 2. Using for loop
14. Write a program that prints a list of the integers from 1 to 20 with their squares.
15. Write a program that outputs 20 lines, numbered 1 to 20, each with your name on it.
16. Write a program that prints out a list of the integers from 1 to 20 and their squares. The
output
should look like this:
1 --- 1
2 --- 4
3 --- 9
...
20 --- 400
17. Write a program that uses a for loop to print the numbers 8, 11, 14, 17, 20, . . . , 83, 86,
89.
18. Write a program that uses a for loop to print the numbers 100, 98, 96, . . . , 4, 2.
19. Write a program that uses exactly four for loops to print the sequence of letters below.
AAAAAAAAAABBBBBBBCDCDCDCDEFFFFFFG
20. Write a program that asks the user for their name and how many times to print it. The
program should print out the user’s name the specified number of times.
21. Write a program that prints a giant letter A like the one below. Allow the user to specify
how
large the letter should be.
*
* *
*****
* *
* *
22. Use for loops to print a diamond like the one below. Allow the user to specify how high
the
diamond should be.
*
***
*****
*******
*****
***
*
23. Use a for loop to print an upside down triangle like the one below. Allow the user to
specify
how high the triangle should be.
****
***
**
*
24. Use a for loop to print a triangle like the one below. Allow the user to specify how high
the
triangle should be.
*
**
***
****
25. Use a for loop to print a box like the one below. Allow the user to specify how wide and
how
high the box should be.
*******************
* *
* *
*******************
26. Use a for loop to print a box like the one below. Allow the user to specify how wide and
how
high the box should be. [Hint: print(‘*’*10) prints ten asterisks.]
*******************
*******************
*******************
*******************
For loop:
Solution:
#1
'''for i in range(3):
num=int(input("enter the number"))
print("the sqr of number is:",num*num)'''
#3
'''print("a")
print("b")
for i in range(5):
print("c")
print("d")
print("E")'''
#4
'''print("a")
print("b")
for i in range(5):
print("c")
for i in range(5):
print("d")
print("e")'''
#5
'''for hari in range(10):
print(hari)
#6
for i in range(4):
print(i+1,"hello")'''
#7
'''for i in range(100):
for wacky_name in range(100):
print(i)
print(wacky_name)'''
#8
'''for i in range(5,0,-1):
print(i,end="")
print("blast off!!")
#9
for i in range(4):
print("*"*6)
#10
for i in range(4):
print("*"*(i+1))'''
'''#11
for i in range(10):
print("Pavithra")'''
#12
'''for i in range(100):
print(i+1,"Pavithra")'''
#13
'''for i in range(100,0,-2):
print(i)'''
#14
'''for i in range(1,21):
print(i,i*i)'''
#15
'''for i in range(1,21):
print(i,"pavithra")'''
#16
for i in range(1,21):
print(i,i*i,sep="---")
#17
'''for i in range(8,90,3):
print(i)'''
#19
'''for i in range(10):
print("A",end="")
for i in range(8):
print("B",end="")
for i in range(5):
print("CD",end="")
for i in range(1):
print("EFFFFFFG",end="")'''
#20
'''a=int(input("enter the number"))
b=input("enter the name")
for i in range(a):
print(b)'''
#22
'''a=int(input("enter the size of dimond"))
for i in range(1,a,1):
print("*"*i)
for i in range(a,0,-1):
print("*"*i)'''
#23
'''a=int(input("enter the number"))
for i in range(a,0,-1):
print("*"*i)'''
#24
'''a=int(input("enter the number:"))
for i in range(a+1):
print("*"*i)'''
#26
'''a=int(input("enter the wide :"))
b=int(input("enter the hight:"))
for i in range(b):
print("*"*a)'''
for and if loop(example)
ex1:
d={0:"zero",1:"one",2:"two",3:"three",4:"four",5:"five",6:"six",7:"seven",8:"eight",9:"nine",1
0:"ten"}
num=int(input("enter the number"))
for i in d:
if (num < 9):
print( i , d[i])
if num>9:
if(num%2==0):
print("even")
else:
print("odd")
ouput:
enter the number11
odd
ex:
l=list("1234")
l[0]=l[1]=5
print(l)
output: [5, 5, '3', '4']
ex:
a='welcome to python'
print([Link]())
output:
['welcome', 'to', 'python']
output:
enter the value34
ex:
a=90
b=12
c=a//b
print(c)
output:
7
Ex:
a=90
b=45
if a==90:
print(a)
else:
print(b)
output:
90
#regular expression
#A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern.
#RegEx can be used to check if a string contains the specified search pattern.
#Python has a built-in package called re, which can be used to work with Regular
Expressions.
import re
txt = "The rain in Spain"
x = [Link]("^The.*Spain$", txt)
x
OUTPUT:
<[Link] object; span=(0, 17), match='The rain in Spain'>
Ex:
import re
import re
output:
[]
Ex: #The search() function searches the string for a match, and returns a Match object if there
is a match.
import re
output:
The first white-space character is located in position: 3
Ex:
#split
#The split() function returns a list where the string has been split at each match:
import re
output:
['The rain in Spain']
Ex:
#You can control the number of occurrences by specifying the maxsplit parameter:
import re
ex:
import re
txt = "The rain in Spain"
x = [Link]("\s", "9", txt)
print(x)
ex:
import re
output: []
ex:
#The search() function searches the string for a match, and returns a Match object if there is a
match.
import re
output:
The first white-space character is located in position: 3
Ex:
#split
#The split() function returns a list where the string has been split at each match:
import re
output:
Ex:
#You can control the number of occurrences by specifying the maxsplit parameter:
import re
output:
['The', 'rain', 'in Spain']
Ex:
import re
output:
The9rain9in9Spain
Ex:
import re
#Find all lower case characters alphabetically between "a" and "m":
x = [Link]("[a-m]", txt)
print(x)
output:
Ex:
# initialising string
ini_string = "welcome123for127welcome"
# printing result
print("final string : ", res)
output:
initial string : welcome123for127welcome
final string : 123127
ex:
'''Write calculations using functions and get the results. Let's have a look at some examples:
seven(times(five())) # must return 35
four(plus(nine())) # must return 13
eight(minus(three())) # must return 5
six(divided_by(two())) # must return 3
Conditions:
● There must be a function for each number from 0 ("zero") to 9 ("nine")
● There must be a function for each of the following mathematical operations: plus,
minus, times, divided_by
● Each calculation consist of exactly one operation and two numbers
● The most outer function represents the left operand, the most inner function
represents the right operand
● Division should be integer division. For example, this should return 2, not
2.666666...:
eight(divided_by(three()))'''
ex:
a=7
def mul():
b=5
return a*b
mul()
output:
35
Ex:
a=6
def sum():
b=7
return a+b
sum()
output:
13
Ex:
a=8
def sub():
b=3
return a-b
sub()
output:
5
Ex:
a=6
def div():
b=3
return a//b
div()
output:
2
Ex:
#Program to swap 2 numbers without using 3rd variable
import re
"^(?=(?:\\D*\\d){2})(?=(?:[^a-z]*[a-z]){2})(?=(?:[^A-Z]*[A-
Z]){2})(?=(?:[^!@#$%^&*+=]*[!@#$%^&*+=]){2}).{15,}$"
Output:
^(?=(?:\D*\d){2})(?=(?:[^a-z]*[a-z]){2})(?=(?:[^A-Z]*[A-
Z]){2})(?=(?:[^!@#$%^&*+=]*[!@#$%^&*+=]){2}).{15,}$
Ex:
#Write a Python function to find the Max of three numbers.
a=34
b=89
c=90
def max():
a=10
b=20
c=30
if(a>b) and (a>c):
return a
elif(b>c) and (b>a):
return b
else:
return c
max()
output:
30
Ex:
max(23,45,67)
output:
67
Ex:
def wel():
print("welcome to python")
print(wel())
output:
welcome to python
None
Ex:
def wel():
return "welcome to python"
wel()
output:
welcome to python
ex:
def wel():
return "welcome to python"
print(wel())
output:
welcome to python
ex:
def wel():
print("welcome to python")
print(wel())
output:
welcome to python
None
Ex:
def grandchild(array1,array2):
print([Link]("rooney"))
print([Link]("rooney"))
print(len(array1 and array2))
grandchild({"shaw":"luke","rooney":"wayne"},{"ronaldo":"rooney","rooney":"shaw"})
output:
wayne
shaw
2
Ex:
dict1={"luke":"shaw","wayne":"rooney","rooney":"ronaldo","shaw":"rooney"}
x=[]
y=0
for i in dict1:
[Link]=="ronaldo"
[Link]([Link]())
for j in x:
for k in dict1:
if([Link]=="rooney"):
y+=1
print(y)
output:
0
Ex:
def grandchild(array):
print([Link]("rooney"))
grandchild({"shaw":"luke","rooney":"wayne","ronaldo":"rooney","rooney":"shaw"})
output:
shaw
ex:
def test_prime(n):
if (n==1):
return False
#elif (n==2):
#return True;
else:
for x in range(2,n):
if(n % x==0): # assume n=8, therefore 1 in range(2,8) ---- 8%2=0==>false
return False
return True #assume n= 7,therefore 7 in range(2,7) -------- 7%2!=0 (so 7 is a [Link]
is true)
print(test_prime(7))
output:
True
Ex:
def test_prime(n):
if (n==1):
return False
#elif (n==2):
#return True;
else:
for x in range(2,n):
if(n % x==0): # assume n=8, therefore 1 in range(2,8) ---- 8%2=0==>false
return False
return True #assume n= 7,therefore 7 in range(2,7) -------- 7%2!=0 (so 7 is a [Link]
is true)
print(test_prime(8))
output:
False
Ex:
import string
def ispangram(str):
alphabet = "abcdefghijklmnopqrstuvwxyz"
for char in alphabet:
if char not in [Link]():
return False
return True
# Driver code
string = 'the quick brown fox jumps over the Lazy dog'
if(ispangram(string) == True):
print("Yes")
else:
print("No")
output:
Yes
Ex:
var='python with ML'
str='on'
print ([Link](str,0,10))
output:
4
Ex:
print ('288'.isdecimal())
output:
True
Ex:
output:
Python is. an easy lan
Ex:
output:
235
Ex:
output:
enter the list23,34,45,656
['2', '3', ',', '3', '4', ',', '4', '5', ',', '6', '5', '6']
Ex:
def sum(numbers):
sum = 0
for x in numbers:
sum=sum+ x
return sum
sum((8, 2, 3, 0, 7))
output:
20
Ex:
l=[34,45,67,89]
def sum():
sum = 0
#l=[34,45,67,89]
for x in l:
sum=sum+ x
return sum
sum()
output:
235
Ex:
output:
F
15 10
Har Fr e
63 13
0 1 gra 619 an m 42 2 0.00 1 1 1 1
46 48.
ve ce al
02 88
e
F
15 11
Sp e
64 8380 25
1 2 Hill 608 ai m 41 1 1 0 1 0
73 7.86 42.
n al
11 58
e
F
15 11
Fr e
61 Oni 1596 39
2 3 502 an m 42 8 3 1 0 1
93 o 60.80 31.
ce al
04 57
e
Cus Su Cre Ge G T B Num Ha IsAct Esti
Ro Ex
tom rn dit ogr en A en al OfPr sCr iveM mate
wN ite
erI a Sco ap de ge ur an oduc Ca embe dSal
um d
d me re hy r e ce ts rd r ary
ber
F
15 93
Fr e
70 Bon 82
3 4 699 an m 39 1 0.00 2 0 0 0
13 i 6.6
ce al
54 3
e
F
15 79
Mit Sp e
73 1255 08
4 5 chel 850 ai m 43 2 1 1 1 0
78 10.82 4.1
l n al
88 0
e
.
... ... ... ... ... ... ... ... ... ... ... ... ... ... .
.
15 96
Obi Fr M
999 999 60 27
jiak 771 an al 39 5 0.00 2 1 0 0
5 6 62 0.6
u ce e
29 4
15 10
Joh Fr M
999 999 56 5736 16
nsto 516 an al 35 10 1 1 1 0
6 7 98 9.61 99.
ne ce e
92 77
F
15 42
Fr e
999 999 58 08
Liu 709 an m 36 7 0.00 1 0 1 1
7 8 45 5.5
ce al
32 8
e
15 Ge 92
Sab M
999 999 68 rm 7507 88
bati 772 al 42 3 2 1 0 1
8 9 23 an 5.31 8.5
ni e
55 y 2
F
15 38
Fr e
999 100 62 Wal 1301 19
792 an m 28 4 1 1 0 0
9 00 83 ker 42.79 0.7
ce al
19 8
e
output:
Ex:
def sum(numbers):
sum=0
for i in numbers:
sum+=i
return sum
sum((8,2,3,-1,7))
output:
19
Ex:
def sum(n):
n=[1,2,3,4,5]
sum=0
for i in n:
sum=sum+i
return sum
sum(n)
output:
15
Ex:
def sum(numbers):
total = 0
for x in numbers:
total += x
return total
print(sum((8, 2, 3, -1, 7)))
output:
19
Ex:
Factorial program
def factorial(n):
if n == 0:
return 1
return n * factorial(n-1)
#n=int(input("Input a number to compute the factiorial : "))
#print(factorial(n))
factorial(5)
output:
120
Ex:
def multiply(numbers):
total = 1
for x in numbers:
total *= x
return total
print(multiply((8, 2, 3, -1, 7)))
output:
-336
Ex:
for i in range(10):
print(i)
output:
0
1
2
3
4
5
6
7
8
9
Ex:
i=1
while i<=10:
print("hai")
pass
break
output:
hai
ex:
def multiply():
total = 0
i=1
while i < 10:
total = total+i
i+=1
print(total)
multiply()
output:
1
3
6
10
15
21
28
36
45
Ex:
def multiply(n):
total = 1
i=1
while i < 10:
total = total*i
i+=1
pass
print(total)
multiply(5)
output:
1
2
6
24
120
720
5040
40320
362880
Ex:
total = 1
i=1
while i < 10:
total = total*i
i+=1
print(total)
continue
output:
1
2
6
24
120
720
5040
40320
362880
Ex:
def sum(numbers):
total = 0
for x in numbers:
total += x
return total
print(sum((8, 2, 3, -1, 7)))
output:
max= lambda a,b,c: a if(a>b) and (a>c) else b if(b>c) and (b>a) else c
print(max(1,20,5))
ex:
output:
65
Ex:
def test_range(n):
if n in range(3,9):
print( " %s is in the range"%str(n))
else :
print("The number is outside the given range.")
test_range(5)
output:
5 is in the range
Ex:
def test_range(n):
for n in range(3,9):
print( "n is in the range:",n)
test_range(7)
output:
n is in the range: 3
n is in the range: 4
n is in the range: 5
n is in the range: 6
n is in the range: 7
n is in the range: 8
ex:
a=13.456789
print('%.3f' %a)
output:
13.457
Ex:
"""ggjk
vkjgkhljk
ivkghohoh
lvblhl"""
a=10
b=90
c=a+b
print("welcome",c,"********",end='')
print("hai",c,'.....',sep='\t!')
output:
ex:
print("welcome", "hai",end="")
print(5)
output:
welcome hai5
ex:
st={1,1,2,2,3,4,4,4,4,5,5,5,6,7}
print(st)
output:
{1, 2, 3, 4, 5, 6, 7}
Ex:
def test(x=9,y=5,z=8):
print('x is',x, 'and y is',y,'and z is',z)
test(3,12)
output:
x is 3 and y is 12 and z is 8
ex:
#[Link] three classes to show parent, child, and grandchild relationships.
class parent:
def fun():
print("parent class")
p1=[Link]()
class child(parent):
def fun1():
#[Link]()
print("child")
p2=child.fun1()
class gchild(child):
def fun2():
#child.fun1()
print("gchild")
p3=gchild.fun2()
p3
output:
parent class
child
gchild
ex:
'''
#4. What is the output of the following code?
class Fruit:
def taste(self):
str = "Sweet"
return str
class Lemon(Fruit):
def taste(self):
str = "Sour"
return super().taste()
lemon1 = Lemon()
print([Link]())
output:
Sweet
Ex:
#Write a Python program to create a lambda function that adds 15 to a given number passed
in as an argument
output:
Ex:
add_15 = lambda x : x + 15
result = add_15(num)
output:
Ex:
#create a lambda function that multiplies argument x with argument y and print the result.
m =lambda x,y:x*y
print(m(12,4))
output:48
ex:
output:
type your number 1:6
type your number 2:7
42
Ex:
output:
Ex:
#Write a Python program to create a function that takes one argument, and that argument will
be multiplied with an unknown given number.
a=int(input("type ur num"))
multi = [lambda a=i: a*a for i in range(2,6)]
for f in multi:
print(f())
output:
type ur num5
4
9
16
25
Ex:
x = int(input("type ur num"))
multiply = lambda y: x * y
print('Double the number of', x, '=', multiply(2))
print('Triple the number of', x, '=', multiply(3))
print('Quadruple the number of', x, '=', multiply(4))
print('Quintuple the number of', x, '=', multiply(5))
output:
type ur num6
Double the number of 6 = 12
Triple the number of 6 = 18
Quadruple the number of 6 = 24
Quintuple the number of 6 = 30
Ex:
marks = [('English', 88), ('Science', 90), ('Maths', 97), ('Social sciences', 82)]
[Link](key = lambda x: x[1])
print("Sorting the List of marks:")
print(marks)
output:
Ex:
a=input("subject name")
a1=int(input("mark of a"))
b=input("subject name")
b1=int(input("mark of b"))
c=input("subject name")
c1=int(input("mark of c"))
d=input("subject name")
d1=int(input("mark of d"))
marks = [(a, a1), (b, b1), (c, c1), (d, d1)]
[Link](key = lambda x: x[1])
print("Sorting the List of marks:")
print(marks)
output:
subject namescience
mark of a56
subject namemaths
mark of b67
subject namesocial
mark of c89
subject nameenglish
mark of d67
Sorting the List of marks:
[('science', 56), ('maths', 67), ('english', 67), ('social', 89)]
Ex:
out=lambda x,y:x*y
print(out(12,13))
output:
156
Ex:
out=lambda x:x*23
print(out(12))
output:
276
Ex:
x=90
out=lambda x:x*23
print(out(x))
output:
2070
Ex:
output:
enter the value12
276
Ex:
output:
y is greater
ex:
output:
34
Ex:
out= lambda x,y: f"{x} is greater" if x>y else f"{y} is greater"
print(out(12,34))
output:
34 is greater
Ex:
out= lambda x,y,z: f"{x} is greater" if x>y and x>z else ( f"{y} is greater" if y>z and y>x
else f"{z} is greater")
print(out(12,34,45))
output:
45 is greater
Ex:
x,y,z=int(input("enter the x value")),int(input("enter the y value")),int(input("enter the z
value"))
out= lambda x,y,z: f"{x} is greater" if x>y and x>z else f"{y} is greater" if y>z and y>x
else f"{z} is greater"
print(out(x,y,z))
output:
enter the x value45
enter the y value56
enter the z value78
78 is greater
Ex:
"""
1. Write a Python program to create a lambda function that adds 15 to a given number passed
in as an argument, also create a lambda function that multiplies argument x with argument y
and print the result"""
r = lambda a : a + 15
print(r(10))
output:
25
Ex:
r = lambda x, y : x * y
print(r(12, 4))
output:
48
Ex:
output=lambda a,b:a*b
print(output(12,13))
output:
156
Ex:
def multi(x,y):
return x*y
multi(12,23)
output:
276
Ex:
"""2. Write a Python program to create a function that takes one argument, and that argument
will be multiplied with an unknown given number."""
def multi(n):
return lambda x : x * n
result = multi(2)
print("Double the number of 15 =", result(15))
output:
Double the number of 15 = 30
Ex:
print()
# Driver Function
display(5)
output:
**
****
**
****
**
Ex:
output:
*
**
***
****
*****
Ex:
for i in range(6,0,-1):
print('*'*i)
output:
******
*****
****
***
**
*
Ex:
for i in range(1,6,1):
print('1'*i)
output:
1
11
111
1111
11111
Ex:
output:
1
12
123
1234
Ex:
Country=["india","Pakistan","srilanka","Maldives"]
Country[2]="Singapore"
print(Country)
[Link]("india")
print(Country)
[Link]("kk")
print(Country)
[Link]()
print(Country)
Country=["india","Pakistan","srilanka","Maldives"]
[Link]()
print(Country)
print([Link]())
print([Link]())
output:
Ex:
my_dict = {1: 'apple', 2: 'ball'}
my_dict.get(1)
output:
apple
ex:
my_dict = {"@": 'apple', 2.4: 'ball',"@": 'apple', 2.4: 'ball'}
my_dict
output:
{'@': 'apple', 2.4: 'ball'}
Ex:
output:
{'@': 'apple', 2.4: 'ball'}
Ex:
set = {1,2,3,4,5,6,7,7,8,8,8,9}
print(set)
output:
{1, 2, 3, 4, 5, 6, 7, 8, 9}
Ex:
output:
[2, 4, 3]
Ex:
output:
John
DATASCIENCE CODING
SOURCE CODE 1:
import numpy as np
print("Creating array using numpy")
a=[Link](10)
b=[Link]([10.0,20.0,45.0,64.0,72.5])
c=[Link]([[10,20,30],[40,50,100]])
d=[Link]([[[1,2,3],[4,5,6]],[[7,8,9],[4,3,2]]])
print("Creating array with range function")
ar1=[Link](10)
print(ar1)
ar2=[Link](1,11)
print(ar2)
ar3=[Link](10,30,2)
print(ar3)
ar4=[Link](-20,6,5)
print(ar4)
print("Creating 1-D array with zero values")
array1=[Link](5)
print(array1)
print("Creating 2-D array with zero values")
array2=[Link]((2,3))
print(array2)
print("Creating 3-D array with zero values")
array3=[Link]((4,3,5))
print(array3)
print("Creating 1-D array with full function")
array_1=[Link](shape=5, fill_value=6)
print(array_1)
print("Creating 2-D array with zero values")
array_2=[Link](shape=(2,3),fill_value=8)
print(array_2)
print("Creating 3-D array with zero values")
array_3=[Link](shape=(4,3,5),fill_value=3)
print(array_3)
print("Display the content of different arrays")
print(a)
print(b)
print(c)
print(d)
print("Type and Dimensions of different arrays")
print("Type of array a=",type(a))
print("Dimension of array a=",[Link])
print("Dimension of array b=",[Link])
print("Dimension of array c=",[Link])
print("Dimension of array d=",[Link])
print("properties of array")
print("Data type of array a=",[Link])
print("Data type of array b=",[Link])
print("Size of different arrays")
print("Size of array a=",[Link])
print("Size of array b=",[Link])
print("Size of array c=",[Link])
print("Size of array d=",[Link])
print("Memory space require to store each element in array a=",[Link])
print("Memory space require to store each element in array b=",[Link])
print("change the dimension of array")
print([Link](3,2))
print("Statistical functions using array")
a1=[Link]([[4,8],[6,12]])
b1=[Link](a1,axis=0)
b2=[Link](a1,axis=1)
print("Mean releated with axis 0=",b1)
print("Mean releated with axis 1=",b2)
a2=[Link]([[1,4,5,6],[3,5,7,8],[8,9,6,5]])
c1=[Link](a2,axis=0)
c2=[Link](a2,axis=1)
print("Median releated with axis 0=",c1)
print("Median releated with axis 1=",c2)
c3=[Link](a2,axis=0)
print("Standard deviation of array a2 related with axis 0=",c3)
print("inserting data inside the existing array");
i=[Link]([[3,5],[9,8]])
j=[Link]([[10,12],[21,22]])
k=[Link](i,j)
print(k)
print("broadcasting of value in specific axis of an array")
m=[Link]([[1,5],[2,4],[3,6],[8,9]])
print([Link](m,2,[9],axis=0))
print([Link](m,2,[9],axis=1))
print([Link](m,1,[9],axis=1))
print("Concatenation of two arrays")
i1=[Link]([[6,7],[8,9]])
j1=[Link]([[1,2]])
k1=[Link]((i1,j1))
print(k1)
print("Mathamatical function using NumPy")
print("Addition of two arrays")
print(i+j)
print("Alternative approch")
print([Link](i,j))
print("Substraction of two arrays")
print(i-j)
print("Alternative approch")
print([Link](i,j))
print("Multiplication of two arrays")
print(i*j)
print("Alternative approch")
print([Link](i,j))
print("division of two arrays")
print(i/j)
print("Alternative approch")
print([Link](i,j))
print("creating array with random value between 0 and 1")
i3=[Link](3,3)
print(i3)
print("Soted array content:")
s_arr=[Link](k)
print(s_arr)
print("Accessing array elements using index")
print("Second element in array b=",b[0])
print("The value of second element in second row in array c=",c[1][1])
print("last element in First row of array c=",c[0,-1])
print("last element in Second row of array c=",c[1,-1])
print("Accessing 3 dimensional array content:")
print(d[0,1,2])
print("1-D Array with slice function")
print(b[1:4])
print(b[:3])
print(b[2:5])
print(b[-4:-2])
print("2-D Array with slice function")
print(c[0:,0:1])
print("3-D Array with slice function")
print(d[0,1,0:2])
OUTPUT:
Creating array using numpy
Creating array with range function
[0 1 2 3 4 5 6 7 8 9]
[ 1 2 3 4 5 6 7 8 9 10]
[10 12 14 16 18 20 22 24 26 28]
[-20 -15 -10 -5 0 5]
Creating 1-D array with zero values
[0. 0. 0. 0. 0.]
Creating 2-D array with zero values
[[0. 0. 0.]
[0. 0. 0.]]
Creating 3-D array with zero values
[[[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]]
[[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]]
[[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]]
[[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]]]
Creating 1-D array with full function
[6 6 6 6 6]
Creating 2-D array with zero values
[[8 8 8]
[8 8 8]]
Creating 3-D array with zero values
[[[3 3 3 3 3]
[3 3 3 3 3]
[3 3 3 3 3]]
[[3 3 3 3 3]
[3 3 3 3 3]
[3 3 3 3 3]]
[[3 3 3 3 3]
[3 3 3 3 3]
[3 3 3 3 3]]
[[3 3 3 3 3]
[3 3 3 3 3]
[3 3 3 3 3]]]
Display the content of different arrays
10
[10. 20. 45. 64. 72.5]
[[ 10 20 30]
[ 40 50 100]]
[[[1 2 3]
[4 5 6]]
[[7 8 9]
[4 3 2]]]
Type and Dimensions of different arrays
Type of array a= <class '[Link]'>
Dimension of array a= 0
Dimension of array b= 1
Dimension of array c= 2
Dimension of array d= 3
properties of array
Data type of array a= int32
Data type of array b= float64
Size of different arrays
Size of array a= ()
Size of array b= (5,)
Size of array c= (2, 3)
Size of array d= (2, 2, 3)
Memory space require to store each element in array a= 4
Memory space require to store each element in array b= 8
change the dimension of array
[[ 10 20]
[ 30 40]
[ 50 100]]
Statistical functions using array
Mean releated with axis 0= [ 5. 10.]
Mean releated with axis 1= [6. 9.]
Median releated with axis 0= [3. 5. 6. 6.]
Median releated with axis 1= [4.5 6. 7. ]
Standard deviation of array a2 related with axis 0= [2.94392029 2.1602469
0.81649658 1.24721913]
inserting data inside the existing array
[ 3 5 9 8 10 12 21 22]
broadcasting of value in specific axis of an array
[[1 5]
[2 4]
[9 9]
[3 6]
[8 9]]
[[1 5 9]
[2 4 9]
[3 6 9]
[8 9 9]]
[[1 9 5]
[2 9 4]
[3 9 6]
[8 9 9]]
Concatenation of two arrays
[[6 7]
[8 9]
[1 2]]
Mathamatical function using NumPy
Addition of two arrays
[[13 17]
[30 30]]
Alternative approch
[[13 17]
[30 30]]
Substraction of two arrays
[[ -7 -7]
[-12 -14]]
Alternative approch
[[ -7 -7]
[-12 -14]]
Multiplication of two arrays
[[ 30 60]
[189 176]]
Alternative approch
[[ 30 60]
[189 176]]
division of two arrays
[[0.3 0.41666667]
[0.42857143 0.36363636]]
Alternative approch
[[0.3 0.41666667]
[0.42857143 0.36363636]]
creating array with random value between 0 and 1
[[0.71741742 0.76694434 0.46223485]
[0.44627637 0.95567247 0.34222874]
[0.56830415 0.58420945 0.78117302]]
Soted array content:
[ 3 5 8 9 10 12 21 22]
Accessing array elements using index
Second element in array b= 10.0
The value of second element in second row in array c= 50
last element in First row of array c= 30
last element in Second row of array c= 100
Accessing 3 dimensional array content:
6
1-D Array with slice function
[20. 45. 64.]
[10. 20. 45.]
[45. 64. 72.5]
[20. 45.]
2-D Array with slice function
[[10]
[40]]
3-D Array with slice function
[4 5]
SOURCE CODE 2:
Import pandas as pd
Import numpy as np
Print(“Create a series from ndarray”)
List1=[Link]([‘x’,’y’,’z’])
x=[Link](List1)
print(x)
print(“Create a series from dictonary”)
data={‘a’:100,’b’:200,’c’:300}
x1=[Link](data)
print(x1)
print(“Create a Data framefrom List”)
list2=[10,20,30,40,50]
x2=[Link](list2)
print(x2)
print(“Create a data frame dictionary”)
dict1={“Tamilnadu”:”Chennai”,”Karnataka”:”Bangalaru”,”Maharastra”:”Mum
bai”}
x3=[Link](dict1)
print(x3)
print(“Create a data frame using dictionary”)
dict2={“Ram”:25,”Robert”:24,”Rahim”:22}
x4=[Link](dict2)
print(“Create data from Series dictionary”)
x5={“States”:[Link]([“Tamilnadu”,”Andhra”,”Orissa”])
“capital”:[Link]([“Chennai”,”Hyderabad”,”Bhuneswar”])}
Dict2=[Link](x5)
print(dict2)
print("To delete a columns")
del dict2["cm"]import pandas as pd
import numpy as np
print("create a Series from nd array")
List1=[Link](['x','y','z'])
x=[Link](List1)
print(x)
print("create a Series from idictionary")
data={'a':120,'b':220,'c':300}
x1=[Link](data)
print("create a Data Frame using List")
List2=[10,20,30,40,50]
x2=[Link](List2)
print(x2)
print("create a DataFrame using dictionary")
mat1=(["ram",25],["robert,23"],["mohamed",21])
x3=[Link](mat1,columns=["name","age"])
print(x3)
print("create a DataFrame from dictionary")
dict1={"Tamilnadu":"Chennai",
"Karnataka":"Bangalore",
"Maharashra":"Mumbai"
}
x4=[Link](dict1,index=[0])
print(x4)
x5={"State":[Link](["Taminadu","Andhra","Odisha"]),
"Capital":[Link](["Chennai","Hyderabed","Bhavaneshwar"])
}
dict2=[Link](x5)
print(dict2)
print(“To print a Coloumn…”)
print(dict2["State"])
print("To add a new column")
dict2["cm"]=[Link](["Stalin","Bomm
print(dict2)
print("To sort a value")
Sort_dict=dict2.sort_values(by="State")
print(Sort_dict)
OUTPUT:
Create a series from ndarray
0 x
1 y
2 z
dtype: object
Create a series from dictonary
a 100
b 200
c 300
dtype: int64
Create a Data framefrom List
0
0 10
1 20
2 30
3 40
4 50
Create a data frame dictionary
States Capital
0 Tamilnadu Chennai
1 Karnataka Bangalaru
2 Maharastra Mumbai
Create a data frame using dictionary
Name Age
0 Ram 25
1 Robert 24
2 Rahim 22
Create data from Series dictionary
States capital
0 Tamilnadu Chennai
1 Andhra Hyderabad
2 Orissa Bhuvaneswar
To delete a columns
capital
0 Chennai
1 Hyderabad
2 Bhuvaneswar
State Capital
0 Taminadu Chennai
1 Andhra Hyderabed
2 Odisha Bhavaneshwar
To Print a Coloumn
0 Taminadu
1 Andhra
2 Odisha
Name: State, dtype: object
To add a new column
State Capital cm
0 Taminadu Chennai stalin
1 Andhra Hyderabed Boomai
2 Odisha Bhavaneshwar Naveen Patnayak
To sort a value
State Capital cm
1 Andhra Hyderabed Boomai
2 Odisha Bhavaneshwar Naveen Patnayak
0 Taminadu Chennai stalin
SOURCE CODE 3:
import pandas as pd
print("pandas using csv....")
movies=pd.read_csv("E:\[Link]")
print([Link]())
print("To read last five Rows.... ")
print([Link]())
print("To display information about the data")
print([Link]())
print("To display the size of the dataset")
print([Link])
print("[Link]")
print("To print the column names in the data set")
print([Link])
print("To identify the null values column")
print([Link]())
print("To count the no of cells in each column")
print([Link]().sum())
print("To display summary of variable")
print([Link]())
print("To retrieve a specific column")
sub=movies[["Star1","Star2"]]
print(sub)
print("To retrieve from Row")
rowwise=[Link][2:5]
print(rowwise)
print("To retrive from Row using index")
rowwise1=[Link][1]
print(rowwise1)
print("To retrieve specific rows")
sub_movies=[Link][2:4]
sub_movies=[Link][1:4]
print(sub_movies)
print("To retrieve data from conditional selection")
cond=(movies["Director"]=="Peter Jackson")
print(cond)
print("conditional selection using numbers")
cond1=(movies["Rating"]>=8.6)
print(cond1)
OUTPUT:
pandas using csv....
Poster_Link ... Gross
0 [Link] ... 2,83,41,469
1 [Link] ... 13,49,66,411
2 [Link] ... 53,48,58,444
3 [Link] ...
5,73,00,000
4 [Link] ... 43,60,000
[5 rows x 16 columns]
To read last five Rows....
Poster_Link ... Gross
995 [Link] ... NaN
996 [Link] ... NaN
997 [Link] ... 3,05,00,000
998 [Link] ... NaN
999 [Link] ... NaN
[5 rows x 16 columns]
To display information about the data
<class '[Link]'>
RangeIndex: 1000 entries, 0 to 999
Data columns (total 16 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Poster_Link 1000 non-null object
1 Series_Title 1000 non-null object
2 Released_Year 1000 non-null object
3 Certificate 899 non-null object
4 Runtime 1000 non-null object
5 Genre 1000 non-null object
6 Rating 1000 non-null float64
7 Overview 1000 non-null object
8 Meta_score 843 non-null float64
9 Director 1000 non-null object
10 Star1 1000 non-null object
11 Star2 1000 non-null object
12 Star3 1000 non-null object
13 Star4 1000 non-null object
14 No_of_Votes 1000 non-null int64
15 Gross 831 non-null object
dtypes: float64(2), int64(1), object(13)
memory usage: 125.1+ KB
None
To display the size of the dataset
(1000, 16)
To print the column names in the data set
Index(['Poster_Link', 'Series_Title', 'Released_Year', 'Certificate',
'Runtime', 'Genre', 'Rating', 'Overview', 'Meta_score', 'Director',
'Star1', 'Star2', 'Star3', 'Star4', 'No_of_Votes', 'Gross'],
dtype='object')
To identify the null values column
Poster_Link Series_Title Released_Year ... Star4 No_of_Votes Gross
0 False False False ... False False False
1 False False False ... False False False
2 False False False ... False False False
3 False False False ... False False False
4 False False False ... False False False
.. ... ... ... ... ... ... ...
995 False False False ... False False True
996 False False False ... False False True
997 False False False ... False False False
998 False False False ... False False True
999 False False False ... False False True
[1000 rows x 16 columns]
To count the no of cells in each column
Poster_Link 0
Series_Title 0
Released_Year 0
Certificate 101
Runtime 0
Genre 0
Rating 0
Overview 0
Meta_score 157
Director 0
Star1 0
Star2 0
Star3 0
Star4 0
No_of_Votes 0
Gross 169
dtype: int64
To display summary of variable
Rating Meta_score No_of_Votes
count 1000.000000 843.000000 1.000000e+03
mean 7.949300 77.971530 2.736929e+05
std 0.275491 12.376099 3.273727e+05
min 7.600000 28.000000 2.508800e+04
25% 7.700000 70.000000 5.552625e+04
50% 7.900000 79.000000 1.385485e+05
75% 8.100000 87.000000 3.741612e+05
max 9.300000 100.000000 2.343110e+06
To retrieve a specific column
Star1 Star2
0 Tim Robbins Morgan Freeman
1 Marlon Brando Al Pacino
2 Christian Bale Heath Ledger
3 Al Pacino Robert De Niro
4 Henry Fonda Lee J. Cobb
.. ... ...
995 Audrey Hepburn George Peppard
996 Elizabeth Taylor Rock Hudson
997 Burt Lancaster Montgomery Clift
998 Tallulah Bankhead John Hodiak
999 Robert Donat Madeleine Carroll
[3 rows x 16 columns]
To retrive from Row using index
Poster_Link [Link]
Series_Title The Godfather
Released_Year 1972
Certificate A
Runtime 175 min
Genre Crime, Drama
Rating 9.2
Overview An organized crime dynasty's aging patriarch t...
Meta_score 100.0
Director Francis Ford Coppola
Star1 Marlon Brando
Star2 Al Pacino
Star3 James Caan
Star4 Diane Keaton
No_of_Votes 1620367
Gross 13,49,66,411
Name: 1, dtype: object
To retrieve specific rows
Poster_Link ... Gross
1 [Link] ... 13,49,66,411
2 [Link] ... 53,48,58,444
3 [Link] ...
5,73,00,000
[3 rows x 16 columns]
To retrieve data from conditional selection
0 False
1 False
2 False
3 False
4 False
Name: Director, dtype: bool
conditional selection using numbers
0 True
1 True
2 True
3 True
4 True
995 False
996 False
997 False
998 False
999 False
Name: Rating, Length: 1000, dtype: bool
SOURCE CODE 4:
import numpy as np
import pandas as pd
import [Link] as mtp
from [Link] import SimpleImputer
from [Link] import LabelEncoder, OneHotEncoder
from [Link] import ColumnTransformer
from sklearn.model_selection import train_test_split
from [Link] import StandardScaler
# imputer = SimpleImputer(missing_values=[Link], strategy='mean')
print("to print and import dataset")
data=pd.read_csv("E:\[Link]")
print([Link]())
print([Link]())
print("to extract and print independent variable")
x=[Link][:,:-1].values
print(x)
print("to extract and print dependent variable")
y=[Link][:,3].values
print(y)
print("to handle missing data")
print("to replace missing value with mean value ")
imputer = SimpleImputer(missing_values = [Link], strategy =
'mean',verbose=0)
imputer = [Link](x[:, 1:3])
x[:, 1:3] = [Link](x[:, 1:3])
print(x)
print("to convert country variablr and print")
label_encoder_x=LabelEncoder()
x[:,0]=label_encoder_x.fit_transform(x[:,0])
print(x)
print("to count and print purchase variable")
LabelEncoder_y=LabelEncoder()
y=LabelEncoder_y.fit_transform(y)
print(y)
print("encoding and print dummy variable")
labelencoder_x = LabelEncoder()
x[:,0] = labelencoder_x.fit_transform(x[:,0])
ct = ColumnTransformer([("Country", OneHotEncoder(), [0])], remainder =
'passthrough')
x = ct.fit_transform(x)
print("to perform test and train split")
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=0)
print("the x training test data")
print(x_train)
print("the x testing data")
print(x_test)
print("the y training dataset")
print(y_train)
print("the y testing data")
print(y_test)
print("to perform feature scaling and print dataset values")
st_x=StandardScaler()
x_train=st_x.fit_transform(x_train)
x_test=st_x.transform(x_test)
print("training dataset after scaling")
print(x_train)
print("testing dataset after scaling")
print(x_test)
OUTPUT:
to print and import dataset
country age salary purchase
0 India 38.0 68000.0 No
1 France 43.0 45000.0 Yes
2 Germany 30.0 54000.0 No
3 France 48.0 65000.0 No
4 Germany 40.0 NaN Yes
country age salary purchase
5 India 35.0 58000.0 Yes
6 Germany NaN 53000.0 No
7 France 49.0 79000.0 Yes
8 India 50.0 88000.0 No
9 France 37.0 77000.0 Yes
to extract and print independent variable
[['India' 38.0 68000.0]
['France' 43.0 45000.0]
['Germany' 30.0 54000.0]
['France' 48.0 65000.0]
['Germany' 40.0 nan]
['India' 35.0 58000.0]
['Germany' nan 53000.0]
['France' 49.0 79000.0]
['India' 50.0 88000.0]
['France' 37.0 77000.0]]
to extract and print dependent variable
['No' 'Yes' 'No' 'No' 'Yes' 'Yes' 'No' 'Yes' 'No' 'Yes']
to handle missing data
to replace missing value with mean value
[['India' 38.0 68000.0]
['France' 43.0 45000.0]
['Germany' 30.0 54000.0]
['France' 48.0 65000.0]
['Germany' 40.0 65222.22222222222]
['India' 35.0 58000.0]
['Germany' 41.111111111111114 53000.0]
['France' 49.0 79000.0]
['India' 50.0 88000.0]
['France' 37.0 77000.0]]
to convert country variablr and print
[[2 38.0 68000.0]
[0 43.0 45000.0]
[1 30.0 54000.0]
[0 48.0 65000.0]
[1 40.0 65222.22222222222]
[2 35.0 58000.0]
[1 41.111111111111114 53000.0]
[0 49.0 79000.0]
[2 50.0 88000.0]
[0 37.0 77000.0]]
to count and print purchase variable
[0 1 0 0 1 1 0 1 0 1]
encoding and print dummy variable
to perform test and train split
the x training test data
[[0.0 1.0 0.0 40.0 65222.22222222222]
[1.0 0.0 0.0 37.0 77000.0]
[1.0 0.0 0.0 43.0 45000.0]
[0.0 1.0 0.0 41.111111111111114 53000.0]
[1.0 0.0 0.0 49.0 79000.0]
[1.0 0.0 0.0 48.0 65000.0]
[0.0 0.0 1.0 38.0 68000.0]
[0.0 0.0 1.0 35.0 58000.0]]
the x testing data
[[0.0 1.0 0.0 30.0 54000.0]
[0.0 0.0 1.0 50.0 88000.0]]
the y training dataset
[1 1 1 0 1 0 0 1]
the y testing data
[0 0]
to perform feature scaling and print dataset values
training dataset after scaling
[[-1. 1.73205081 -0.57735027 -0.29460737 0.1339619 ]
[ 1. -0.57735027 -0.57735027 -0.93095928 1.22626663]
[ 1. -0.57735027 -0.57735027 0.34174455 -1.74150472]
[-1. 1.73205081 -0.57735027 -0.05892147 -0.99956188]
[ 1. -0.57735027 -0.57735027 1.61444837 1.41175234]
[ 1. -0.57735027 -0.57735027 1.40233107 0.11335238]
[-1. -0.57735027 1.73205081 -0.71884198 0.39158094]
[-1. -0.57735027 1.73205081 -1.35519389 -0.5358476 ]]
testing dataset after scaling
[[-1. 1.73205081 -0.57735027 -2.41578041 -0.90681902]
[-1. -0.57735027 1.73205081 1.82656568 2.24643804]]
SOURCE CODE 5:
Import numpy as np
Import [Link] as plt
From sklearn.linear_model import LinearRegression
From [Link] import mean_squared_error
temp=[20,25,30,35,40]
ice=[13,21,25,35,38]
x=[Link]([temp]).T
y=[Link](ice)
rmodel=LinearRegression()
rmodel=[Link](x,y)
rmodel_slope=rmodel.coef_
print(“Model Slope=”,rmodel_slope)
rmodel_intercept=rmodel.intercept_
print(“Model Intercept=”,rmodel_intercept)
y_predict=[Link](x)
rmse=[Link](mean_squared_error(y,y_predict))
print(“Model RMSE=”,rmse)
r2=[Link](x,y)
print(“ R Square Error=”,r2)
[Link](temp,ice,marker='*',edgecolors='r')
[Link](temp,y_predict,'-bo')
[Link]()
OUTPUT:
Model Slope= [1.28]
Model Intercept= -12.0
Model RMSE= 1.3856406460551007
R Square Error= 0.9770992366412214
SOURCE CODE 6:
import pandas as pd
import numpy as np
from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import train_test_split
from [Link] import accuracy_score
data=pd.read_csv("D:\datasets_puthon\[Link]")
print("The content of Sample data set are...")
print([Link]())
X=[Link][:,:-1].values
y=[Link][:,-1].values
print("The shape of Indenpendent data is")
print([Link])
print("The shape of dependent data is")
print([Link])
gnb=GaussianNB()
X_test,X_train,y_test,y_train=train_test_split(X,y,test_size=30)
[Link](X_train,y_train)
y_pred=[Link](X_test)
acc=accuracy_score(y_test,y_pred)
print("The accuracy naive bayes algorithm=",acc*100)
OUTPUT:
The content of Sample data set are...
sepal length (cm) sepal width (cm) ... petal width (cm) target
0 5.1 3.5 ... 0.2 Iris-setosa
1 4.9 3.0 ... 0.2 Iris-setosa
2 4.7 3.2 ... 0.2 Iris-setosa
3 4.6 3.1 ... 0.2 Iris-setosa
4 5.0 3.6 ... 0.2 Iris-setosa
[5 rows x 5 columns]
The shape of Indenpendent data is
(150, 4)
The shape of dependent data is
(150,)
Accuracy of Naive Bayes Algorithm= 95.0
SOURCE CODE 7:
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from [Link] import StandardScaler
from sklearn.linear_model import LogisticRegression
from [Link] import confusion_matrix,accuracy_score
ds=pd.read_csv("D:\[Link]")
print("Display the First 5 rows of data set")
print([Link]())
X=[Link][:,:-1].values
print("The content of independent variable are")
print(X)
y=[Link][:,-1].values
print("The content of dependent variable are")
print(y)
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.30)
sc=StandardScaler()
X_train=sc.fit_transform(X_train)
X_test=[Link](X_test)
classifier=LogisticRegression()
[Link](X_train,y_train)
y_pred=[Link](X_test)
cm=confusion_matrix(y_test,y_pred)
print("The Result of confusion matrix is given below")
print(cm)
res=accuracy_score(y_test,y_pred)
print("The accuracy of Logistic Regression=",res*100)
OUTPUT:
Display the First 5 rows of data set
Sample code number Clump Thickness ... Mitoses Class
0 1000025 5 ... 1 2
1 1002945 5 ... 1 2
2 1015425 3 ... 1 2
3 1016277 6 ... 1 2
4 1017023 4 ... 1 2
[5 rows x 11 columns]
The content of independent variable are
[[1000025 5 1 ... 3 1 1]
[1002945 5 4 ... 3 2 1]
[1015425 3 1 ... 3 1 1]
...
[ 888820 5 10 ... 8 10 2]
[ 897471 4 8 ... 10 6 1]
[ 897471 4 8 ... 10 4 1]]
SOURCE CODE 8:
import numpy as np
import pandas as pd
from [Link] import SimpleImputer
from [Link] import MinMaxScaler
from sklearn import model_selection
from [Link] import BaggingClassifier
from [Link] import DecisionTreeClassifier
from [Link] import AdaBoostClassifier
from sklearn.linear_model import LogisticRegression
from [Link] import DecisionTreeClassifier
from [Link] import SVC
from [Link] import VotingClassifier
ds=pd.read_csv("D:\datasets_puthon\[Link]")
print("The content of sample data set are")
print([Link]())
[Link](['Sample code number'],axis=1,inplace=True)
print("The content after dropping coloumn are")
print([Link]())
print("The description about the data set...")
[Link]()
print("The information about the data set are...")
print([Link]())
print("The content of first 25 Bare Nuclei coloumn in the data set...")
print(ds['Bare Nuclei'].head(25))
[Link]('?',0,inplace=True)
print("The content of first 25 Bare Nuclei coloumn in the data set after replacing
null values...")
print(ds['Bare Nuclei'].head(25))
values=[Link]
impute=SimpleImputer()
impute_data=impute.fit_transform(values)
scaler=MinMaxScaler(feature_range=(0,1))
scaler_data=scaler.fit_transform(impute_data)
X=scaler_data[:,0:9]
y=scaler_data[:,9]
kfold=model_selection.KFold(n_splits=10)
cart=DecisionTreeClassifier()
num_trees=100
model=BaggingClassifier(base_estimator=cart,n_estimators=num_trees,random
_state=7)
results=model_selection.cross_val_score(model,X,y,cv=kfold)
print("The accuracy of the Bagging Ensemble Algorithm is given below:")
print([Link]()*100)
seed=7
num_trees=70
kfold=model_selection.KFold(n_splits=10,shuffle=True)
model=AdaBoostClassifier(n_estimators=num_trees,random_state=seed)
results=model_selection.cross_val_score(model,X,y,cv=kfold)
print("The accuracy of the AdaBoost Ensemble Algorithm is given below:")
print([Link]()*100)
kfold=model_selection.KFold(n_splits=100)
estimators=[]
model1=LogisticRegression()
model2=DecisionTreeClassifier()
model3=SVC()
model=VotingClassifier(estimators=[('logistic',model1),('cart',model2),('svm',m
odel3)],voting='hard')
results=model_selection.cross_val_score(model,X,y,cv=kfold)
kfold=model_selection.KFold(n_splits=100)
estimators=[]
print("The accuracy of the Voting Ensemble Algorithm is given below:")
print([Link]()*100)
OUTPUT:
The content of sample data set are
Sample code number Clump Thickness ... Mitoses Class
0 1000025 5 ... 1 2
1 1002945 5 ... 1 2
2 1015425 3 ... 1 2
3 1016277 6 ... 1 2
4 1017023 4 ... 1 2
[5 rows x 11 columns]
The content after dropping coloumn are
Clump Thickness Uniformity of Cell Size ... Mitoses Class
0 5 1 ... 1 2
1 5 4 ... 1 2
2 3 1 ... 1 2
3 6 8 ... 1 2
4 4 1 ... 1 2
[5 rows x 10 columns]
The description about the data set...
The information about the data set are...
<class '[Link]'>
RangeIndex: 699 entries, 0 to 698
Data columns (total 10 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Clump Thickness 699 non-null int64
1 Uniformity of Cell Size 699 non-null int64
2 Uniformity of Cell Shape 699 non-null int64
3 Marginal Adhesion 699 non-null int64
4 Single Epithelial Cell Size 699 non-null int64
5 Bare Nuclei 699 non-null object
6 Bland Chromatin 699 non-null int64
7 Normal Nucleoli 699 non-null int64
8 Mitoses 699 non-null int64
9 Class 699 non-null int64
dtypes: int64(9), object(1)
memory usage: 54.7+ KB
None
The content of first 25 Bare Nuclei coloumn in the data set...
0 1
1 10
2 2
3 4
4 1
5 10
6 10
7 1
8 1
9 1
10 1
11 1
12 3
13 3
14 9
15 1
16 1
17 1
18 10
19 1
20 10
21 7
22 1
23 ?
24 1
Name: Bare Nuclei, dtype: object
The content of first 25 Bare Nuclei coloumn in the data set after replacing null
values...
0 1
1 10
2 2
3 4
4 1
5 10
6 10
7 1
8 1
9 1
10 1
11 1
12 3
13 3
14 9
15 1
16 1
17 1
18 10
19 1
20 10
21 7
22 1
23 0
24 1
Name: Bare Nuclei, dtype: object
The accuracy of the Bagging Ensemble Algorithm is given below:
95.85714285714285
The accuracy of the AdaBoost Ensemble Algorithm is given below:
95.9896480331263
The accuracy of the Voting Ensemble Algorithm is given below:
96.42857142857143
SOURCE CODE 9:
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from [Link] import DecisionTreeClassifier
from [Link] import accuracy_score
import [Link] as plt
from sklearn import tree
dis=pd.read_csv("D:\datasets_puthon\deci_tree.csv")
print("display sample records from the data set are...")
print([Link]())
X=[Link](['Outcome'],axis=1)
y=dis['Outcome']
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.30,random_state=
1)
clf=DecisionTreeClassifier()
clf=[Link](X_train,y_train)
y_pred=[Link](X_test)
result=accuracy_score(y_test,y_pred)
print("Accuracy of the Algorithm=",result*100,"%")
clf=DecisionTreeClassifier(criterion='entropy',max_depth=7)
clf=[Link](X_train,y_train)
y_pred=[Link](X_test)
res=accuracy_score(y_test,y_pred)
print("The accuracy of modified metrics=",res*100,"%")
[Link](figsize=(30,20))
tree.plot_tree(clf,fontsize=40,filled=True,rounded=True,max_depth=3)
[Link]()
OUTPUT:
display sample records from the data set are...
Pregnancies Glucose BloodPressure ... DiabetesPedigreeFunction Age
Outcome
0 6 148 72 ... 0.627 50 1
1 1 85 66 ... 0.351 31 0
2 8 183 64 ... 0.672 32 1
3 1 89 66 ... 0.167 21 0
4 0 137 40 ... 2.288 33 1
[5 rows x 9 columns]
Accuracy of the Algorithm= 69.6969696969697 %
The accuracy of modified metrics= 77.48917748917748 %
[5 rows x 5 columns]
The value of X in data set are...
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm)
0 5.1 3.5 1.4 0.2
1 4.9 3.0 1.4 0.2
2 4.7 3.2 1.3 0.2
3 4.6 3.1 1.5 0.2
4 5.0 3.6 1.4 0.2
.. ... ... ... ...
145 6.7 3.0 5.2 2.3
146 6.3 2.5 5.0 1.9
147 6.5 3.0 5.2 2.0
148 6.2 3.4 5.4 2.3
149 5.9 3.0 5.1 1.8
145 Iris-virginica
146 Iris-virginica
147 Iris-virginica
148 Iris-virginica
149 Iris-virginica
Name: target, Length: 150, dtype: object
The accuracy of Polynomial Kernel= 93.33333333333333 %
The polynomial kernel confusion matrix results are:
[[14 0 0]
[ 0 15 2]
[ 0 1 13]]
The polynomial kernel classification Report:
precision recall f1-score support
accuracy 0.93 45
macro avg 0.93 0.94 0.94 45
weighted avg 0.93 0.93 0.93 45
accuracy 0.93 45
macro avg 0.93 0.94 0.94 45
weighted avg 0.93 0.93 0.93 45
accuracy 0.04 45
macro avg 0.03 0.05 0.04 45
weighted avg 0.03 0.04 0.03 45
SOURCE CODE 11:
import numpy as np
import pandas as pd
from [Link] import StandardScaler
from [Link] import LabelEncoder
from sklearn.model_selection import train_test_split
from [Link] import KNeighborsClassifier
import [Link] as plt
from [Link] import accuracy_score,confusion_matrix
from sklearn.model_selection import GridSearchCV
from [Link] import classification_report
data=pd.read_csv("D:\datasets_puthon\knn_ds.csv")
print("The Sample conteny of data set are...")
print([Link]())
X=[Link](['Outcome'],axis=1).values
y=data['Outcome'].values
sc=StandardScaler()
x=sc.fit_transform(X)
le=LabelEncoder()
y=le.fit_transform(y)
print("The value of X axis in the data set...")
print(x)
print("The value of y axis in the data set...")
print(y)
x_test,x_train,y_test,y_train=train_test_split(x,y,test_size=0.3,random_state=42
)
neighbors=[Link](1,9)
train_accuracy=[Link](len(neighbors))
test_accuracy=[Link](len(neighbors))
for i,k in enumerate(neighbors):
knn=KNeighborsClassifier(n_neighbors=k)
[Link](x_train,y_train)
train_accuracy[i]=[Link](x_train,y_train)
test_accuracy[i]=[Link](x_test,y_test)
[Link]('ggplot')
[Link](("KNN Varying Numbers of Neighbors"))
[Link](neighbors,test_accuracy,label="Testing Accuracy")
[Link](neighbors,train_accuracy,label="Train Accuracy")
[Link]()
[Link]("Number of Neighbors")
[Link]("Accuracy")
[Link]()
y_pred=[Link](x_test)
ac_score=accuracy_score(y_test,y_pred)*100
print("The accuracy of test set K-NN algotithm=",ac_score)
cm=confusion_matrix(y_test,y_pred)
print("The confusion matrix of K-NN algorithm:")
print(cm)
p_grid={'n_neighbors':[Link](1,50)}
knn=KNeighborsClassifier()
knn_cv=GridSearchCV(knn,p_grid, cv=5)
knn_cv.fit(x,y)
print("The best score value of K-NN algorithm=",knn_cv.best_score_)
print("The best parameter range value of K-NN
algorithm=",knn_cv.best_params_)
cl_report=classification_report(y_test,y_pred)
print("The classification report of K-NN algorithm:")
print(cl_report)
OUTPUT:
The Sample content of data set are...
Pregnancies Glucose BloodPressure ... DiabetesPedigreeFunction Age
Outcome
0 6 148 72 ... 0.627 50 1
1 1 85 66 ... 0.351 31 0
2 8 183 64 ... 0.672 32 1
3 1 89 66 ... 0.167 21 0
4 0 137 40 ... 2.288 33 1
[5 rows x 9 columns]
The value of X axis in the data set...
[[ 0.63994726 0.84832379 0.14964075 ... 0.20401277 0.46849198
1.4259954 ]
[-0.84488505 -1.12339636 -0.16054575 ... -0.68442195 -0.36506078
-0.19067191]
[ 1.23388019 1.94372388 -0.26394125 ... -1.10325546 0.60439732
-0.10558415]
...
[ 0.3429808 0.00330087 0.14964075 ... -0.73518964 -0.68519336
-0.27575966]
[-0.84488505 0.1597866 -0.47073225 ... -0.24020459 -0.37110101
1.17073215]
[-0.84488505 -0.8730192 0.04624525 ... -0.20212881 -0.47378505
-0.87137393]]
The value of y axis in the data set...
[1 0 1 0 1 0 1 0 1 1 0 1 0 1 1 1 1 1 0 1 0 0 1 1 1 1 1 0 0 0 0 1 0 0 0 0 0
1110001010010000100100001001010001010
0000100000100010000100000110000000011
1001110001000110011111000000000010000
0000101100010000110000110001010100000
1111100110101110000001101000111101111
0000010011000111100011010000000011000
1010010100110000010001001100100011100
1010110100101100101001010111001010001
0000111000000000100000111011001001001
1000010010000000111001001001011010101
0110000110101000011010100000100001001
1100100100010010000000001000000010001
0001100000001000010001000100010000110
0000010000000000010001111001100000000
0000011000000010000000101100010101010
1001001000011010000110100011000000000
0100001001000100011100000010001011110
1100000001101001010000010101011000011
0001011001001100100100000001110000001
1 0 0 1 0 0 1 0 1 1 1 0 0 1 1 1 0 1 0 1 0 1 0 0 0 0 1 0]
The accuracy of test set K-NN algotithm= 72.62569832402235
The confusion matrix of K-NN algorithm:
[[322 27]
[120 68]]
The best score value of K-NN algorithm= 0.7669892199303965
The best parameter range value of K-NN algorithm= {'n_neighbors': 17}
The classification report of K-NN algorithm:
precision recall f1-score support
OUTPUT:
display the sample data set...
CustomerID Gender Age Annual Income (k$) Spending Score (1-100)
0 1 Male 19 15 39
1 2 Male 21 15 81
2 3 Female 20 16 6
3 4 Female 23 16 77
4 5 Female 31 17 40
The attributes of the data set
<class '[Link]'>
RangeIndex: 200 entries, 0 to 199
Data columns (total 5 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 CustomerID 200 non-null int64
1 Gender 200 non-null object
2 Age 200 non-null int64
3 Annual Income (k$) 200 non-null int64
4 Spending Score (1-100) 200 non-null int64
dtypes: int64(4), object(1)
memory usage: 7.9+ KB
None
check the missing value details...
CustomerID 0
Gender 0
Age 0
Annual Income (k$) 0
Spending Score (1-100) 0
dtype: int64
drop the unnecessary coloumn ...
Gender Age Annual Income (k$) Spending Score (1-100)
0 Male 19 15 39
1 Male 21 15 81
The Label Encoded data set ....
CustomerID Gender Age Annual Income (k$) Spending Score (1-100)
79 80 0 49 54 42
197 198 1 32 126 74
38 39 0 36 37 26
[-0.33916743 -0.87077078 0.73027906 -0.24190423 -0.37113766]
[0.4000535 0.26102704 0.19651835 0.1376936 0.00470751]
Shape of PCA2
(160, 2)
CustomerID Gender Age Annual Income (k$) Spending Score (1-100)
Clusters
0 28 28 28 28 28
1 34 34 34 34 34
2 35 35 35 35 35
3 28 28 28 28 28
4 35 35 35 35 35