0 ratings 0% found this document useful (0 votes) 33 views 11 pages Python Part2
The document outlines various Python functions for managing employee data, including updating salaries and searching for employees by ID. It also discusses file handling for text, CSV, and JSON formats, emphasizing the importance of exception handling in Python. Additionally, the document touches on encryption methods and custom exceptions for password validation.
AI-enhanced title and description
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Go to previous items Go to next items
Save python part2 For Later upaate_employe ‘salaries
with open(File_nane,"w")as file
‘or data in updated deta:
‘File.write(datay"\n")
iprint("The updated details are:")
For data in updated data
print (data)
def search enployee.by id(File_nane,enp_id)f
found-Fale|
‘ith open(file_nane,“r")as file
‘sor line 19 #6
‘eidynane,salary-Line.strip()-split(’,")
Sf ha. strap()=-enp_id
print(frthe employee {nane.strip()} withname. scrap) 77 (UPIBTEO 33
porcea_oacaappenatT (&97=107>
with open(File_nane, "x")as file
"for data in updated data
file.write(datas"\o")
Iprint("The updated details are:")
for data in updated data:
print(data)
Het search employee. by_1d(file_nane,enp_id)b
found-False
ith open(file_nane,"r")as file
for Hine in file: 4
eidsnane,salary-Line.strip()-sPHt("»
Sf eld.strip()--enp_id ;
pric trte enpoye (nam, trip) 58h id (oop_id} has salary Rs-{salary.stea
break
Af not found:
print (one records) found")
File nane~"enployee txta
eee
Product +7)
Informe
main. py
Description
Objective:
To work with Text
Files
Concept
Explanation:
+ Text les 3
contain textual
date encoded in
a specif
character
lencoding such
05 UTF-8 or
ASCIL Python's
file-handting 2
copobiities can
create, read,
write. ang
Sate pred ayer PONG Sh asinenetale
Ines cays eontarel
row file writelines(*\n")
nge(new_num_toys)
y_detall=inpat()
detail)
all_content=now_file.read(:
cio & ee
Feedback
HE sew
70m ,For — in range(new_num_toys):
Foy_detaileinpat()
'oys. append(toy_detail)
with open(‘new toys.txt',‘a")as new file:
fer toy in new toys:
pew_file.urite(toy+"\0")
with open(*new toys.txt",'r’)as new file:
all_content=new file,read()
print(all_content)
print(*No.of toys: (Len(all_content.splitlines())}.") I
‘except FileNitFoundérror: f
Print("The file ‘toys.trt? does not exists. Please make sure the file is in #
$f name == *_main_" Z
main) 53+ def main():
Be try:
Ss: with open(‘onebayinternational.csv",'t")as File:
reader-csv.OictReader(file)
countriessset()
For now in reader:
countries .add(rou[' versus")
sorted _countriesssorted(countries)
| for country in sorted countries
pint Country)
except FélewotFounderror
pint ("The File ‘OneDayInternational.csv" does not exist.
i t se
ae
df, ,
- # Ft 2EG] A _—_G Mrosseognzatresaccom/modiptorslest pp 61ers 87908
jerthe 37
Counties “* ©
‘Sachin has
Played
‘Against - CSV
file
Description
Objective:
Lrtries-set()
ees rs }
Boer A tact lle omecies
fpanation Pe
+ csv (Comma- Fine tite ‘Oneoayinterrational.csv' does not exist. Please make sure the #ile Saline
cee
Values) files are a
ae
Bests
eran
—
eres
Eotacisomn,wa men
Fitter ne 8 ®
“Gustomerd > _ YAH)
Ssonrie Gon
1 heport Jeon
2
3 def Filter_custoners(loan_type)
with open(loan.json’, 'r")as f:
data-json.load(f)
‘filtered custoners-[]
Towork with 1son
“files 7
a
3
for customer Sn data["custoner
for Lean in eustoner( loans]
Concept aa> At loan‘ loan_type’ ]=~1oan_type:
Explanation: 2 ‘Filtered customers. append{ (custoner[ ‘Account. Mnber" je
+ JSON if Filtered customers:
Perec int (*\n Coan Detais\0")
& et print ("Account_number customer_name loan_amount™)
Object ie or custoner date in filtered Zusteners?
Notation) fies 3s
prineceTeustone~ data) (certo data] (customer data
Desnt(No custoners avaiable)
Bs tom.type-input(“ter the loan cpa")
Bi rsteseactteers(aone Sipe)Description | ;
Objective: agree coe
Toworkwith JSON
files
Concept
Explonation:
rane" J Joan{Loan_anount'})
+ JSON m
(ovaseript
‘Object peas F “
Notation) files
cre o popular 4,
Fa eee errs
interchange: Dre atert he star pe
format used to 4 stoners (Loan type)
store and i
exchange
Terminal Feedback | * nO
structured doto.
Ba @r.zease a2 Seas"_init_(self,cost, type)
Felf,__cost=float (cost)
self.
-0,02*self,_cost
ostself._cost
self.__premiun-2.0
def get_prenium(self):
Feturn self,preniue
vehicle cost=float(input("Enter the vehicle cost:"))
Vehicle-type-int(input("Enter the type of vehicle (1 for 2 wheeler, 2 for 4 wh
vehicle objavehicie(venicie cost vehicle type)‘encryption py
1 import re
2
3+ def encrypt_message(nessage):
4- det replace char(naten
5 charomateh.group(e)
& iF char isalpha(
a iF char
8 returo ‘3!
3 elif chan == '2
20 return "a"
ru else:
ing and string manipulation in Python. a return chr(ord(char)sa)
‘allow us to efficiently search, match, and Be elif chan. isaigit(): 2
ee text based on specific patterns. 1 ur, stint (ehar) 29818)
5 return char
i
17 encrypt_nessage=re.sub(r[a-24-20-9]"s1
ptimplementation: ie Pre
20 nessage=input(“actual_wessag
latio, the message is encrypted by 2) res-encrypt_message(nessage)
|each alphabetic character with its 22 print( "Encrypted nessage:(res}")
ant character using regular expressions
‘module,Se PPE /rognisent fekstac com/niod/yp\forms/edit php?id:
< Password Update
Description
Winport necessary nodule here
Objective: fron password. validation inport va
From exception inport(
Passnorduengthexception,
Passhordcaseexception,
Passworddigitexception,
PasshordspecialcharException,
i
To work with Exception Handling.
Concept Explanation
* Exception handling in Python allows for the pai? tes Seneca
‘management of runtime errors by defining 3 =
custom exceptions, endbiing specific eror Be try
coneitios to be captured and handled 7 cepttevaaate perirdenps
graceful. xcept PasshordLengthexception a 2
Srane(f-inialsé persue)
Pasguordeasebrception 35
eine #-invali passvond fe)
‘concept implementation: crepe puaneorbia tetera aa
= Print (fTnvelld passords(@}")
+ Inthis scenario, custom exceptions xcept Pasauordspecialehorbsception 35:
ee ccm. : «PSertsniCertnvalid passe)
PasewordCasetsception,
‘PasswordDigitxception, and .
“Fasswordspecioichartxception) are detine