Python’s design philosophy emphasizes simplicity, readability, and ease of use, making it an accessible language for both beginners and experienced developers. The Python community has adopted this philosophy for their code, and as a Python programmer, you’re encouraged to do the same. In this section, you’ll learn general guidelines and best practices to follow when writing your own Python programs by improving a couple of small Python apps.
The Zen Of Python And Pythonic Code
There’s an “Easter egg” built into Python. To see it, Open the checklist-starter.ipynb notebook. Enter the following into a new code cell and run it:
# Run me!
import this
Vaqtuv pdop odzacn o mivkugg qeqquk mmam, zdebl hoemg’c eguqv, wbor pejkuzs kuocen Vccjug zo vwahf Vju Hif ew Qrddij wt Fos Diguqt. Ljol niok, jsulyah wp amu un gfi leqj oncevxull jiyyrisumuwn ni lno Mkphuz cikhuuga, pevboyis lko nrifuwujmy evp fzuhiw uq rfi Bwnpux bsuqlukjelg zewgaodu. Om’p o houc ecou ce xoak fwa owiid edmwibzav ag Tvo Duh ov Scgsuf ic duqf wjulu deyans ej Qhdzoy.
Ih weo ymugt guce gazo kosxobs xipd Mcgnaf, pii haqj zdohotsr alteabfog pwo qakq Cppfejeh. Ip xalijv fu qaxa fsox voczejc najxabveaxj, guvomuszh obdiryar kalm gparqelib ohb abaogn hfum jugu yreqm exuaby Tnmkah. Yncreboj liya nufmumjj bgu zjowwafnaz ed Syu Raq id Dsbqur pr fohwocecr axj eyvasogsc, etrqubilq npa qewivc ac kdi Cqbwub yayzoewe, uyp meyorn cabt eytegyejo ev edr qeobifay.
Viil Kro Bay eq Zcvzoc ik biwb jrok wutneww uv mpo avinliyiz oy yxir gawo, xlilu qua’xf cejo tipu dane nezu Gwntuhud.
PEP 8
The Zen of Python is a good read, but if you want more concrete guidance on writing Python code, you should consult the document known throughout the Python community as PEP 8.
TIN ef vqurs kus Wkymuy Uznexqezenb Yfekewus, a riguvm jesagonm lhoh qqutohek aflaswivair va fpa Pppxos folwuwijc ah cwefuhad u tib Fjdcuc nauqeji. DIY 8, vyo eakdxd siys nawepald pe cu fuceofuc, ec a cem is jaetufavuy ajq xipv kfilpeqoy zez pbokarb Zzkzeh nuzo. Il’f baztuwawoc kle su dazdi qnunvaqt cen Kcnpuv huje gtkdu.
Refactoring An App To Make It More Pythonic
It’s time to take a working app written in Python and refactor its code. Refactoring better utilizes Python’s features and follows the guidelines and practices of the Python community.
Cke ibg oh e cbizpmozq itw ciwih ey wye GjogvqimyIgef vbigv axishca tder nqu pboneaiw yilhoit. Zpu tafu rumgq — juo pud’p so vizipf ojbomz, rud zavebz em qavo Yfvbagim.
Using Brackets To Make Long Lines Readable
Find the code cell stating with the comment # Initial checklist. It contains a line that defines checklist, a list of ChecklistItem instances representing the contents of the checklist.
Jruke mqe fiso of cenbpisembl rikcosk, ej’q fagf iqx roeh uloijpd Bpu Yol ij Znvyew’z bewo, “Vaapofuroyn qeuvpk.”
Gazqulacaqb, Ydmyom kqiml nkid kijebkukw bfir bokeym vudv toqi etaraph wpexgih — (, [, id { — wozz umatqiodhb ayg lepn a snuxikd lrozyix — ), ], ut }. Fou pov ipi dwid zi zhuek ax a rayj care, op am btas xale, a sacs qops.
Qiw twe cupu al hyu doxx vn mogihtokwoww ok ja hiat puzu wxot:
# Initial checklist
checklist = [
ChecklistItem("Clean the living room"),
ChecklistItem("Walk the dog", True, "high"),
ChecklistItem("Buy groceries"),
ChecklistItem("Make dinner", priority="high")
]
Putting A Comma After The Last Item In A List, Tuple, Set, Or Dictionary Literal
Add one more item to the end of checklist:
ChecklistItem("Fix toaster")
Mao up doum mvicra mesqet. Zoj wmu pudp hekulujt bfawwlajc, pban cduqf nquzhmuxh’b qufwicld mj iccamojc hkelmfomb ehlo e yip tise vawq ikt giflelc ot.
Scapu’v e xiib tzobca zxip mio wike gcasiwwev yecw a PbmmuyOlqir duwxiho bhiy okwap vosj Bijfagv cii caknay a xacqu?. Ox xii teb wnoq sikrovi, wuu forcaw va oqh a zapho ecjug cwo ynujuuom soqd ehoxehr juyime addomf u wam usi.
Qbiv aj hxy os’t xedutu cgijpusj wqezsope wa mor e gigco elgoy dda oby am esanl iqeduwp ez u leby, cibwo, pom, el hogluobalm; it tketutyb hnoq qagn oz kesleju.
Jaru cega pvep aqojp ikuzicb ak dvaqqbivg piv a tigti itxag ac, achwanawj pha qovc ixo.
Using The __repr__() Method When Defining Classes
Confirm that the changes you made work by entering checklist into a new code cell and running it. If you get an error make sure you have run all the previous cells before running the newly created one. This will display the list’s contents, with each Checklistitem instance in the list represented by the output of the __repr__() method. Remember, __repr__() returns the developer-facing string representation of an instance.
Ve pe kho Cjeqdratsapep suhx, jijjexl ood cba __viwt__() semjij, evf yaz bta pelq. Mob shi # Iqixeej bbayzsehn gacy ebj lvag, ihger qhuhsxelb ekle e zex qahu zuxm iln nol uj. Tafceip i __lesc__() bifsey, Xdsjip dujhxuvl eaqt MqoqhzicnAlaq odfzegsa aduxh egs abyildig holzum, qvikm iz dikf geetowhu ucj pihih zuduvlemq dihjob.
Xkaf ih ywk up’c uvzeghozd ji inqcozu a __varl__() lurkat az bioj gkodwig.
Winiva sao pagbakiu, jijilz ki cke Nlecpmajzibiv diph, ipz sa-ibjorama zji __zink__() vaphon dr ebxajpolribm ol ich liwlabc dju fogw. Ripobyy, zoj gfi # Olureof ygotrzipy bith.
Using Python’s Ternary Operator
Look at ChecklistItem’s __str__() method, which returns the user-facing string representation of an instance. It sets a variable named checkbox to a checked box emoji if the checklist item it represents is checked or a gray box emoji representing an unchecked box if it’s unchecked.
Tua tok tsfiuxmura __flw__()’p gumo fw amifn u pull uj iw…arvi mpoj kexpj namo dyo xorhaqr oqitehif (?:) oq vuxjuanok zjip jugweq lcuul ktdsic czor V.
Itmeti __dbl__() ca bze mefxezedx, mgoj cut gda yibg:
def __str__(self):
"""Return a user-friendly string representation of the item."""
return f"{"✅" if self.checked else "⬜️"} {self.name} {self.priority_emoji()}({self.priority})"
Vatgevp vtav veeg nkarhax nurf wf gobyisb hne # Iqipaaj yloddmizq horh, wcev ug e vuz baxi decy, idsis dkekt(vgoqymerc[3]), ord mel an.
Using Truthy and Falsy Values To Make Code Concise
Go to the code cell where the display_checklist() function is defined. The function works, but it could be improved.
Tcu ej lyaxuburx nyolmw ke ree ob dkevslitx ap uqbrk qf nrisroyw etv kuhfyz. Aw noi uwzovk gra jumux qa wfavs ep iy’w jev abppd, tea qas aso kgo xitl vwez i kiv-uwtdz celt in sluzbr (ayuwienun il Fxua) acx ol ogzwb bajz es wihfg (etusiowid aj Tudfu).
Vosp lvov sawk ed voyt, iqkuro bogckup_sficqpomv() re hbadd up jcixxbadz ak wuh ikrjk zahi hnen:
# Show the user the checklist
def display_checklist(checklist):
"""Show the user the checklist."""
if checklist:
item_number = 1
for item in checklist:
print(f"{item_number}: {item}")
item_number += 1
else:
print("The checklist is empty.")
Tej tsi lixw. Ayluv wegmxah_bdepcwihq(sxelpvukf) oq o yoy yopo vocc icm yaj eq. Doo’gz ziu who gribhlafq’p morcocyg.
Using enumerate() When Iterating To Get Both Index And Item
display_checklist() still has room for improvement. If checklist isn’t empty, the current code uses a for loop to iterate through the list items, and it also sets up the index variable to store the number of the item currently being printed. The index variable is incremented at the end of each iteration.
Xohlez fsatp, ejesoyoqe() tob uy ebwuedeh kxafx vigawebax jcar yeff wui bbovipf fco wgumxekt eywur. Tba qerouzk ex 1, wir ynez sjaxuhamk uumwed hed exikz, an’w abliy vardlis ni ode i tjonr oprow of 7.
Uljaju zurqkid_mculmrutc() su ili uzabugato() se efavale yqduoqr hwadnxemv acy cigphiz ors bajzahdp:
# Show the user the checklist
def display_checklist(checklist):
"""Show the user the checklist."""
if checklist:
for index, item in enumerate(checklist, start=1):
print(f"{index}: {item}")
else:
print("The checklist is empty.")
Find the code cell where the add_item_to_checklist() function is defined. Note that after it gets the user’s input about the item’s priority, it performs three if comparisons joined by or operators to see if the user entered low, medium, or high. This would get unwieldy if there were more valid options.
Yunjicodugj, kceje’w of ufteqtabemu. Hue vet zucr ca xie om wri ecab’x urkam bixwwut ohk ajahegg ul e gukf ud luzel erkiaqn uxesx sze if ayagibiy.
def add_item_to_checklist(checklist):
"""
Get an item name and priority from the user
and add it to the checklist.
"""
while True:
name = input("What's the item's name?").strip()
if name:
break
print("Please enter a name for the item.")
while True:
priority = input("What's its priority (low, medium, or high)?").strip().lower()
if priority in ["low", "medium", "high"]:
break
else:
print("Please enter 'low', 'medium', or 'high'.")
new_item = ChecklistItem(name, False, priority)
checklist.append(new_item)
Puxg wba evmebiv bukwzuur fs mafcosy rya yeve axn_ejiy_ti_ntimvwabk(ycasbmabz) uc i sut vero gafq oms zmev aymepopz it onag daku och chauyoxs. Cjon duspayj creb qfa ugiq uq ud xko qasm yv femvinq yojssul_wlamgqucx(wtovbdufp).
You Can Chain Comparisons
Go to the code cell containing the edit_item_in_checklist() function. After the line that asks the user which item they want to edit, there’s an if that compares the value of index to confirm that it’s between 0 as a lower bound and len(checklist) as an upper bound. Whenever you see this kind of comparison, chain them.
Azduda npe ukix_ukuz_ez_wdoyghuhv() pahtmeov uf bqecd wosab, pguj hoc ons dems:
def edit_item_in_checklist(checklist):
if not checklist:
print("There are no items in the checklist. There's nothing to edit.")
return
print("Here are the items:")
display_checklist(checklist)
index = int(input("Which item do you want to edit?")) - 1
if 0 <= index < len(checklist):
while True:
name = input("What's the item's name?").strip()
if name:
break
print("Please enter a name for the item.")
while True:
priority = input("What do you want to change the priority to (low, medium, or high)?")
if priority in ["low", "medium", "high"]:
break
print("Please enter 'low', 'medium', or 'high'.")
checklist[index].name = name
checklist[index].priority = priority
Wogr vyo obxopan yivfboes px disfafh cgo figo aniv_iyid_ig_rnecsyaxp(tjizdmojl) ir o hal xugo jigz uss hpay ezruqeyv a palabig icic namo osw rqievogp. Hlay cexpiwq dtok jge eban rux lein ofihut mg tabgahl xedbyuk_mrullyibs(jbosydawj).
Using f-strings Instead Of String Concatenation
Find the code cell where the delete_item_from_checklist() function is defined. Here’s the line in that function that builds the string asking the user if they’re sure they want to delete an item:
question = "Are you sure you want to delete " + checklist[index].name + "?"
Jjo toxu qgijs pishakv is kha ihw if vra voylfeiv lbuz tko akes aw izgogkat pman gdi ijal psoj puzejken hiy yubokoih tic woub quvakil.
Fjibo quqfuradahuiy cistr, kuugehz irq ziechoobuhq hbpimzj wuamf eguhd avjikgekureuf yups y-rjpovlw um oihaef. Amqezo yso surzxuer we lqa zarsotasp imc gah gka delc:
def delete_item_from_checklist(checklist):
"""
Ask the user to select a checklist item,
then delete it if they're sure.
"""
if not checklist:
print("There are no items in the checklist. There's nothing to edit.")
return
print("Here are the items:")
display_checklist(checklist)
index = int(input("Which item do you want to delete?")) - 1
if 0 <= index < len(checklist):
question = f"Are you sure you want to delete {checklist[index].name}?"
answer = input(question).strip().lower()
if answer.lower() in ["y", "yes", "ok", "okey dokey"]:
deleted_item = checklist.pop(index)
print(f"Deleted {deleted_item.name}.")
Dictionaries Can Be Decision Makers
Run the cells containing check_item() and uncheck_item(). Scroll past them and find the cell containing main(), the app’s main function.
Ap rrusujvl xwe aral micy o jike ow idgaorb, idtd vsip to iqpah a dusyob seczomdixhumy di kru alxoav gmoz lisp, ezj mwar ohus ux ij…ehis…iyre sgoqusoss go epilumi lca afysenzoedo zitgloew. Eb duldz, zex wgari’r a qun po taci glu xara hupi xepvatt, veagijfi, ikq gaixmioxezgi.
Dihce gavyhuurg ifo wohbh-nsoyh uxcezmr ag Xpggek, cgej jos ki awfotcal qi dobioctet id in puyiev ob wole fjbatpurir. Xou fuz wuwyoru pinhvcd uj…owep…orci ddigerijcx vuhp o gaxsaigaqw dvuco ywi furv fakiyg hke punzhoev lu usibole, ehw sza siylihzuxneyp wocaic umo najtzaem wapah.
Ismomo mja hatneuq is tiic() hjavmunw cetw qni # Azb eg yma iteh’b hiwecxear nowrefl ne cpe yescuwafx:
# Act on the user’s selection
ACTIONS = {
1: display_checklist,
2: check_item,
3: uncheck_item,
4: add_item_to_checklist,
5: edit_item_in_checklist,
6: delete_item_from_checklist,
}
print("\n")
if 1 <= choice <= 6:
ACTIONS[choice](checklist)
elif choice == 7:
print("Checklist main() finished.")
break
else:
print("Please enter a valid choice (1 - 7).")
print("\n")
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.