py 3
py 3
JSON
# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'
# parse x:
y = json.loads(x)
RegEx
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.
findall - Returns a list containing all matches
search - Returns a Match object if there is a match anywhere in the string
split - Returns a list where the string has been split at each match
sub - Replaces one or many matches with a string
findall() Function
search() Function
The search() function searches the string for a match, and returns a Match object if there is a
match.
If there is more than one match, only the first occurrence of the match will be returned:
import re
split() Function
The split() function returns a list where the string has been split at each match:
import re
sub() Function
The sub() function replaces the matches with the text of your choice:
import re
.span() returns a tuple containing the start-, and end positions of the match.
.string returns the string passed into the function
.group() returns the part of the string where there was a match
import re
User Input
Python allows for user input.
String Formatting
The format() method allows you to format selected parts of a string.
To control such values, add placeholders (curly brackets { }) in the text, and run the values
through the format() method:
price = 49
txt = "The price is {} dollars"
print(txt.format(price))
price = 49
txt = "The price is {:.2f} dollars"
print(txt.format(price))
The price is 49.00 dollars
Multiple Values
If you want to use more values, just add more values to the format() method:
quantity = 3
itemno = 567
price = 49
myorder = "I want {} pieces of item number {} for {:.2f} dollars."
print(myorder.format(quantity, itemno, price))
I want 3 pieces of item number 567 for 49.00 dollars.
Index Numbers
You can use index numbers (a number inside the curly brackets {0}) to be sure the values are
placed in the correct placeholders:
quantity = 3
itemno = 567
price = 49
myorder = "I want {0} pieces of item number {1} for {2:.2f} dollars."
print(myorder.format(quantity, itemno, price))
I want 3 pieces of item number 567 for 49.00 dollars.
age = 36
name = "John"
txt = "His name is {1}. {1} is {0} years old."
print(txt.format(age, name))
Named Indexes
You can also use named indexes by entering a name inside the curly brackets {carname}
myorder = "I have a {carname}, it is a {model}."
print(myorder.format(carname = "Ford", model = "Mustang"))
I have a Ford, it is a Mustang.
File Handling
The key function for working with files in Python is the open() function.
#f = open("file.txt")
Read File
f = open("demo.txt", "r")
print(f.read())
File handling is an integral part of programming. File handling in Python i
s simplified with built-in methods, which include creating, opening, and cl
osing files. While files are open, Python additionally allows performing va
rious file operations, such as reading, writing, and appending information.
Read Lines
f = open("demo.txt", "r")
print(f.readline())
File handling is an integral part of programming.
Close Files
It is a good practice to always close the file when you are done with it.
f = open("demo.txt", "r")
print(f.readline())
f.close()
File handling is an integral part of programming.
To write to an existing file, you must add a parameter to the open() function:
"a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content
f = open("demo1.txt", "a")
f.write("Now the file has more content!")
f.close()
To create a new file in Python, use the open() method, with one of the following parameters:
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist
f = open("myfile.txt", "x") #a new empty file is created!
f = open("myfile.txt", "w") #Create a new file if it does not exist:
Delete a File
To delete a file, you must import the OS module, and run its os.remove() function:
import os
os.remove("demofile.txt")
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-35-e4f794a2e954> in <module>()
1 import os
----> 2 os.remove("demofile.txt")
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
The file does not exist
Delete Folder
Classes/Objects
A Class is like an object constructor, or a "blueprint" for creating objects.
class MyClass:
x=5
#object
p1 = MyClass()
print(p1.x)
5
Object Methods
Objects can also contain methods. Methods in objects are functions that belong to the object.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
Hello my name is John
Abstraction in Python
Abstraction is used to hide the internal functionality of the function from the users. The users only
interact with the basic implementation of the function, but inner working is hidden. User is familiar
with that "what function does" but they don't know "how it does."
# Python program demonstrate
# abstract base class work
from abc import ABC, abstractmethod
class Car(ABC):
def mileage(self):
pass
class Tesla(Car):
def mileage(self):
print("The mileage is 30kmph")
class Suzuki(Car):
def mileage(self):
print("The mileage is 25kmph ")
class Duster(Car):
def mileage(self):
print("The mileage is 24kmph ")
class Renault(Car):
def mileage(self):
print("The mileage is 27kmph ")
# Driver code
t= Tesla ()
t.mileage()
r = Renault()
r.mileage()
s = Suzuki()
s.mileage()
d = Duster()
d.mileage()
The mileage is 30kmph
The mileage is 27kmph
The mileage is 25kmph
The mileage is 24kmph
Encapsulation in Python
wrapping data and methods that work with data in one unit. This prevents data modification
accidentally by limiting access to variables and methods.
class Employee:
# constructor
def __init__(self, name, salary, project):
# data members
self.name = name
self.salary = salary
self.project = project
# method
# to display employee's details
def show(self):
# accessing public data member
print("Name: ", self.name, 'Salary:', self.salary)
# method
def work(self):
print(self.name, 'is working on', self.project)
Python Inheritance
Inheritance enables us to define a class that takes all the functionality from a parent class and
allows us to add more.
class Polygon:
def __init__(self, no_of_sides):
self.n = no_of_sides
self.sides = [0 for i in range(no_of_sides)]
def inputSides(self):
self.sides = [float(input("Enter side "+str(i+1)+" : ")) for i in range(self.n)]
def dispSides(self):
for i in range(self.n):
print("Side",i+1,"is",self.sides[i])
class Triangle(Polygon):
def __init__(self):
Polygon.__init__(self,3)
def findArea(self):
a, b, c = self.sidesvv
# calculate the semi-perimeter
s = (a + b + c) / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)
t = Triangle()
>>> t.inputSides()
Enter side 1 : 3
Enter side 2 : 5
Enter side 3 : 4
>>> t.dispSides()
Side 1 is 3.0
Side 2 is 5.0
Side 3 is 4.0
>>> t.findArea()
The area of the triangle is 6.00
File "<ipython-input-77-b85143daecbc>", line 3
>>> t.inputSides()
^
SyntaxError: invalid syntax
Polymorphism:
The word polymorphism means having many forms. In programming, polymorphism means the
same function name (but different signatures) being used for different types. The key difference
is the data types and number of arguments used in function.
#Example of inbuilt polymorphic functions:
5
3
# A simple Python function to demonstrate
# Polymorphism
def add(x, y, z = 0):
return x + y+z
# Driver code
print(add(2, 3))
print(add(2, 3, 4))
class India():
def capital(self):
print("New Delhi is the capital of India.")
def language(self):
print("Hindi is the most widely spoken language of India.")
def type(self):
print("India is a developing country.")
class USA():
def capital(self):
print("Washington, D.C. is the capital of USA.")
def language(self):
print("English is the primary language of USA.")
def type(self):
print("USA is a developed country.")
obj_ind = India()
obj_usa = USA()
for country in (obj_ind, obj_usa):
country.capital()
country.language()
country.type()
In Python, Polymorphism lets us define methods in the child class that have the same name as
the methods in the parent class. In inheritance, the child class inherits the methods from the
parent class. However, it is possible to modify a method in a child class that it has inherited from
the parent class. This is particularly useful in cases where the method inherited from the parent
class doesn’t quite fit the child class. In such cases, we re-implement the method in the child
class. This process of re-implementing a method in the child class is known as Method
Overriding.
class Bird:
def intro(self):
print("There are many types of birds.")
def flight(self):
print("Most of the birds can fly but some cannot.")
class sparrow(Bird):
def flight(self):
print("Sparrows can fly.")
class ostrich(Bird):
def flight(self):
print("Ostriches cannot fly.")
obj_bird = Bird()
obj_spr = sparrow()
obj_ost = ostrich()
obj_bird.intro()
obj_bird.flight()
obj_spr.intro()
obj_spr.flight()
obj_ost.intro()
obj_ost.flight()
class Animal:
def speak(self):
raise NotImplementedError("Subclass must implement this method")
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
Woof!
Meow!
#SYNTAX ERROR
# initialize the amount variable
amount = 10000
#EXCEPTIONS
# initialize the amount variable
marks = 10000
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-7-75eedf38684f> in <cell line: 6>()
4
5 # perform division with 0
----> 6 a = marks / 0
7 print(a)
ZeroDivisionError: division by zero
TYPE ERROR
TypeError: This exception is raised when an operation or function is applied to an object of the
wrong type. Here’s an example:
x=5
y = "hello"
z = x + y # Raises a TypeError: unsupported operand type(s) for +: 'int' and 'str'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-8-d6c146f786ff> in <cell line: 3>()
1 x = 5
2 y = "hello"
----> 3 z = x + y # Raises a TypeError: unsupported operand type(s) for +:
'int' and 'str'
Try and except statements are used to catch and handle exceptions in Python. Statements that
can raise exceptions are kept inside the try clause and the statements that handle the exception
are written inside except clause.
# Python program to handle simple runtime error
#Python 3
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
except:
print ("An error occurred")
Second element = 2
An error occurred
Raising Exception
The raise statement allows the programmer to force a specific exception to occur. The sole
argument in raise indicates the exception to be raised. This must be either an exception instance
or an exception class (a class that derives from Exception).
# Program to depict Raising Exception
try:
raise NameError("Hi there") # Raise Error
except NameError:
print ("An exception")
raise # To determine whether the exception was raised or not
An exception
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-10-87bf2bdaba1c> in <cell line: 3>()
2
3 try:
----> 4 raise NameError("Hi there") # Raise Error
5 except NameError:
6 print ("An exception")
NameError: Hi there
EXERCISE
class programs:
1. Write a Python class which has two methods get_String and print_String. get_String
accept a string from the user and print_String print the string in upper case
2. Write a Python class named Rectangle constructed by a length and width and a method
which will compute the area of a rectangle.
3. Write a Python class named Circle constructed by a radius and two methods which will
compute the area and the perimeter of a circle.
INHERITANCE
1)Write a Python program to create a Vehicle class with max_speed and mileage instance
attributes.
3)Create a child class Bus that will inherit all of the variables and methods of the Vehicle
class.Given class Vehicle:
self.name = name
self.max_speed = max_speed
self.mileage = mileage
4)Create a Bus class that inherits from the Vehicle class. Give the capacity argument of
Bus.seating_capacity() a default value of 50.
class Vehicle: def init(self, name, max_speed, mileage): self.name = name self.max_speed =
max_speed self.mileage = mileage
5)Define a class attribute”color” with a default value white. I.e., Every Vehicle should be white.
self.name = name
self.max_speed = max_speed
self.mileage = mileage