You are on page 1of 38

9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

In [1]:

1 print("Hello Daud")
2 print(2+3)

Hello Daud
5

In [2]:

1 import math
2 math.ceil(2.678)

Out[2]:

In [3]:

1 #if statement
2
3 a=int(input("Enter number 1: "))
4 b=int(input("Enter number 2: "))
5 if(a>b):
6 print("a is greater")
7 elif(a==b):
8 print("they are equal")
9 else:
10 print("b is greater")

Enter number 1: 12
Enter number 2: 12
they are equal

In [4]:

1 #while loop
2
3 i=0
4 while i<6:
5 print(i)
6 i=i+1
7

0
1
2
3
4
5

localhost:8888/notebooks/Python Fundament.ipynb# 1/38


9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

In [5]:

1 fruit=["maembe","ddd","chy"]
2 for i in fruit:
3 print(i)
4

maembe
ddd
chy

In [6]:

1 jia="DAUD NAMAYALA"
2 for i in jia:
3 print(i)
4

D
A
U
D

N
A
M
A
Y
A
L
A

In [7]:

1 #Nested for loop


2
3 fruits=["Banana", "Apple","Mango"]
4 students=["Faraja","Rambee","Daud"]
5 for x in fruits:
6 for y in students:
7 print(x,y)

Banana Faraja
Banana Rambee
Banana Daud
Apple Faraja
Apple Rambee
Apple Daud
Mango Faraja
Mango Rambee
Mango Daud

localhost:8888/notebooks/Python Fundament.ipynb# 2/38


9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

In [8]:

1 def myFistFunction(student):
2 print(student+" Daud")
3 myFistFunction("Linus")
4 myFistFunction("Joseph")
5
6

Linus Daud
Joseph Daud

In [9]:

1 import math
2 math.ceil(0.1)

Out[9]:

In [10]:

1 x=input(int)
2 y=input(int)
3 #(x,y)=(2,-4)
4 math.copysign(x, y)
5 print(x, y)

<class 'int'>12
<class 'int'>12

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-10-7d963b9349d4> in <module>
2 y=input(int)
3 #(x,y)=(2,-4)
----> 4 math.copysign(x, y)
5 print(x, y)

TypeError: must be real number, not str

In [11]:

1 #return the absolute value of the number


2 import math
3 math.fabs(-2.4)

Out[11]:

2.4

In [15]:

1 #return the absolute value of the number


2
3 math.fabs(-2.4)
4 import math
5

localhost:8888/notebooks/Python Fundament.ipynb# 3/38


9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

In [13]:

1 import math
2 x=int(input(print("Enter the number ",))
3
4 print("hello world")
5 print("\U0001F917")
6 print("\U0001F600")
7 math.factorial(x)

File "<ipython-input-13-dbd13bca44f0>", line 4


print("hello world")
^
SyntaxError: invalid syntax

In [40]:

1 math.floor(0.9)

Out[40]:

In [41]:

1 import fraction
2 print(Fraction(128, -26))
3 print(Fraction(256))
4 print(Fraction())
5 print(Fraction('2/5'))
6 print(Fraction(' -5/7'))
7 print(Fraction('2.675438 '))
8 print(Fraction('-32.75'))
9 print(Fraction('5e-3'))
10 print(Fraction(7.85))
11 print(Fraction(1.1))
12 print(Fraction(2476979795053773, 2251799813685248))

---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-41-b4c07352d455> in <module>
----> 1 import fraction
2 print(Fraction(128, -26))
3 print(Fraction(256))
4 print(Fraction())
5 print(Fraction('2/5'))

ModuleNotFoundError: No module named 'fraction'

localhost:8888/notebooks/Python Fundament.ipynb# 4/38


9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

In [16]:

1 name="Daud"
2 print(name+' Namayala')
3 print("The first name has the following characters:",name[0],name[1],name[2],name[3])
4 print(name[1:])
5 print(name[2:])

Daud Namayala
The first name has the following characters: D a u d
aud
ud

In [17]:

1 daud=['Sailing Dad','Davy']
2 namayala=['Linus','Antony']
3 joseph=['Linus','Antony']
4 print(daud)
5 print(namayala)

['Sailing Dad', 'Davy']


['Linus', 'Antony']

In [18]:

1 marks = input("Enter marks of each subject : ")


2
3 if int(marks)>= 40:
4 print('Pass')
5 else:
6 print('Fail')

Enter marks of each subject : 34


Fail

localhost:8888/notebooks/Python Fundament.ipynb# 5/38


9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

In [3]:

1 def inputmark():
2 print("ENTER STUDENT ID:")
3 id= int(input())
4 print("Enter EXAM score :")
5 exam= int(input())
6 print("Enter all test scores:")
7 mark1=int(input())
8 mark2=int(input())
9 mark3=int(input())
10 mark4=int(input())
11 mark5=int(input())
12 mark6=int(input())
13 mark7=int(input())
14 mark8=int(input())
15 mark9=int(input())
16 mark10=int(input())
17 sum=(mark1+mark2+mark3+mark4+mark5+mark6+mark7+mark8+mark9+mark10)
18 avge=sum/10
19 print("TEST AVERAGE IS:" +str(avge))
20 print("Final mark is:",compute_mark(avge,exam))
21 print("Lattest grade is :",getgrade(compute_mark(avge,exam)))
22 print_Remark(getgrade(compute_mark(avge,exam))
23 def compute_mark(avge,exam):
24 final_mark=0.4*avge+0.6*exam
25 return final_mark
26 def getgrade(final_mark):
27 if 90<=final_mark<=100:
28 grade='A'
29 elif 80<=final_mark<=89:
30 grade='B'
31 elif 70=final_mark<=79:
32 grade='C'
33 elif 60<=final_mark<=69:
34 grade='D'
35 else:
36 grade='F'
37 return grade
38 def print_Remark(grade):
39 if grade=='A'
40 print("Remark:Exallent")
41
42 elif grade=='B'
43 print("Remark:Good")
44
45 elif grade=='C'
46 print("Remark:satisfactory")
47 elif grade=='D'
48 print("Remark:fail")
49 elif grade=='F'
50 print("Remark:poor")
51 inputmark()
52

File "<ipython-input-3-857a3b0b00b6>", line 23


def compute_mark(avge,exam):
^
SyntaxError: invalid syntax

localhost:8888/notebooks/Python Fundament.ipynb# 6/38


9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

localhost:8888/notebooks/Python Fundament.ipynb# 7/38


9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

In [20]:

1 name = input("Enter your name: ")


2 print(f"enter the marks for {name} ")
3 scores = []
4 courses = ['C++', 'MT117', 'DATABASE', 'SECURITY', 'NETWORKING', 'IT', 'CS', 'ST', 'PRO
5 for j in range(10):
6 a = int(input(f"{courses[j]}: "))
7 scores.append(a)
8 total = 0
9 for i in range(len(scores)):
10 if (scores[i]<=100 and scores[i]>=70):
11 grade = 'A'
12 count = 5
13 elif(scores[i]<=69 and scores[i]>=61):
14 grade = 'B'
15 count = 4
16 elif(scores[i]<=69 and scores[i]>=61):
17 grade = 'B'
18 count = 4
19 elif(scores[i]<=69 and scores[i]>=61):
20 grade = 'C'
21 count = 3
22 elif (scores[i] <= 69 and scores[i] >= 61):
23 grade = 'D'
24 count = 2
25 elif (scores[i] <= 69 and scores[i] >= 61):
26 grade = 'F'
27 count = 2
28 print(f"{courses[i]} {scores[i]}")
29 total += count
30 gpa = total/len(scores)
31 print(f"GPA: {gpa}")
32 if gpa < 2:
33 print("FAILED")
34 else:
35 print("PASSED")
36
37

Enter your name: rtyu


enter the marks for rtyu
C++: 78
MT117: 89
DATABASE: 00
SECURITY: 899
NETWORKING: 9
IT: 9
CS: 9
ST: 0
PROBABILITY: 0
STATISTICS: 0
C++ 78
MT117 89
DATABASE 0
SECURITY 899
NETWORKING 9
IT 9
CS 9
ST 0
PROBABILITY 0
localhost:8888/notebooks/Python Fundament.ipynb# 8/38
9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

STATISTICS 0
GPA: 5.0
PASSED

localhost:8888/notebooks/Python Fundament.ipynb# 9/38


9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

In [21]:

1 name = input("Enter your name: ")


2 print(f"enter the marks for {name} ")
3 scores = []
4 courses = ['C++', 'MT117', 'DATABASE', 'SECURITY', 'NETWORKING', 'IT', 'CS', 'ST', 'PRO
5 for j in range(10):
6 a = int(input(f"{courses[j]}: "))
7 scores.append(a)
8 total = 0
9 grade = ''
10 count = ''
11 for i in range(len(scores)):
12
13 if (scores[i]<=100 and scores[i]>=70):
14 grade = 'A'
15 count = 5
16 elif(scores[i]<=69 and scores[i]>=60):
17 grade = 'B+'
18 count = 4
19 elif(scores[i]<=59 and scores[i]>=50):
20 grade = 'B'
21 count = 3
22 elif(scores[i]<=49 and scores[i]>=40):
23 grade = 'C'
24 count = 2
25 elif (scores[i] <= 39 and scores[i] >= 30):
26 grade = 'D'
27 count = 1
28 elif (scores[i] <= 29 and scores[i] >= 0):
29 grade = 'F'
30 count = 0
31 print(f"{courses[i]} {scores[i]} {grade}")
32 total += count
33 gpa = total/len(scores)
34 print(f"GPA: {gpa}")
35 if gpa < 2:
36 print("FAILED")
37 else:
38 print("PASSED")
39
40

Enter your name: tt


enter the marks for tt
C++: 90
MT117: 0
DATABASE: 0
SECURITY: 9
NETWORKING: 9
IT: 9
CS: 0
ST: 9
PROBABILITY: 9
STATISTICS: 8
C++ 90 A
MT117 0 F
DATABASE 0 F
SECURITY 9 F
NETWORKING 9 F
IT 9 F
localhost:8888/notebooks/Python Fundament.ipynb# 10/38
9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

CS 0 F
ST 9 F
PROBABILITY 9 F
STATISTICS 8 F
GPA: 0.5
FAILED

In [ ]:

1 #PHYTHON LIBRARIES IN DATA SCIENCE(Funtion to simplify coding-Minimize the lines of cod


2 #Lists of usefully libraries
3 #Numpy-simply multidimential array and matrix
4 #Matplotlb-ploting graphs
5 #Pandas-to access files/data from the files
6 #Scikit-learn-
7 #NLTP_Natural Language processing
8

localhost:8888/notebooks/Python Fundament.ipynb# 11/38


9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

In [8]:

1 #Numpy-simply multidimential array and matrix


2 import numpy as np
3
4 #zero dimensional array
5
6 a=np.array(23)
7 print(a)
8
9 #one dimensional array
10 b=np.array([1,2,3,4,5,6,7])
11 print(b)
12
13 #two dimensional array
14 c=np.array([[1,2,3],[2,4,6]])
15 print(c)
16
17 #three dimensional array
18 d=np.array([[[1,2,3],[2,4,6],[3,6,9]]])
19 print(d)
20
21 #Accessing the dimensionsof the aray by using the function #ndim
22 print(b[-2])
23 print(a.ndim)
24 print(b.ndim)
25 print(c.ndim)
26 print(d.ndim)
27 print(b[1:5])
28
29 #b=np.array([1,2,3,4,5,6,7])
30 print(b[2:6:2])
31 #syntax array_name(row,-1)
32 f=np.array([[1,2,3,4,5],[2,4,6,9]])
33 print(d[1,-1])
34
35 #slicing array
36 #the stoping index
37 #
38
39

23
[1 2 3 4 5 6 7]
[[1 2 3]
[2 4 6]]
[[[1 2 3]
[2 4 6]
[3 6 9]]]
6
0
1
2
3
[2 3 4 5]
[3 5]

<ipython-input-8-1fc1a3606520>:32: VisibleDeprecationWarning: Creating an


ndarray from ragged nested sequences (which is a list-or-tuple of lists-or
-tuples-or ndarrays with different lengths or shapes) is deprecated. If yo
u meant to do this, you must specify 'dtype=object' when creating the ndar
localhost:8888/notebooks/Python Fundament.ipynb# 12/38
9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

ray.
f=np.array([[1,2,3,4,5],[2,4,6,9]])

---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-8-1fc1a3606520> in <module>
31 #syntax array_name(row,-1)
32 f=np.array([[1,2,3,4,5],[2,4,6,9]])
---> 33 print(d[1,-1])
34
35 #slicing array

IndexError: index 1 is out of bounds for axis 0 with size 1

In [9]:

1 #Random number generation using Numpy


2 #Random module is used to generate random numbers
3 import numpy as np
4 a=np.random.rand() # generates random float
5 print(a)
6 b=np.random.randint(100)
7 print(b)

0.522958427663721
5

In [10]:

1 a=np.random.rand() # generates random flaot


2 print(a)
3 b=np.random.randint(100, size=10)
4 print(b)

0.6551553579208564
[42 65 59 89 95 32 47 51 75 45]

In [11]:

1 b=np.random.randint(100, size=100)
2 print(b)

[63 39 28 16 38 57 73 80 83 44 11 41 40 94 63 48 11 86 50 90 91 91 85 74
85 58 53 61 40 24 79 58 40 12 44 47 0 47 74 61 23 50 61 67 91 1 39 73
65 81 83 17 1 35 22 59 32 75 3 25 71 35 81 38 29 59 43 97 51 15 1 71
87 91 91 36 71 75 12 5 92 30 72 69 56 4 52 90 97 3 20 95 62 96 79 7
90 8 81 79]

localhost:8888/notebooks/Python Fundament.ipynb# 13/38


9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

In [12]:

1 #arrange f(x) using numpy


2 #sysntax np.arrange(start=, stop=, step=)
3 w=np.arange.(start=0, stop=10, step=2)
4 print(w)
5
6 #two dimensions arange
7
8 y=np.arange(start=1, stop=10, step=1).reshape(3,2)

File "<ipython-input-12-0031ac6371cf>", line 3


w=np.arange.(start=0, stop=10, step=2)
^
SyntaxError: invalid syntax

In [13]:

1 #Matrices Manupulation by using numpy library


2 zeros=np.zeros((3,5))
3 ones=np.ones((3,4))
4 print(zeros)
5 print(ones)

[[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]]
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]

In [14]:

1 #matrix declaration
2 matrix1=np.matrix([[2,3,6],[5,6,7]])
3 matrix2=np.matrix([[9,1,1],[7,2,-5]])
4 print(matrix1)
5 print(matrix2)

[[2 3 6]
[5 6 7]]
[[ 9 1 1]
[ 7 2 -5]]

localhost:8888/notebooks/Python Fundament.ipynb# 14/38


9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

In [15]:

1 import numpy as np
2
3 my=np.array([[2,3,4],[1,1,2,4]])
4
5 print(my)
6 print(my[1][-2])
7 #print(type(my))

[list([2, 3, 4]) list([1, 1, 2, 4])]


2

<ipython-input-15-df90705c5ea6>:3: VisibleDeprecationWarning: Creating an nd


array from ragged nested sequences (which is a list-or-tuple of lists-or-tup
les-or ndarrays with different lengths or shapes) is deprecated. If you mean
t to do this, you must specify 'dtype=object' when creating the ndarray.
my=np.array([[2,3,4],[1,1,2,4]])

In [16]:

1 #adding(add), substracting, dividing(, doting, multipling, and transposing


2
3 print(np.divide(matrix1, matrix2))

[[ 0.22222222 3. 6. ]
[ 0.71428571 3. -1.4 ]]

In [17]:

1 #strong password
2 import random
3 s="abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_+"
4 length=4
5 password="".join(random.sample(s, length))
6 print("Password is:", password)

Password is: Ys(p

In [23]:

1 import numpy as np
2 my=np.array([[[1,2,3],[2,4,6],[3,6,9]]])
3 print(my)
4 print(my[0][0])

[[[1 2 3]
[2 4 6]
[3 6 9]]]
[1 2 3]

In [24]:

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

#31/Aug/2021 #Using python to skecth graphs using matplot Library import numpy as np #to generate data that
will be used to draw the graph import matplotlib.pyplot as plt #python library to plot grap
localhost:8888/notebooks/Python Fundament.ipynb# 15/38
9/3/21, 5:33 PM Python Fundament - Jupyter Notebook
g p p p pyp p py y p g p
#plotting a simple line y=np.array([0,10]) plt.plot(y) plt.show()

In [26]:

1 #import numpy as np #to generate data that will be used to draw the graph
2 #import matplotlib.pyplot as plt
3 x=np.array([1,2,3,4,5,6,7])
4 y=np.array([2,4,6,8,12,14,16])
5 plt.plot(x,y,'o')
6 plt.show()

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-26-36783af17f04> in <module>
3 x=np.array([1,2,3,4,5,6,7])
4 y=np.array([2,4,6,8,12,14,16])
----> 5 plt.plot(x,y,'o')
6 plt.show()

NameError: name 'plt' is not defined

In [27]:

1 #changing line color


2 x=np.array([1,2,3,4,5,6,7])
3 y=np.array([2,4,6,8,12,14,16])
4 plt.plot(x,y,color='b', lw=3)
5 plt.show()

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-27-3fc1c04aa21b> in <module>
2 x=np.array([1,2,3,4,5,6,7])
3 y=np.array([2,4,6,8,12,14,16])
----> 4 plt.plot(x,y,color='b', lw=3)
5 plt.show()

NameError: name 'plt' is not defined

In [28]:

1 #style of lines
2 x=np.array([1,2,3,4,5,6,7])
3 y=np.array([2,4,6,8,10,12,14])
4 plt.plot(x,y,color='b',lw=3, linestyle='dotted',marker='*')
5 plt.show()

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-28-4a05baac791f> in <module>
2 x=np.array([1,2,3,4,5,6,7])
3 y=np.array([2,4,6,8,10,12,14])
----> 4 plt.plot(x,y,color='b',lw=3, linestyle='dotted',marker='*')
5 plt.show()

NameError: name 'plt' is not defined

localhost:8888/notebooks/Python Fundament.ipynb# 16/38


9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

In [29]:

1 #markers in matplotlibraries,marker size=ms,


2 #marker edge color =mec
3
4 x=np.array([1,2,3,4,5,6,7])
5 y=np.array([2,4,6,8,10,12,14])
6 plt.plot(x,y,color='b',lw=3, marker='v', ms=5, mec='r')
7 plt.show()

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-29-118e9424e440> in <module>
4 x=np.array([1,2,3,4,5,6,7])
5 y=np.array([2,4,6,8,10,12,14])
----> 6 plt.plot(x,y,color='b',lw=3, marker='v', ms=5, mec='r')
7 plt.show()

NameError: name 'plt' is not defined

In [30]:

1 #Ploting multiple lines within the same plot


2 y1=np.random.randint(100, size=10)
3 y2=np.random.randint(100, size=10)
4
5 plt.plot(y1, label='Line 1')
6 plt.plot(y2, label='Line 2')
7
8 plt.legend()
9 plt.show()

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-30-f8a8db74b41c> in <module>
3 y2=np.random.randint(100, size=10)
4
----> 5 plt.plot(y1, label='Line 1')
6 plt.plot(y2, label='Line 2')
7

NameError: name 'plt' is not defined

localhost:8888/notebooks/Python Fundament.ipynb# 17/38


9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

In [31]:

1 #saving graphs in maltplotlibrary using plt.savefig('Location/name of the figure')


2 y1=np.random.randint(100, size=10)
3 y2=np.random.randint(100, size=10)
4
5 plt.plot(y1, label='Line 1')
6 plt.plot(y2, label='Line 2')
7
8 plt.legend()
9 plt.show()
10 plt.savefig('Desktop/My first plot in python.png')

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-31-7c237585e217> in <module>
3 y2=np.random.randint(100, size=10)
4
----> 5 plt.plot(y1, label='Line 1')
6 plt.plot(y2, label='Line 2')
7

NameError: name 'plt' is not defined

In [32]:

1 #title and labelin matplotlibraries and naming the graphy


2 plt.plot(x,y)
3 plt.xlabel('X-Axis')
4 plt.ylabel('Y-Axis')
5 plt.title('Example', loc='right')
6 plt.show

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-32-e544ee56f7d8> in <module>
1 #title and labelin matplotlibraries and naming the graphy
----> 2 plt.plot(x,y)
3 plt.xlabel('X-Axis')
4 plt.ylabel('Y-Axis')
5 plt.title('Example', loc='right')

NameError: name 'plt' is not defined

localhost:8888/notebooks/Python Fundament.ipynb# 18/38


9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

In [33]:

1 #Background of the graph(Grid lines using matplotlip)


2 #title and labelin matplotlibraries and naming the graphy
3 plt.plot(x,y, marker='v')
4 plt.xlabel('X-Axis')
5 plt.ylabel('Y-Axis')
6 plt.title('Example', loc='center')
7 plt.grid(axis='y',color='r')
8 plt.show()
9

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-33-247ba9c9de0f> in <module>
1 #Background of the graph(Grid lines using matplotlip)
2 #title and labelin matplotlibraries and naming the graphy
----> 3 plt.plot(x,y, marker='v')
4 plt.xlabel('X-Axis')
5 plt.ylabel('Y-Axis')

NameError: name 'plt' is not defined

In [34]:

1 #ploting multiple graphs within a single plot using plt.subplot(row, column, position)
2 #by specifing the row and column of where the graph will be plotted
3 #ploat number 1
4 x1=[1,2,3,4,5]
5 y1=[3,5,7,9,11]
6
7 plt.subplot(1,2,1)#single row, two columns, first position
8 plt.title('Car')
9 plt.grid(color='r')
10 plt.plot(x1,y1)
11
12 #plot number 2
13 x2=[4,5,6,7,8]
14 y2=[5,6,7,8,9]
15
16 plt.subplot(1,2,2)#single row, two columns, first position
17 plt.title('Train')
18 plt.grid(color='g')
19 plt.plot(x2,y2)
20
21 plt.show

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-34-d3c73002f895> in <module>
5 y1=[3,5,7,9,11]
6
----> 7 plt.subplot(1,2,1)#single row, two columns, first position
8 plt.title('Car')
9 plt.grid(color='r')

NameError: name 'plt' is not defined

localhost:8888/notebooks/Python Fundament.ipynb# 19/38


9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

In [1]:

1 #ploting multiple graphs within a single plot using plt.subplot(row, column, position)
2 #by specifing the row and column of where the graph will be plotted
3 #ploat number 1
4 x1=[1,2,3,4,5]
5 y1=[3,5,7,9,11]
6
7 plt.subplot(1,1,1)#single row, two columns, first position
8 plt.title('Car')
9 plt.grid(color='r')
10 plt.plot(x1,y1)
11 plt.show()
12
13 #plot number 2
14 x2=[4,5,6,7,8]
15 y2=[5,6,7,8,9]
16
17 plt.subplot(2,2,2)#single row, two columns, first position
18 plt.title('Train')
19 plt.grid(color='g')
20 plt.plot(x2,y2)
21
22 plt.show()

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-7143bc47422b> in <module>
5 y1=[3,5,7,9,11]
6
----> 7 plt.subplot(1,1,1)#single row, two columns, first position
8 plt.title('Car')
9 plt.grid(color='r')

NameError: name 'plt' is not defined

localhost:8888/notebooks/Python Fundament.ipynb# 20/38


9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

In [2]:

1 #use subplot to plot six figures in a single plot with three columns and two rows using
2 #your data for ploting
3
4 y1=np.random.randint(100, size=10)
5 y2=np.random.randint(100, size=10)
6 y3=np.random.randint(100, size=10)
7 y4=np.random.randint(100, size=10)
8 y5=np.random.randint(100, size=10)
9 y6=np.random.randint(100, size=10)
10
11 plt.subplot(2,3,1)
12 plt.plot(y1, label='Line 1')
13 plt.grid(color='k')
14 plt.show()
15
16 plt.subplot(2,3,2)
17 plt.plot(y2, label='Line 2')
18 plt.grid(color='r')
19 plt.show()
20
21 plt.subplot(2,3,3)
22 plt.plot(y3, label='Line 3')
23 plt.grid(color='b')
24 plt.show()
25
26 plt.subplot(2,2,1)
27 plt.plot(y4, label='Line 4')
28 plt.grid(color='g')
29 plt.show()
30
31 plt.subplot(2,2,2)
32 plt.plot(y5, label='Line 5')
33 plt.grid(color='b')
34 plt.show()
35
36 plt.subplot(2,2,3)
37 plt.plot(y6, label='Line 6')
38 plt.grid(color='r')
39 plt.show()

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-2-08de7618a0f8> in <module>
2 #your data for ploting
3
----> 4 y1=np.random.randint(100, size=10)
5 y2=np.random.randint(100, size=10)
6 y3=np.random.randint(100, size=10)

NameError: name 'np' is not defined

localhost:8888/notebooks/Python Fundament.ipynb# 21/38


9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

In [ ]:

1 #ploting the scatter graph using matplot library rand for float number
2 x=np.random.rand(10)
3 y=np.random.rand(10)
4
5 plt.scatter(x,y,color='k')
6 plt.grid(color='r')
7 plt.show()

In [35]:

1 #ploting the scatter graph using matplot library rand for float number
2 y1=np.random.randint(200, size=20)
3 y2=np.random.randint(200, size=20)
4
5 plt.scatter(y1,y2,color='b')
6
7 x1=np.random.randint(200, size=20)
8 x2=np.random.randint(200, size=20)
9
10 plt.scatter(x1,x2,color='r')
11 plt.legend()
12 plt.show()

No handles with labels found to put in legend.

localhost:8888/notebooks/Python Fundament.ipynb# 22/38


9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

In [34]:

1 #how to draw bar graph and pichart using matplotlib


2
3 A=['Mango','Orange','Apple','Banana']
4 B=[100,200,60,70]
5 plt.bar(A,B)
6

Out[34]:

<BarContainer object of 4 artists>

In [36]:

1 A=['Mango','Orange','Apple','Banana']
2 B=[100,200,60,70]
3 plt.hist(B)
4 plt.show

Out[36]:

<function matplotlib.pyplot.show(close=None, block=None)>

localhost:8888/notebooks/Python Fundament.ipynb# 23/38


9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

In [37]:

1 A=['Mango','Orange','Apple','Banana']
2 B=[100,200,60,70]
3 #mylabels=['Mango','Orange','Apple','Banana']
4 plt.pie(B, labels=A, startangle=180)
5
6 plt.show()

In [38]:

1 #How to print date and time in python


2
3 import datetime
4 x=datetime.datetime.now()
5 print(x)
6 print(x.year)
7 print(x.strftime('%A'))

2021-09-01 17:16:59.110217
2021
Wednesday

localhost:8888/notebooks/Python Fundament.ipynb# 24/38


9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

In [39]:

1 A=['Mango','Orange','Apple','Banana']
2 B=[100,200,60,70]
3 #mylabels=['Mango','Orange','Apple','Banana']
4 plt.pie(B, labels=A, startangle=90)
5
6 plt.show()

In [44]:

1 import pandas as pd
2 series=pd.Series([1,2,3,4,5],['a','b','c','d','e'])
3 print(series)

---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-44-2dba0caf753d> in <module>
----> 1 import pandas as pd
2 series=pd.Series([1,2,3,4,5],['a','b','c','d','e'])
3 print(series)

C:\ProgramData\Anaconda3\lib\site-packages\pandas\__init__.py in <module>
177
178 from pandas.util._tester import test
--> 179 import pandas.testing
180 import pandas.arrays
181

C:\ProgramData\Anaconda3\lib\site-packages\pandas\testing.py in <module>
3 """
4
----> 5 from pandas._testing import (
6 assert_extension_array_equal,
7 assert_frame_equal,

C:\ProgramData\Anaconda3\lib\site-packages\pandas\_testing.py in <module>
3052
3053
-> 3054 cython_table = pd.core.base.SelectionMixin._cython_table.items()
3055
3056

AttributeError: partially initialized module 'pandas' has no attribute 'cor


e' (most likely due to a circular import)

localhost:8888/notebooks/Python Fundament.ipynb# 25/38


9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

In [29]:

1 def compare(num1, num2, num3):


2 if num1>numb2 and numb1>numb3:
3 return numb1
4 elif numb2>numb1 and numb2>numb3:
5 return numb2
6 elif numb3>numb2 and numb3>numb1:
7 return numb3
8 print(max(30,40,50))
9

50

In [27]:

1 pwd

Out[27]:

'C:\\Users\\DAVY'

In [11]:

1 import numpy as np
2 import pandas as pd
3 import matplotlib.pyplot as plt
4 import seaborn as sns
5
6 %matplotlib inline

In [12]:

1 pd.read_csv('Linear-Regression\Advertising.csv')
2 #x=advertisment[['TV','Radio','Newspaper']]

Out[12]:

TV Radio Newspaper Sales

0 230.1 37.8 69.2 22.1

1 44.5 39.3 45.1 10.4

2 17.2 45.9 69.3 9.3

3 151.5 41.3 58.5 18.5

4 180.8 10.8 58.4 12.9

... ... ... ... ...

195 38.2 3.7 13.8 7.6

196 94.2 4.9 8.1 9.7

197 177.0 9.3 6.4 12.8

198 283.6 42.0 66.2 25.5

199 232.1 8.6 8.7 13.4

200 rows × 4 columns

localhost:8888/notebooks/Python Fundament.ipynb# 26/38


9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

In [25]:

1 sns.joinplothist('Radio','TV')

---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-25-69881cdf72a9> in <module>
----> 1 sns.joinplothist('Radio','TV')

AttributeError: module 'seaborn' has no attribute 'joinplothist'

In [ ]:

In [17]:

1 pwd

Out[17]:

'C:\\Users\\DAVY'

In [16]:

1 plt.scatter(y_test,program)

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-16-df9f8bf34c7c> in <module>
----> 1 plt.scatter(y_test,program)

NameError: name 'y_test' is not defined

In [32]:

1 from sklearn.linear_model import LinearRegression

In [33]:

1 add=LinearRegression()

In [34]:

1 add.fit(x_train, y_train)

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-34-6db589d678ae> in <module>
----> 1 add.fit(x_train, y_train)

NameError: name 'x_train' is not defined

localhost:8888/notebooks/Python Fundament.ipynb# 27/38


9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

In [1]:

1 import numpy as np
2 import pandas as pd
3 import matplotlib.pyplot as plt
4 import seaborn as sns
5 %matplotlib inline
6

In [3]:

1 USA=pd.read_csv('USA_Housing.csv')
2 USA

Out[3]:

Avg.
Avg.
Area Avg. Area
Avg. Area Area Area
Number Number of Price A
Income House Population
of Bedrooms
Age
Rooms

208 Michael Fe
0 79545.458574 5.682861 7.009188 4.09 23086.800503 1.059034e+06 674\nLaurab

188 Johnso
1 79248.642455 6.002900 6.730821 3.09 40173.072174 1.505891e+06 Suite 079
Kathlee

9127 E
2 61287.067179 5.865890 8.512727 5.13 36882.159400 1.058988e+06 Stravenue\nDan
WI 0

USS Barnett\nF
3 63345.240046 7.188236 5.586729 3.26 34310.242831 1.260617e+06

USNS Raymon
4 59982.197226 5.040555 7.839388 4.23 26354.109472 6.309435e+05
AE

... ... ... ... ... ... ...

USNS William
4995 60567.944140 7.830362 6.137356 3.46 22837.361035 1.060194e+06
AP 3015

PSC 92
4996 78491.275435 6.999135 6.576763 4.02 25616.115489 1.482618e+06 8489\nAPO AA

4215 Tracy
4997 63390.686886 7.250591 4.805081 2.13 33266.145490 1.030730e+06 Suite 076\nJosh
V

USS Wallace\nF
4998 68001.331235 5.534388 7.130144 5.44 42625.620156 1.198657e+06

37778 George
4999 65510.581804 5.992305 6.792336 4.07 46501.283803 1.298950e+06 Apt. 509\nEa

5000 rows × 7 columns

localhost:8888/notebooks/Python Fundament.ipynb# 28/38


9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

In [4]:

1 USA.columns

Out[4]:

Index(['Avg. Area Income', 'Avg. Area House Age', 'Avg. Area Number of Room
s',
'Avg. Area Number of Bedrooms', 'Area Population', 'Price', 'Addres
s'],
dtype='object')

In [5]:

1 sns.set_style('whitegrid')

In [6]:

1 sns.histplot(USA['Avg. Area Number of Rooms'])

Out[6]:

<AxesSubplot:xlabel='Avg. Area Number of Rooms', ylabel='Count'>

localhost:8888/notebooks/Python Fundament.ipynb# 29/38


9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

In [23]:

1 sns.histplot(USA['Avg. Area House Age'])

Out[23]:

<AxesSubplot:xlabel='Avg. Area House Age', ylabel='Count'>

In [24]:

1 sns.histplot(USA['Price'])

Out[24]:

<AxesSubplot:xlabel='Price', ylabel='Count'>

localhost:8888/notebooks/Python Fundament.ipynb# 30/38


9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

In [27]:

1 sns.histplot(USA['Avg. Area Number of Bedrooms'])

Out[27]:

<AxesSubplot:xlabel='Avg. Area Number of Bedrooms', ylabel='Count'>

In [7]:

1 sns.histplot(USA['Area Population'])

Out[7]:

<AxesSubplot:xlabel='Area Population', ylabel='Count'>

localhost:8888/notebooks/Python Fundament.ipynb# 31/38


9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

In [14]:

1 sns.jointplot(x='Area Population', y='Price', data=USA)

Out[14]:

<seaborn.axisgrid.JointGrid at 0x2d1c7ca2f70>

In [ ]:

localhost:8888/notebooks/Python Fundament.ipynb# 32/38


9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

In [16]:

1 sns.lmplot(x='Area Population', y='Price', data=USA)

Out[16]:

<seaborn.axisgrid.FacetGrid at 0x2d1c9355580>

In [ ]:

1 sns.jointplot(x='Area Population', y='Price', data=USA)

1 # resedials in terms of graphs #error cheking using


metrix sk learn library

localhost:8888/notebooks/Python Fundament.ipynb# 33/38


9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

In [17]:

1 USA.columns

Out[17]:

Index(['Avg. Area Income', 'Avg. Area House Age', 'Avg. Area Number of Room
s',
'Avg. Area Number of Bedrooms', 'Area Population', 'Price', 'Addres
s'],
dtype='object')

In [18]:

1 x=USA[['Avg. Area House Age','Avg. Area Number of Rooms','Avg. Area Number of Bedrooms'

In [19]:

1 x

Out[19]:

Avg. Area House Age Avg. Area Number of Rooms Avg. Area Number of Bedrooms

0 5.682861 7.009188 4.09

1 6.002900 6.730821 3.09

2 5.865890 8.512727 5.13

3 7.188236 5.586729 3.26

4 5.040555 7.839388 4.23

... ... ... ...

4995 7.830362 6.137356 3.46

4996 6.999135 6.576763 4.02

4997 7.250591 4.805081 2.13

4998 5.534388 7.130144 5.44

4999 5.992305 6.792336 4.07

5000 rows × 3 columns

In [20]:

1 y=USA['Price']

localhost:8888/notebooks/Python Fundament.ipynb# 34/38


9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

In [21]:

1 y

Out[21]:

0 1.059034e+06
1 1.505891e+06
2 1.058988e+06
3 1.260617e+06
4 6.309435e+05
...
4995 1.060194e+06
4996 1.482618e+06
4997 1.030730e+06
4998 1.198657e+06
4999 1.298950e+06
Name: Price, Length: 5000, dtype: float64

In [22]:

1 from sklearn.model_selection import train_test_split

In [52]:

1 x_train,x_test,y_train, y_test=train_test_split(x,y,test_size=0.3,random_state=80)

In [53]:

1 x.shape

Out[53]:

(5000, 3)

In [54]:

1 x_train.shape

Out[54]:

(3500, 3)

In [55]:

1 from sklearn.linear_model import LinearRegression

In [56]:

1 ad=LinearRegression()

In [57]:

1 ad.fit(x_train,y_train)

Out[57]:

LinearRegression()

localhost:8888/notebooks/Python Fundament.ipynb# 35/38


9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

In [58]:

1 ad.intercept_

Out[58]:

-548371.3898093791

In [59]:

1 ad.coef_

Out[59]:

array([159295.33265485, 115163.79709745, 7017.68232871])

In [60]:

1 x.columns

Out[60]:

Index(['Avg. Area House Age', 'Avg. Area Number of Rooms',


'Avg. Area Number of Bedrooms'],
dtype='object')

In [61]:

1 cdf=pd.DataFrame(data=ad.coef_,index=x.columns,columns= ['coeffs'])

In [62]:

1 prediction=ad.predict(x_test)

In [63]:

1 plt.scatter(y_test,prediction)
2 plt.xlabel('y_test')
3 plt.ylabel('predict y')

Out[63]:

Text(0, 0.5, 'predict y')

localhost:8888/notebooks/Python Fundament.ipynb# 36/38


9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

In [65]:

1 equate=pd.DataFrame({'real_ones':y_test})
2 equate

Out[65]:

real_ones

2613 1.813858e+06

1118 1.286573e+06

2763 8.732420e+05

817 1.186357e+06

1442 1.085943e+06

... ...

2814 1.657363e+06

4727 1.690541e+06

3105 9.125856e+05

888 1.184894e+06

4102 7.815242e+05

1500 rows × 1 columns

In [67]:

1 equate=pd.DataFrame({'reaal_ones':y_test,'prediction':prediction})
2 equate

Out[67]:

reaal_ones prediction

2613 1.813858e+06 1.407328e+06

1118 1.286573e+06 1.208260e+06

2763 8.732420e+05 1.401041e+06

817 1.186357e+06 1.587941e+06

1442 1.085943e+06 1.059027e+06

... ... ...

2814 1.657363e+06 1.137931e+06

4727 1.690541e+06 1.362355e+06

3105 9.125856e+05 1.520731e+06

888 1.184894e+06 1.566221e+06

4102 7.815242e+05 1.261561e+06

1500 rows × 2 columns

localhost:8888/notebooks/Python Fundament.ipynb# 37/38


9/3/21, 5:33 PM Python Fundament - Jupyter Notebook

In [ ]:

localhost:8888/notebooks/Python Fundament.ipynb# 38/38

You might also like