Python 5,6,7
Python 5,6,7
#Doc String
def squarDoc Stringe(n):
'''Takes in a number n, returns the square of n'''
return n**2
print(square.__doc__)
#return function
def addEven(n, m):
if n%2 == 0 and m%2 == 0:
return n+m
else:
return n*m
print(addEven(2,2))
print(addEven(2,3))
4
6
#In-Built Function
#abs
complex_num = (3+10j)
#divmod
divmod(10,7)
(1, 3)
divmod(13.5,7.8)
(1.0, 5.7)
#Enumerate
x = ('apple', 'banana', 'cherry')
y = enumerate(x)
print(list(y))
#Filter
ages = [5, 12, 17, 18, 24, 32]
def myFunc(x):
if x < 18:
return False
else:
return True
for x in adults:
print(x)
18
24
32
#Map
def myfunc(a, b):
return a + b
x = map(myfunc, ('apple', 'banana', 'cherry'), ('orange', 'lemon',
'pineapple'))
print(x)
print(list(x))
import functools
lis = [1, 3, 5, 6, 2, ]
print("The sum of the list elements is : ", end="")
print(functools.reduce(lambda a, b: a+b, lis))
print("The maximum element of the list is : ", end="")
print(functools.reduce(lambda a, b: a if a > b else b, lis))
#isinstance
class myObj:
name = "John"
y = myObj()
x = isinstance(y, myObj)
print(x)
True
#lambda function
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(filter(lambda x: (x%2 == 0) , my_list))
print(new_list)
[4, 6, 8, 12]
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
choice = input("Enter choice(1/2/3/4): ")
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
else:
print("Invalid Input")
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
----------------------------------------------------------------------
-----
KeyboardInterrupt Traceback (most recent call
last)
<ipython-input-30-efd003dd92fd> in <module>
14
15 while True:
---> 16 choice = input("Enter choice(1/2/3/4): ")
17
18 if choice in ('1', '2', '3', '4'):
~\anaconda3\lib\site-packages\ipykernel\kernelbase.py in
raw_input(self, prompt)
858 "raw_input was called, but this frontend does
not support input requests."
859 )
--> 860 return self._input_request(str(prompt),
861 self._parent_ident,
862 self._parent_header,
~\anaconda3\lib\site-packages\ipykernel\kernelbase.py in
_input_request(self, prompt, ident, parent, password)
902 except KeyboardInterrupt:
903 # re-raise KeyboardInterrupt, to truncate
traceback
--> 904 raise KeyboardInterrupt("Interrupted by user")
from None
905 except Exception as e:
906 self.log.warning("Invalid Message:",
exc_info=True)
#python 6
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
array1[2]
#indexing
array1 = np.arange(12).reshape(4,3)
array1
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
array1[3][1]
10
#Slicing
array1 = np.arange(9)
array1
array([0, 1, 2, 3, 4, 5, 6, 7, 8])
array1[3:6]
array([3, 4, 5])
array1[4:]
array([4, 5, 6, 7, 8])
array1[:7]
array([0, 1, 2, 3, 4, 5, 6])
array1[:]
array([0, 1, 2, 3, 4, 5, 6, 7, 8])
#np.may_share_memory
import numpy as demo
arr1 = demo.zeros([3, 4])
arr2 = arr1[::1]
mydemo = demo.may_share_memory(arr1, arr2)
print (mydemo)
True
#Fancy Indexing
import numpy as np
rand = np.random.RandomState(42)
x = rand.randint(100, size=10)
print(x)
[51 92 14 71 60 20 82 86 74 74]
ind = [3, 7, 4]
x[ind]
array([71, 86, 60])
array([[71, 86],
[60, 20]])
X = np.arange(12).reshape((3, 4))
X
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
<matplotlib.legend.Legend at 0x1996d2b35e0>
#Write a Python Program to implement following concepts related to
Pandas
# import pandas to use pandas DataFrame
import pandas as pd
data = [('Peter', 18, 7),
('Riff', 15, 6),
('John', 17, 8),
('Michel', 18, 7),
('Sheli', 17, 5) ]
df = pd.DataFrame(data, columns =['Name', 'Age', 'Score'])
print(df)
movie_id title \
0 19995 Avatar
1 285 Pirates of the Caribbean: At World's End
2 206647 Spectre
3 49026 The Dark Knight Rises
4 49529 John Carter
... ... ...
4798 9367 El Mariachi
4799 72766 Newlyweds
4800 231617 Signed, Sealed, Delivered
4801 126186 Shanghai Calling
4802 25975 My Date with Drew
cast \
0 [{"cast_id": 242, "character": "Jake Sully", "...
1 [{"cast_id": 4, "character": "Captain Jack Spa...
2 [{"cast_id": 1, "character": "James Bond", "cr...
3 [{"cast_id": 2, "character": "Bruce Wayne / Ba...
4 [{"cast_id": 5, "character": "John Carter", "c...
... ...
4798 [{"cast_id": 1, "character": "El Mariachi", "c...
4799 [{"cast_id": 1, "character": "Buzzy", "credit_...
4800 [{"cast_id": 8, "character": "Oliver O\u2019To...
4801 [{"cast_id": 3, "character": "Sam", "credit_id...
4802 [{"cast_id": 3, "character": "Herself", "credi...
crew
0 [{"credit_id": "52fe48009251416c750aca23", "de...
1 [{"credit_id": "52fe4232c3a36847f800b579", "de...
2 [{"credit_id": "54805967c3a36829b5002c41", "de...
3 [{"credit_id": "52fe4781c3a36847f81398c3", "de...
4 [{"credit_id": "52fe479ac3a36847f813eaa3", "de...
... ...
4798 [{"credit_id": "52fe44eec3a36847f80b280b", "de...
4799 [{"credit_id": "52fe487dc3a368484e0fb013", "de...
4800 [{"credit_id": "52fe4df3c3a36847f8275ecf", "de...
4801 [{"credit_id": "52fe4ad9c3a368484e16a36b", "de...
4802 [{"credit_id": "58ce021b9251415a390165d9", "de...
#groupby
gk = df.groupby('title')
gk.first()
movie_id \
title
#Horror 301325
(500) Days of Summer 19913
10 Cloverfield Lane 333371
10 Days in a Madhouse 345003
10 Things I Hate About You 4951
... ...
[REC]² 10664
eXistenZ 1946
xXx 7451
xXx: State of the Union 11679
Æon Flux 8202
cast \
title
crew
title
df1 = pd.DataFrame(
{
"A": ["A0", "A1", "A2", "A3"],
"B": ["B0", "B1", "B2", "B3"],
"C": ["C0", "C1", "C2", "C3"],
"D": ["D0", "D1", "D2", "D3"],
},
index=[0, 1, 2, 3],
)
df2 = pd.DataFrame(
{
"A": ["A4", "A5", "A6", "A7"],
"B": ["B4", "B5", "B6", "B7"],
"C": ["C4", "C5", "C6", "C7"],
"D": ["D4", "D5", "D6", "D7"],
},
index=[4, 5, 6, 7],
)
df3 = pd.DataFrame(
{
"A": ["A8", "A9", "A10", "A11"],
"B": ["B8", "B9", "B10", "B11"],
"C": ["C8", "C9", "C10", "C11"],
"D": ["D8", "D9", "D10", "D11"],
},
index=[8, 9, 10, 11],
)
result = pd.concat(frames)
df2 = pd.DataFrame({'Duration':
['30day','40days','35days','60days','55days'],
'Discount':[1000,2300,2500,2000,3000]})
data = pd.DataFrame({
'age' : [ 10, 22, 13, 21, 12, 11, 17],
'section' : [ 'A', 'B', 'C', 'B', 'B', 'A', 'A'],
'city' : [ 'Gurgaon', 'Delhi', 'Mumbai', 'Delhi', 'Mumbai',
'Delhi', 'Mumbai'],
'gender' : [ 'M', 'F', 'F', 'M', 'M', 'M', 'F'],
'favourite_color' : [ 'red', np.NAN, 'yellow', np.NAN, 'black',
'green', 'red']
})
data
data.iloc[[0,2]]
#python 7
class Person:
def say_hi(self):
print('Hello, my name is', self.name)
p1 = Person('Nikhil')
p2 = Person('Abhinav')
p3 = Person('Anshul')
p1.say_hi()
p2.say_hi()
p3.say_hi()
#Inheritance
class Animal:
def speak(self):
print("Animal Speaking")
class Dog(Animal):
def bark(self):
print("dog barking")
class DogChild(Dog):
def eat(self):
print("Eating bread...")
d = DogChild()
d.bark()
d.speak()
d.eat()
dog barking
Animal Speaking
Eating bread...
#Operator-Overloading
class example:
def __init__(self, X):
self.X = X
object_2 = example( int( input( print ("Please enter the value: "))))
#Polymorphism
class Tomato():
def type(self):
print("Vegetable")
def color(self):
print("Red")
class Apple():
def type(self):
print("Fruit")
def color(self):
print("Red")
def func(obj):
obj.type()
obj.color()
obj_tomato = Tomato()
obj_apple = Apple()
func(obj_tomato)
func(obj_apple)
Vegetable
Red
Fruit
Red
Enter a:4
Enter b:0
----------------------------------------------------------------------
-----
ZeroDivisionError Traceback (most recent call
last)
<ipython-input-109-be5b57e399df> in <module>
2 a = int(input("Enter a:"))
3 b = int(input("Enter b:"))
----> 4 c = a/b
5 print("a/b = %d" %c)
6
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d"%c)
# Using Exception with except statement. If we print(Exception) it
will return exception class
except Exception:
print("can't divide by zero")
print(Exception)
else:
print("Hi I am else block")
Enter a:4
Enter b:0
can't divide by zero
<class 'Exception'>
file = open('Downloads/demo.txt','w')
file.write('Hello World')
file.write('This is our new text file')
file.write('and this is another line.')
file.write('Why? Because we can do it this easily.')
file.close()
Hello
os.remove('Downloads/demo - Copy.txt')