0% found this document useful (0 votes)
10 views

py 3

The document provides an overview of JSON and its conversion between Python and JSON formats, as well as Regular Expressions (RegEx) and their functions in Python. It also covers user input, string formatting, file handling, and object-oriented programming concepts such as classes, methods, inheritance, encapsulation, and polymorphism in Python. Each section includes code examples to illustrate the concepts discussed.

Uploaded by

Mariya Jacob
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

py 3

The document provides an overview of JSON and its conversion between Python and JSON formats, as well as Regular Expressions (RegEx) and their functions in Python. It also covers user input, string formatting, file handling, and object-oriented programming concepts such as classes, methods, inheritance, encapsulation, and polymorphism in Python. Each section includes code examples to illustrate the concepts discussed.

Uploaded by

Mariya Jacob
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Oops FileHandling

JSON

JSON is a syntax for storing and exchanging data.

JSON is text, written with JavaScript object notation.

Convert from Python to JSON


import json

# a Python object (dict):


x={
"name": "John",
"age": 30,
"city": "New York"
}

# convert into JSON:


y = json.dumps(x)

# the result is a JSON string:


print(y)
{"name": "John", "age": 30, "city": "New York"}

Convert from JSON to Python


import json

# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'

# parse x:
y = json.loads(x)

# the result is a Python dictionary:


print(y["age"])
30

RegEx

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.
 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

The findall() function returns a list containing all matches.


import re

txt = "The rain in Spain"


x = re.findall("ai", txt)
print(x)
['ai', 'ai']

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

txt = "The rain in Spain"


x = re.search("\s", txt) #\s Returns a match where the string contains a white space character

print("The first white-space character is located in position:", x.start())


The first white-space character is located in position: 3
import re

txt = "The rain in Spain"


x = re.search("Portugal", txt)
print(x)
None

split() Function

The split() function returns a list where the string has been split at each match:
import re

txt = "The rain in Spain"


x = re.split("\s", txt)
print(x)
['The', 'rain', 'in', 'Spain']

sub() Function

The sub() function replaces the matches with the text of your choice:
import re

txt = "The rain in Spain"


x = re.sub("\s", "9", txt)
print(x)
The9rain9in9Spain
import re

txt = "The rain in Spain"


x = re.sub("\s", "9", txt, 2) #count=2
print(x)
The9rain9in Spain
import re

txt = "The rain in Spain"


x = re.search("ai", txt)
print(x) #this will print an object
<_sre.SRE_Match object; span=(5, 7), match='ai'>

 .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

txt = "The rain in Spain"


x = re.search(r"\bS\w+", txt)
print(x.string)
The rain in Spain

User Input
Python allows for user input.

That means we are able to ask the user for input.


username = input("Enter username:")
print("Username is: " + username)
Enter username:john
Username is: john

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))

The price is 49 dollars


#Format the price to be displayed as a number with two decimals:

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))

His name is John. John is 36 years old.

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.

The open() function takes two parameters; filename, and mode.


 "r" - Read - Default value. Opens a file for reading, error if the file does not exist
 "a" - Append - Opens a file for appending, creates the file if it does not exist
 "w" - Write - Opens a file for writing, creates the file if it does not exist
 "x" - Create - Creates the specified file, returns an error if the file exists
#To open a file for reading it is enough to specify the name of the file:

#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 Only Parts of the File


f = open("demo.txt", "r")
print(f.read(5))
File

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.

Write to an Existing File

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()

#open and read the file after the appending:


f = open("demo1.txt", "r")
print(f.read())
File handling is an integral part of programming.
File handling in Python is simplified with built-in
methods, which include creating, opening, and closing
files. While files are open, Python additionally
allows performing various file operations, such
as reading, writing, and appending information.Now the file has more conten
t!Now the file has more content!Now the file has more content!
f = open("demo1.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()

#open and read the file after the appending:


f = open("demo1.txt", "r")
print(f.read())
Woops! I have deleted the content!

Create a New File

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")

FileNotFoundError: [WinError 2] The system cannot find the file specified:


'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

To delete an entire folder, use the os.rmdir() method:


import os
os.rmdir("myfolder")
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-37-35d2d6158629> in <module>()
1 import os
----> 2 os.rmdir("myfolder")

FileNotFoundError: [WinError 2] The system cannot find the file specified:


'myfolder'
Python Object Oriented
class student:
name="abc"
roll=4
obj=student()
obj.name
Out[3]:
'abc'
obj.roll
Out[4]:
4
class student:
def __init__(self,nm,ag, gend,roll):
self.name=nm
self.age=ag
self.gender=gend
self.roll_no=roll
def display(self):
print(self.name,self.age,self.roll_no,self.gender)
stu_1=student("abc",15,'m',1)
stu_2=student("xyz",15,'f',2)
stu_1.name
Out[57]:
'abc'
stu_2.name
Out[58]:
'xyz'
stu_2.display()
xyz 15 2 f
stu_1.display()
abc 15 1 m

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)

# creating object of a class


emp = Employee('Jessa', 8000, 'NLP')

# calling public method of the class


emp.show()
emp.work()
Name: Jessa Salary: 8000
Jessa is working on NLP

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:

# Python program to demonstrate in-built poly-


# morphic functions

# len() being used for a string


print(len("geeks"))

# len() being used for a list


print(len([10, 20, 30]))

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))

#Polymorphism with class

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()

New Delhi is the capital of India.


Hindi is the most widely spoken language of India.
India is a developing country.
Washington, D.C. is the capital of USA.
English is the primary language of USA.
USA is a developed country.

Polymorphism with Inheritance:

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()

There are many types of birds.


Most of the birds can fly but some cannot.
There are many types of birds.
Sparrows can fly.
There are many types of birds.
Ostriches cannot fly.
#Simple example of polymorphism:
#polymorphism in Python using inheritance and method overriding:

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!"

# Create a list of Animal objects


animals = [Dog(), Cat()]

# Call the speak method on each object


for animal in animals:
print(animal.speak())

Woof!
Meow!

PYTHON EXCEPTION HANDLING

#SYNTAX ERROR
# initialize the amount variable
amount = 10000

# check that You are eligible to


# purchase Dsa Self Paced or not
if(amount > 2999)
print("You are eligible to purchase Dsa Self Paced")

File "<ipython-input-6-72b3dee2a066>", line 7


if(amount > 2999)
^
SyntaxError: expected ':'

#EXCEPTIONS
# initialize the amount variable
marks = 10000

# perform division with 0


a = marks / 0
print(a)

---------------------------------------------------------------------------
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'

TypeError: unsupported operand type(s) for +: 'int' and 'str'

Try and Except Statement – Catching Exceptions

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]))

# Throws error since there are only 3 elements in array


print ("Fourth element = %d" %(a[3]))

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.

2)create a Vehicle class without any variables and methods.

3)Create a child class Bus that will inherit all of the variables and methods of the Vehicle
class.Given class Vehicle:

def __init__(self, name, max_speed, mileage):

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.

Use the following code for your parent Vehicle class.

class Vehicle: def init(self, name, max_speed, mileage): self.name = name self.max_speed =
max_speed self.mileage = mileage

def seating_capacity(self, capacity):


return f"The seating capacity of a {self.name} is {capacity}
passengers"

5)Define a class attribute”color” with a default value white. I.e., Every Vehicle should be white.

Use the following code for this exercise. class Vehicle:

def __init__(self, name, max_speed, mileage):

self.name = name

self.max_speed = max_speed

self.mileage = mileage

class Bus(Vehicle): pass

class Car(Vehicle): pass

You might also like