Uploaded by Dr. P. S. Raja

NM-PYTHON-3

advertisement
7/26/23, 6:52 PM
NM-PYTHON-3 - Jupyter Notebook
In [ ]:
def calc(n1, n2, opr):
if opr == "+":
result = n1 + n2
elif opr == "-":
result = n1 -n2
elif opr in "*xX":
result = n1 * n2
elif opr =="/":
result = n1 / n2
elif opr =="%":
result = n1 % n2
else:
result = None
return result
#main
ans =calc(10,20,"@")
if ans != None:
print(ans)
else:
print("Invalid operation!")
In [ ]:
# Anusha
# A
# An
# Anu
# Anus
# Anush
# Anusha
print("%-*.*s"%(20,10, "Jayanthi is very active"))
In [ ]:
name = input()
size = len(name)
for i in range(1, size+1):
print("%*.*s"%(size,i,name))
In [ ]:
name = input()
size = len(name)
for i in range(1, size+1):
print("%-*.*s"%(size,i,name))
localhost:8888/notebooks/NM-PYTHON-3.ipynb#
1/14
7/26/23, 6:52 PM
NM-PYTHON-3 - Jupyter Notebook
In [ ]:
name = input()
size = len(name)
for i in range(1, size+1):
print("%-*.*s%*.*s"%(size,i,name,size,i,name))
In [ ]:
name = input()
size = len(name)
for i in range(size,0,-1):
print("%-*.*s%*.*s"%(size,i,name,size,i,name[::-1]))
In [ ]:
name = input()
size = len(name)
for i in range(size,0,-1):
print("%-*.*s%*.*s"%(size,i,name,size,i,name[::-1]))
for i in range(1,size+1):
print("%-*.*s%*.*s"%(size,i,name,size,i,name[::-1]))
In [ ]:
name = input()
L = len(name)
for i in range(L,0,-1):
print("%*.*s%-*.*s"%(L, i, name,L, i, name))
for i in range(1, L):
print("%*.*s%-*.*s"%(L, i, name,L, i, name))
In [ ]:
name = input()
L = len(name)
for i in range(1, L):
print("%*.*s%-*.*s"%(L, i, name,L, i, name))
for i in range(L,0,-1):
print("%*.*s%-*.*s"%(L, i, name,L, i, name))
In [ ]:
name = input()
L = len(name)
for i in range(1, L):
print("%-*.*s%*.*s"%(L, i, name,L, i, name))
for i in range(L,0,-1):
print("%-*.*s%*.*s"%(L, i, name,L, i, name))
localhost:8888/notebooks/NM-PYTHON-3.ipynb#
2/14
7/26/23, 6:52 PM
NM-PYTHON-3 - Jupyter Notebook
In [ ]:
#list methods
"""
append()
insert()
extend()
remove()
pop()
count()
index()
copy()
clear()
reverse()
sort()
"""
l1 = [] # or l1 = list()
l1.append("Anusha")
print(l1)
l1.append("Jayanth")
print(l1)
l1.insert(0, "Soundarya")
print(l1)
l1.insert(-1, "Maniyan")
print(l1)
l1.insert(-10, "Rekha")
print(l1)
In [ ]:
print (l1.index("Anusha"))
In [ ]:
print(l1.index('Aasai'))
In [ ]:
l1.append("Anusha")
print(l1)
In [ ]:
print(l1.index("Anusha", l1.index("Anusha")+1))
In [ ]:
print(l1.count("Anusha"))
localhost:8888/notebooks/NM-PYTHON-3.ipynb#
3/14
7/26/23, 6:52 PM
NM-PYTHON-3 - Jupyter Notebook
In [ ]:
l1.sort()
print(l1)
In [ ]:
l1.reverse()
print(l1)
In [ ]:
l1.sort(reverse=False)
print(l1)
In [ ]:
l2 = ['Rekha', 'Soundarya', 'Anusha', 'Maniyan', 'Jayanth']
l2.sort(reverse=True)
print(l2)
In [ ]:
print(chr(2950))
In [ ]:
l3 = l1.copy()
print(l3)
In [ ]:
l1.clear()
print(l1)
In [ ]:
data = l3.pop()
print(l3, data)
In [ ]:
data = l3.remove("Anusha")
print(l3, data)
In [ ]:
print(l3.remove("Aasai")) # error
localhost:8888/notebooks/NM-PYTHON-3.ipynb#
4/14
7/26/23, 6:52 PM
NM-PYTHON-3 - Jupyter Notebook
In [ ]:
# tuple methods
"""
index()
count()
"""
t1 = 1,2,3
print(t1.count(2))
In [ ]:
#string methods
"""
upper()
lower()
title()
capitalize()
swapcase()
isupper()
islower()
isalpha()
isalnum()
isnumeric()
isprintable()
istitle()
isdigit()
isspace()
count()
find()
index()
rfind()
rindex()
startswith()
endswith()
translate()
maketrans()
split()
join()
ljust()
rjust()
center()
strip()
lstrip()
rstrip()
rsplit()
"""
name = "Vijay"
print(name.upper())
In [ ]:
name = name.upper()
print(name)
localhost:8888/notebooks/NM-PYTHON-3.ipynb#
5/14
7/26/23, 6:52 PM
NM-PYTHON-3 - Jupyter Notebook
In [ ]:
name = name.lower()
print(name)
In [ ]:
name = "vijay is smart"
name = name.title()
print(name)
In [ ]:
name = name.capitalize()
print(name)
In [ ]:
name = "SaBaRI"
print(name)
name = name.swapcase()
print(name)
In [ ]:
name = "SaBaRI@123"
print(name.isalpha())
In [ ]:
print(name.isalnum())
In [ ]:
print(name.find('a'))
In [ ]:
print(name.find('aB'))
In [ ]:
print(name.rfind('a'))
In [ ]:
print(name.count('a'))
localhost:8888/notebooks/NM-PYTHON-3.ipynb#
6/14
7/26/23, 6:52 PM
NM-PYTHON-3 - Jupyter Notebook
In [ ]:
#dictionary
contacts = dict() # contacts = {} ==> empty dictionary
contacts["Aasai"] = 9943115155
contacts["Aaron"] = 9943115155
contacts["Raja"] = [108, 100]
print(contacts)
contacts2 = {'Aasai': 9943115155, 'Aaron': 9943115155, 'Raja': [108, 100]}
In [ ]:
"""
dictionary methods
get()
update()
keys()
values()
pop()
fromkeys()
setdefault()
items()
"""
Set
Collection of unordered different type of elements enclosed with {}
It is mutable
It can have only unique elements
It does not have an index
In [ ]:
# create a set of integer type
student_id = {112, 114, 116, 118, 115}
print('Student ID:', student_id)
# create a set of string type
vowel_letters = {'a', 'e', 'i', 'o', 'u'}
print('Vowel Letters:', vowel_letters)
# create a set of mixed data types
mixed_set = {'Hello', 101, -2, 'Bye'}
print('Set of mixed data types:', mixed_set)
localhost:8888/notebooks/NM-PYTHON-3.ipynb#
7/14
7/26/23, 6:52 PM
NM-PYTHON-3 - Jupyter Notebook
In [ ]:
# create an empty set
empty_set = set()
# create an empty dictionary
empty_dictionary = { }
# check data type of empty_set
print('Data type of empty_set:', type(empty_set))
# check data type of dictionary_set
print('Data type of empty_dictionary', type(empty_dictionary))
Set Methods
add()
remove()
pop()
update()
clear()
copy()
union()
difference()
defference_update()
intersection()
intersection_update()
discard()
issubset()
issuperset()
OOPS
Python is a versatile programming language that supports various programming styles,
including object-oriented programming (OOP) through the use of objects and classes.
An object is any entity that has attributes and behaviors. For example, a parrot is an
object. It has
attributes - name, age, color, etc.
behavior - dancing, singing, etc.
Similarly, a class is a blueprint for that object.
localhost:8888/notebooks/NM-PYTHON-3.ipynb#
8/14
7/26/23, 6:52 PM
NM-PYTHON-3 - Jupyter Notebook
In [ ]:
class Parrot:
# class attribute
name = ""
age = 0
# create parrot1 object
parrot1 = Parrot()
parrot1.name = "Blu"
parrot1.age = 10
# create another object parrot2
parrot2 = Parrot()
parrot2.name = "Woo"
parrot2.age = 15
# access attributes
print(f"{parrot1.name} is {parrot1.age} years old")
print(f"{parrot2.name} is {parrot2.age} years old")
Inheritance
Inheritance is a way of creating a new class for using details of an existing class
without modifying it.
The newly formed class is a derived class (or child class). Similarly, the existing
class is a base class (or parent class).
localhost:8888/notebooks/NM-PYTHON-3.ipynb#
9/14
7/26/23, 6:52 PM
NM-PYTHON-3 - Jupyter Notebook
In [ ]:
# base class
class Animal:
def eat(self):
print( "I can eat!")
def sleep(self):
print("I can sleep!")
# derived class
class Dog(Animal):
def bark(self):
print("I can bark! Woof woof!!")
# Create object of the Dog class
dog1 = Dog()
# Calling members of the base class
dog1.eat()
dog1.sleep()
# Calling member of the derived class
dog1.bark();
Encapsulation
Encapsulation is one of the key features of object-oriented programming. Encapsulation
refers to the bundling of attributes and methods inside a single class.
It prevents outer classes from accessing and changing attributes and methods of a
class. This also helps to achieve data hiding.
In Python, we denote private attributes using underscore as the prefix i.e single _ or
double __. For example,
localhost:8888/notebooks/NM-PYTHON-3.ipynb#
10/14
7/26/23, 6:52 PM
NM-PYTHON-3 - Jupyter Notebook
In [ ]:
class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
def setMaxPrice(self, price):
self.__maxprice = price
c = Computer()
c.sell()
# change the price
c.__maxprice = 1000
c.sell()
# using setter function
c.setMaxPrice(1000)
c.sell()
Polymorphism
Polymorphism is another important concept of object-oriented programming. It simply
means more than one form.
That is, the same entity (method or operator or object) can perform different
operations in different scenarios.
Let's see an example,
localhost:8888/notebooks/NM-PYTHON-3.ipynb#
11/14
7/26/23, 6:52 PM
NM-PYTHON-3 - Jupyter Notebook
In [ ]:
class Polygon:
# method to render a shape
def render(self):
print("Rendering Polygon...")
class Square(Polygon):
# renders Square
def render(self):
print("Rendering Square...")
class Circle(Polygon):
# renders circle
def render(self):
print("Rendering Circle...")
# create an object of Square
s1 = Square()
s1.render()
# create an object of Circle
c1 = Circle()
c1.render()
In [ ]:
In [ ]:
class Bank_Account:
def __init__(self):
self.balance=0
print("Welcome to Deposit & Withdrawal Machine!")
def deposit(self):
amount=float(input("Enter amount to be deposited: "))
self.balance += amount
print("Amount Deposited: ",amount)
def withdraw(self):
amount = float(input("Enter amount to withdraw: "))
if self.balance>=amount:
self.balance-=amount
print("You withdraw: ",amount)
else:
print("Insufficient balance ")
def display(self):
print("Net Available Balance=",self.balance)
#creating an object of class
s = Bank_Account()
#calling functions with that class
s.deposit()
s.withdraw()
s.display()
localhost:8888/notebooks/NM-PYTHON-3.ipynb#
12/14
7/26/23, 6:52 PM
NM-PYTHON-3 - Jupyter Notebook
In [ ]:
class Animal:
# attribute and method of the parent class
name = ""
def eat(self):
print("I can eat")
# inherit from Animal
class Dog(Animal):
# new method in subclass
def display(self):
# access name attribute of superclass using self
print("My name is ", self.name)
# create an object of the subclass
labrador = Dog()
# access superclass attribute and method
labrador.name = "Rohu"
labrador.eat()
# call subclass method
labrador.display()
localhost:8888/notebooks/NM-PYTHON-3.ipynb#
13/14
7/26/23, 6:52 PM
NM-PYTHON-3 - Jupyter Notebook
In [ ]:
class Shape:
def __init__(self, name):
self.name = name
def area(self):
pass
def fact(self):
return "I am a two-dimensional shape."
def __str__(self):
return self.name
class Square(Shape):
def __init__(self, length):
super().__init__("Square")
self.length = length
def area(self):
return self.length**2
def fact(self):
return "Squares have each angle equal to 90 degrees."
class Circle(Shape):
def __init__(self, radius):
super().__init__("Circle")
self.radius = radius
def area(self):
return pi*self.radius**2
a = Square(4)
b = Circle(7)
print(b)
print(b.fact())
print(a.fact())
print(b.area())
localhost:8888/notebooks/NM-PYTHON-3.ipynb#
14/14
Download