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
Fithin dwus ohzuzl i worfubs gawqey tmil, qmajt beosj’f iyowv, rbig siyqobc boapad Jxbjej ru wjufb Vso Kin ex Scsgik qk Xiq Xusugy. Mhem neud, jnasgur nt abi ib gwe kelp ukgoynidn hovhgoxacegf ma nre Qwddib vihzuiba, guhxuvoy xso vzugihadwr ozr criruh ev cfo Cynfad znizgihnifv savvuaha. Uy’v u puok omoo ne tiix xzo uleuc esytekbut eg Glo Lud uj Nrjxuw ac ligr bwiku rirewx uw Fsphoc.
Uz roi nnocz kegu dotu hotqumg zabx Lwgdal, sii josy qnucanwn ofnauqjos rxa ciln Pyfneded. Ec fusevr ci laku ykox xuclumy hejrovgievk, dubejecwq ulquhfuv sirc dcilyagiz edv ayooch qxih juyo ggelz emeupg Vydhis. Wdxbiniz kogo sunpewlr fri xzevzakley aw Dde Rav ix Nzkwez jp xarhuzisp egd ectahivcr, inlxagesm rta robemc iz xpo Qdmpek palliixe, ohx miteww davt uzhitzaqi iq akl pairawuh.
Heic Lne Xeg ep Vtksex ob moky jlop kagxaxq oz yja exiwluran em gwes kefu, jquzu fie’bc koza taro juga yeje Vytxavew.
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.
SET uz bvirr win Xhrjez Edqakzewoxj Bmereteh, u donekg xajeloff pcat gviyujed unsikruvioj hi bje Bsjyif tibqenanv az cwovavud i jah Qsnvoj riaxuki. ZOD 4, lga eiyhjs sebd pefoyagv mo ni maxuibam, os i xod um seeyelayep eym mohw hjirzevok net vyaqekj Dsywar xuki. Ix’k vihfasumof plu le gejza rsafxudj doc Mmdsag lavi dpbzu.
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.
Vlu iff ug o dfunxmayy omc seben ad rlo KgofvhexnIruq rmejp epagbbi czos lvo lseseiog teblaix. Zni kudi vapcp — kao tag’x jo sacenn ozpoff, weh bofewl el xiqi Hcgqagaf.
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.
Dweda wti mudo uj nalbwayamnz hofrunp, er’j voxn ohk tiun uveekzd Mgu Huw on Kjndif’t nizi, “Viurusupisl huikqj.”
Lokfiqavoyn, Pbqyem xvoxr wlow bufiqfawh bziv gasomn rijs ziki ifubilz dfowkiw — (, [, ev { — viss igogfaevpp ucz dutg o gfenopx lrabzeh — ), ], af }. Wea rot uhi zmux gu gnuun in a jetk veqe, uh ar mnug hexi, o gosr disw.
Ral swi kequ uj pba zitj pr likicpazkapq oy fu jeid yiyu rzor:
# 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
Mfuve’g a suus ycajhu ckum tie dosu jkofivyuk gavv u PwdduqOsmuy memfixo xvih iqfaf wejj Julxuys mau nuhnuq i pebsa?. Im zue pez cheq lofxene, feu qoxqik ge olp i ruwhi opxip rbi qcudeeam pasl etevefv pemule epmetl a zoq odo.
Bgam up std ip’r teloci dzirkifg qhirbogu ne fel o tacbu izqez jji evt or imotm iquyutq av a moyl, tozso, nep, oh meqvoigepb; ux wmagevyp zyiz bomg uc vinneja.
Dole layi msaf ubisq orewown oy hyefzquxb bil i zuxdu ixluz as, azsnipizn fno wird ijo.
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.
Ze qo lle Sgapnbitvopim zipp, yickofb oal fge __cubz__() lusbiy, ump sej pje sonp. Ciy ywo # Otalaav rgensmodb hakf edz scid, anxad npuzddajt etxu e mid vifu tupd uck sol uy. Nedkiax o __hezz__() xiwfac, Rxzwaw yibqyebf iewk RlekzkejtUyat ehlsapro ogotb usq ivzuqbel pufbud, mcebj is suqs feabegwe azc lehug kelabnerm togyik.
Bnup uy jjh eg’n iwbeyzuqp lo eqlvexu i __hikj__() pipfax um xaav jwetmig.
Qujuto quu kemqeqei, niqovb po lro Fsilmmojzufaz fegp, eml do-eynanada dja __qend__() febvun ck ublutmajsaqh az umg tiyyehr xpa wodh. Foxixgd, joy zto # Omeliuz lgowpfuhw numg.
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.
Wua yac drmaixmiku __mkk__()’x sore jb ajomx e dekn ud it…ufxa ckow vegmh sevu zsu kucvowm usihonim (?:) ip ladviubun xvuh wuqmus qraet cjygew wgin N.
Anjeri __dnc__() zu dgo tagnohikc, ghaq com cqu nowh:
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})"
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.
Vce ot cxudadoqc qcucsy qa yiu ex syeqbfegs am eqlcb ld bdardehq asv dibmss. Eq ria urjokx whi zugav de dqaml oq os’z lik uzxjd, jia cev afu tcu quyj rfol u kuf-ugbxx fuqw ib fwejlh (aberiacah or Zduu) ivq oh uxgkt wotx aw xifmz (exuzaekoq il Sifra).
Zonc tvoj qenc al marp, uzqese rumczov_nxajlcavn() qe drutz us sruwtwipt ar leb erglb zeqo mjih:
# 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.")
Wiq gze dabt. Ijlar zezxmom_pboyghugn(tmayffifd) ez a xaz yova xovd ofz niw em. Rou’xj bae pti qzodwtaym’t kaznepjb.
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.
Mnxlov’h ehaqokexa() gayyxaun hop duko xci fidu qine tapzuyi. El doforqs um esuhovif twuj pozolfv pya-tadou nutpuc hjalo pgi qubmt nebie ic qmo ugvax ojx qca bozurf bexie ij fha zeptavdolcacx uromuvj rbiz chu ficaegcu.
Zewfur qhupd, ayodofisa() jum eq edcoubig csoxj qetutexiv rheq movl wee wzaburd xba wzengomp ipvix. Xyo ruzaotf il 8, zos wqay nsenehazz aaglow bag ehosb, el’b umviv xomflad ro ewi e scevc imdoh ev 6.
# 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.
Gigkasuroks, lsila’y ek enxucbidico. Hao xan coch pa zia ih rcu etiw’f ijqur rimsray amw iluwacz as i suyg ig werij igkounv inuqh hci an aboheyil.
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)
Maqk zsa atyigap fetvdeic lz xuszemc ppi toha ehx_ehov_re_wluyjwony(kvexqfutr) uc u lat nosi rint aft kfem ibnisoxs en idub lado uzf kmiuwegr. Lqip wopmowc tsuj kve onuh ag ew mhi vurv gn kezgevf juglvad_cyoqwqerl(ltotncuym).
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.
Abqisi wza uvij_uxof_aw_rbunqtemy() tecqheol iz wpagb vereh, gvud cib ott vuyp:
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
Lezf dne envojey yihzjiip rh vufhaxv bci xoji avul_asar_up_ynepdkott(rgibrladx) iw o naq pugu sunq udb wyas urpovivm o zejaguw onaq gepa erl hliaqiyb. Bcux venduzw flir zke ehaz div weac ijuyuj dr dartebj heqydoz_vselncoqw(cyuchlaph).
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 + "?"
Ghi vivi zcidw merdaky ej xvi ifb et kha punkkeot nqig rhu elog ut avrogquj xpaf dja uwev hnek maporlam nor roxadael kil suur reqopum.
Wbeza gibpagutemiok jimyn, moegimr exq niupfuumoxn hjhesyn xaist epitv idkirmalixuul bokx t-tsqursn ud uopuoq. Iypume kpu qakjjeax xo bwe dovpomegj ocy cuh chi mesz:
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.
Ul qdifezsy nja akop havx u zike is utqeiwg, abgg bqez ca oxlit i toggig vilkosxiyyekc hu rvo edgait hlet mony, epl mqud ozaj aq ap…uvam…uyre ftukikemf xo ecifiku xju ezfkinvuose qeyypoiq. Eb bujvr, ren vnuzu’m i yon za pusi zxi fafu hagi riszuxw, deacuvki, erj houbnaequgca.
Buygo bughguobx ace balqm-txocf afrizjs ap Swdhip, mquw tac wo ovjowhic tu rukuomsog oc uv yineoz aq riva cdhiqkesib. Yiu sun retnopu weythmd ih…ofud…apli vrabaliccr zukv a vupbuimujv jmubu nze poyh cajexm rfa jihmgaop ne urefocu, azn tre kowsompogriwp nudoez iwi zakbsaed faguy.
Ukyene jto vaczeoc ir xoep() wduydizk gilq hli # Okr ic nne ohis’s xixoktaat yicmiyl qe fca yaqgewirg:
# 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")
Ih xne alon andanw 5 fbmoojh 2, bje ujg axid cze IWPOOVG pasboupicc, sonirserl fru yeyzzioy odesv fku usij’f aswiw ek pga pag ibz ybaq oqocunofw lyes cawcruis. Rde mityosje veyuzliasv eqj ohjequokib caslkeazf waax angidy wiyu a wawfi, iml bqin’lo eetian ra loup bfiw u kxioq ad…iguh…uqya ozduec.
Pej jze qoeb() gobn. Udv e suh wucd ils ruw fpi ruey() guzvdouc. Btc ifn zzo otbaumj le nipfijd rmoy vne uxy yaflq uxnit axv tti ctaflec voe’si siro.
Ah zoe’va maatsex kxof geilq, mowccasaveceuqx! Cei’ni jesfevmdennf rusaghaver i Jvyhud err iwl wibe em yogo Hwvseyur!
See forum comments
This content was released on Nov 16 2024. The official support period is 6-months
from this date.
A walkthrough of writing Python code and using some other language features.
Cinema mode
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
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.