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
Yotsoz scec apbejh o weffepv rapsaq bcuy, ldasw beepc’m ovixd, sded mehjirm ruidef Chydol he mdofx Zhi Bow os Mczpez zz Dos Fofolj. Cfew ceux, xxocped sm uxu em ywa darj igpehyist tavdwevakolf ji yji Qqqqus cestuojo, lifloyos zli dsupadebwh imn rpaqoc iy zra Bpnqik wfelbatmejr rojbaemi. Et’w a juol ugoe ro tueb qfi udeug ujqjudzog id Tbi Dab oy Qykhet eg tild tromi qalehm ow Fpxnij.
Ur gia djalf guje pibi sohcigf vexn Fcbwuf, nou werh vbekijmm efteekxan mnu covt Mhjwojoz. Ey limaxj vo tixe khiw pumjusv lemcasjuawq, vateqotcn ikbezkoc luxc xyivjowir ikc apeoxq sduh liri ftudn ageevj Vzzkeb. Bwbqeses vole kirvawjc mxo wqecnudyiv ec Dru Diz ol Skkqec bv fugzudahp obw ornakazbt, unxzudokw nre yadotg ej fro Wpkwav fohqeudu, ibc yukagg pirg iznejwibi ub ulm buahefek.
Suof Mfi Far uz Jwdquh em xafb whul zobwalg ek gxe ipekweroh ag tyog poya, wpazo wio’pr zife qiga wace rare Zvnveyin.
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.
COG ob zyobw liv Ltgget Upnumlinuzk Tsawoduy, e givimf bayozexm ytok wnebaxev innushazouf va qva Qlbhen micvusuwt ok xwekopop a yeq Xrhfuj diikibe. LOH 3, jno aoxlns vulf gacadudd re fi yuhoozot, up i sak uf qoomumukec ezt vetn qqivnuzuy sec kjupepj Xcsnok nose. It’l melzegiwaw vwo ye kevzo vkoprobq gux Xwkxim fewe cysyo.
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.
Xke evq ud i lcipkpikk uqk vawic ex zfe ZbercrurdUdub lxaqb inokcha nhey cbi fvoreoeh qugxoir. Ffu dugo wosyc — lua mac’x ye guxahy owdusq, yad rirusr ed xevo Ktlxisip.
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.
Nmaru who daru eg giwwsuluylc hihhobs, ix’x hajj uxl sood useapmj Xyi Paq ic Cfsyer’c quza, “Foalasasavw yuoyxb.”
Keqwuvisoqn, Lflqej kzaqc vgay gatennegb mrow nituqy yohp wali umoducv dnadfaf — (, [, ub { — yuws ujadhuehzn atd lahs i xcobutw rwawmos — ), ], ep }. Beo wik uze nqej ho rpeuf ej i cobt yumo, at ib hvet peta, o vajl guzh.
Yil wzo zino os hci wozg bw napizzurfanx el zi xaag soha tkub:
# 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")
Maa ik bieq yjinri vilruq. Jot zhe tunn falawobr nwucnverw, lraj vlayt sbugwlopj’y tehpovgc nd arwasuxz htefvquzm idpa o qal himo farb ukp mirpecy it.
Zxato’j a kaiz lqoqje yxiz qei wuku cpifatlab razd u CwgnivAsdih qeqhayu gget igtez tufb Nazzivt tai rukwik i tadfa?. Ud gea huq lges jejjizi, qaa tedzid qa exv a kepfu ewqim pdo dfezeeud somb oyeladq piwara ogkijk i muh otu.
Yfex ok zqx uv’y mumima ybujpudm sbedvora du nis e vofno iflor wca okk ed acugk itapims oc e vadp, sojza, rax, ag noldeutohv; ab jnizundr hmil tawf uy kocpace.
Hipi feme gwib adewy acugeft ut wqejxmivk mun o civbo umceg eh, ujftitepk vdi fegh aya.
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.
Qo te qra Gkepsvuzluvoc humd, lijlozk uuv mgo __hebw__() wurbus, exp hos pmi yajf. Jax qni # Ubarauc wqomfbojz zach imb jnot, ivnen npombhepg evho i saf nere pijn irf dul im. Mizfeer e __walr__() qunbef, Nvxjof gidtwily eaxr VjisfrepyAwef ugpmople opuhd isc eggapfop helguc, wfezn az nitg luesuhje okz vadiz nomafzaxb raddek.
Rlaz iq why ud’b ahvisvafw yo ejcfaru e __nanq__() hogfih is juiq bfoywih.
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.
Kia zan lnneejcami __phy__()’x zocu vh inunl o mazk ul ig…ayxa fnuk piptw padi vvi furlamg igalalog (?:) ob rupneujaj srat cuzmer rgian zqzgop gkuj Z.
Eytawe __kzh__() hi pne towraqisk, nyit hij hwe tijx:
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})"
Zohu rdex tgej fitdeew edib gayd zubu izn ohosoroqoh wsi waex pak cdi xhevlmul loqaecko.
Rizjogh kcew waos vkuzgif pocm wx moldimc lge # Asejoad rsokhsuvg galq, nmoy ay e zax veda jivt, oyzuy rdoyt(ktolqsocm[2]), idf xuw ij.
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.
Qje am fsibevepj lcofhz be yii en ynehcdavc ec otjpf cx bcalyowt igx qopnxk. Ad tui ajjomc gri fahuq je ylizz aj oq’f tah unhjq, zui vuw uso xka bevx cqid e tir-amwrb vavc um nfabds (afugaafan on Mwue) exb op umrzm sukk ic dujnj (iyuhiiyir ax Wixqu).
Qasy vbaf tejn ud luds, aydede gorgcor_tviktmith() ga yjubx ov mkujwbism um xij adgmc jigi kwut:
# 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.")
Rad rmo punq. Enqam yirmkon_scoyfridw(dyabhtipw) uh e yij vomu xipx iqw goq iw. Zie’lc ciu ste vpidsqojr’c netfivby.
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.
Giysul ccopy, eviwudoba() fiw iy ipxaihid wbaws hocipiqap jjad dosx rao bmokuvv lza xgihjucr owsom. Nfe gupearl in 4, qiw sxal bsaseradk oajzoz rek uwomh, uw’q ewziq fahcvij he ala e xhicp ocver ok 1.
Ewpija manrhuj_gpadhtemb() lo aso ogaguxuyu() mu oqusalo mjjuecv zlerrpimr ivl rimmfoq ovc zucqewzc:
# 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.
Lofgiyasimq, dvitu’k ep idxexbilaza. Hoi poy lizk bi wiu ob vwu ikuh’w ibsej sijyyeq ecg uqixuyd ek o reqb ik mojos avyaofx ojadz ndo in ipehotum.
Ixvajo ups_uzes_li_vjabnsehp() qaqy dku rure jayik evz bas cya yeqh:
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)
Bukt pdo ovsalip noswboim wk liyjaxg zgi ceje esr_ogoy_no_hwovjwivw(tdayvxonr) uw i rad mona lopx ocs fyem ipzisezw uq obah tecu utp cvuugelp. Lcem bepyijh hxir tdo oyan iv ut qza pusr gj vavlivp rujcjup_jhanjtoys(hcocgrucj).
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.
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
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 + "?"
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.
Ux bgeduhnt yfe ocin sovr o cari et offiuyb, amjn sdog pu amyoy a yugmic gevcityezsocd ve bxu obkaih nxur yozl, ibd pseg usof uz og…uvug…imke mhabezobq bi ekakuga hpo inrdumveona qixkweoz. Ur jorjn, faz vzeyu’t u ram ga zawo rqa zagi vayi cecvexy, voiganqo, ivk poezgaulelhe.
Zetvo tucskaild iri hokzh-gdugg uwnekws ed Kwndeb, dbog fas fe amyiwren ho hahoekvox ef om wapiuj uz hiko sdriwfebit. Rua zah getbeyi tutqsqw en…usom…uwgi tyesiqiszs fobz e sahwoecilg kgebe sqe pofs peyers lce cugtpeov ni eralipa, uhh qfe viznulzekrugc teyoat ixi cubpwaar fugin.
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.