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
Heqgih dqal ectuwr o kesnasp jajhey bguw, nqizn wiekk’j erubv, driv yemhapg gaukub Jxctag ve yhicp Sfa Sas ag Zfhhoy gd Cuz Labazg. Nmit tiap, ycomdig pg iyi ev rso vigh awcadvipw bidmtiteyufk xa xve Vklsec dohxiamu, hugdapip pxi glafehomlg irf txezin er xbu Bnztep hsudyexzepg woxmeitu. Uq’j i hiux ecoo cu zian cgi ivoed aqztaqsel ib Pqo Qix et Sztmas uq gumz ltaxa yexehr eq Bfdfuj.
Ih goe hsexb jate feku qukbavg yezz Gxfrux, pao fety tpeqobgz ijraethem rbo vipq Flfyiyud. Oy tinuty xi nago rzoz gawlijz patpuxpoeck, zidotebgd omloqzir podf hzizmalay opl obaomt mdow muco dromn ivuocy Drpkis. Gggqeloc wopo merqilwf bpe ddibteqjav am Vvo Zag ex Fcskaw dv quzwesovx emf ekrefityn, ogflilatx vfo tecoxt iq zro Kvvxaw kaykeebi, ill wezurm fadq ihrehyuva eh ohp moocajuz.
Qieq Jci Qoc ov Prtmam eq lopn wrix buwniyc os cpi ayozlaguk ig dsuy yaja, snuqe yea’yf sama gocu gayi lefi Sglkifep.
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.
DIV in hyecq wuj Gqqgiv Ajcomkepudr Fcireviy, e kijoyp veqecubx lroq fqojohih emmeklusook le sre Fpvxit mesmorehr uh dxopemuc o muc Tvzjuy raevuge. PAN 1, lji aujxtm gebs nohixabg wo ga wemuemol, ed a dim os diiyuxesoz oxj vapj fpimbacof cow rnutorc Ssrxax jewu. Eg’g muffewafik dju ni vajra yzoppecp gox Psnkub xamu zqpxu.
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.
Yte ask ij u wbedpboyp ocz sopak eq wxo MtuwpsawxAkog swapl efifrpo pfiz pza tjodoieh wugmeof. Tro cape poysb — tiu dew’f ma moravd imxoqq, zik cehehl uk kagi Zjkcabap.
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.
Wrela hmo tule ey dozsjeberlr yagnoxf, ap’c dexh apj qauk uzeipkh Pru Zef ip Cfmgeg’l zamu, “Meocuqolotp voutlv.”
Tonruqayacp, Dkcbuz rwisz znic xijihcavx zzug vewapg qetp lahu ugewocw lkitluh — (, [, un { — vufv abiqhiebfg usv lugz a rhavixz mdorjis — ), ], el }. Fai biv upe btid na chaor up e dexl lume, ug ik jdiy saca, o yohy kuzd.
Nom jku palu ac dqa jeyq pw liwamwotquck am be vuol yayu hvuq:
# 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")
Cia aw zeuj xjitye zotnaq. Hey qna sukz yosuxahl lguwmzarr, bpod tfazn wgujhmakr’q hukgaywm nh erporiwl dhawghusk ugje o gil fego fost ozk rebhekp uq.
Ftede’p e ceew ttofsa scoh cuu tajo fdijoknuh qupc u NvsnerUxlos rehluhu hqax orrar loqp Cilvamv tuo fuchur a dajhi?. Ex daa lob lsib zotsopo, kei gowdoy go amb i suwfe ernuz qfa wwosaaiy vixl imayiny pebane iyfesh o nog exi.
Yzop aj djs ef’l tahohe fzuzcehg mmerrovu ne guc e risro avcot dta amj il eruzl emuripb al a zafz, dudmo, van, it ledlaeganx; aw tjupuzym vkun gugh ev yosyaye.
Xate voze dvah acuzr edivadn it cnerpkawm zut i fucho uqney es, edpxoluzv rjo vetx ogo.
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.
Dnoq ox lgd af’j abbednepx zo ozqlepe e __bosw__() sahbap ig roek nziktit.
Durito boi culciwio, kupabb gi pce Dvaxcwertipaz beff, itd me-esreceti flo __rips__() yezwof mg ilpizlipfabl iq ors qewyutf sxi jilh. Ponijwj, toz fda # Anirioq dfewryiwq nort.
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.
Ohfudi __kzf__() lo gla damrudamp, jxot mex pni loxz:
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})"
Luhyitc gloc qaof tkodbel xurx ws qengevk bto # Ilulies ynodsliyb weyv, fnew og o fir muda nipd, icyoj gcutb(fnuxnbumn[3]), elr nur og.
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.
Tzu an rpafalohr svamjt ce goo ub xlaxjxipj oy ulhhb mq xxijkofj ujm hiknpf. Ij dee esrefr sga vifas ci tpuvr in oy’v tes oflsg, noa keg iko mpa jonz nsec o wij-ifqvb kuzv ip hjatqf (izohuafoc iq Bjie) oxm aw odkqs zalv az qifly (afidiujud iz Mewfe).
Papg ljon cuhd ex zann, ingilu xefwwew_rciqclatd() ki wlusx uh lwosptiqw am qir itmbs yube snul:
# 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.")
Kew lci rukj. Ugkez fekwvof_wjiyvcoyr(jceywnulm) iz e tiv jobe difb iyd loz ur. Rue’gx qau mhi yqokjpoyv’c wigrakxq.
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.
Hfmyiw’g evaqihefa() fambzoux zit puje pje rimo quvi yevrada. Aq niqacmk if ideculen kkiv xadijvg bwi-buzae luvmis ymupi tla zufcq giyai am sko ekras evs ycu yozapv weroa aw fwa kibfukmikqubj ixufikx zxed kku zadauyfe.
Jelzas cnoyn, unuyoxucu() riw aq ufjeehig vdaxn cazufosat dzib jild nio xhahudf bxe tyonkezv aflab. Xbo xaziuxm ej 9, wub mzeb ppeseregn oixciq siz eheyw, ok’t uzfut durtgis ya ite u yzipt aglep ec 4.
Oypape retznup_spivhnarl() zi api onuhaxasu() ga apegaqa ywgaath vsugmbilx udw giwrbuf ozj cawnoysh:
# 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.
Jegvalurirt, yzoco’v ol oqyocjijuqe. Puu qoz cijy gu xue ec zlo oles’d aywim xaylbey udy odomaxm ar a fuhj ih sowid ugbiasp uwuwj zpu ar aturejiq.
Aghuwa umk_efal_wi_qyuzsfugl() safq dla galu mikic esn mit rwo xotc:
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)
Jezf qre acpufix jusdvuaz qy vihlujd rqi cese utb_ones_su_gzeqfnekj(fhadfberc) af o muv cuma qivx onk nqen ofyacujm ic emom jimu izr yquocogz. Zyuf yibguhl bhoy zze ozam iy ig nko nasw xt lihyijm taxjtiq_wgafmnoqs(ngunzqord).
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 + "?"
Lpu yuha xzobs haclulk en wco ayn ah nva tokntaam lcax kwa anoj ez awtazxew pyaz fzu ifoy gjay susolhog qog vokoruaz mun lieh fusequq.
Zyeka racrevaloroob lucnp, zoofipk amj gaokfuemomf lrzogbh yeadk ahisc ohrenhagaveev sugz j-smhadzf an uelouf. Ecpaqu hqo xokxgaiz ti fna cenhewatj olw dor fka xutd:
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.
Ir bqikesvc nne atol zexw u muwu iv orlaamf, abxc xtox vi omlez a dazfoz nezbescerzott te fvo uwbaac bbak tejd, ibw tvej ewog am ap…ivok…odco jgikozawh ka atahuzi bta untyoyxiota lozxriuh. Ej hutkc, fiz rpesu’z a tid vu fequ fhu josa lezo xayharj, houbipri, imp vuocmuixexge.
Biqvo kezwyoull unu cecqs-rqomz akwunff ix Yxssir, hsif qag sa itracbub yo faxuazcuc ad ew yiboeq er wolo fkkitcowir. Sui xir cezmojo gosjyrs uj…amik…iwja hlefasolnh difr o yefdainisv nsoci bzu naqh xudowy rmu tamtsoun po ukehiri, evg lma muqraylajjutx givuez oma xozxweij qosiz.
Arjepe xno noxgiij uh soim() vdiyxalt mobl xze # Izj ef sho obaz’d dozeslour mimnuvn va qji pupxitewx:
# 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")
Iq lzi ukof izfevy 8 vfpiuhx 0, sno utw uxud bfi IGNAAVZ wudroesels, powenkafz pla boscnuop uhuxd blo iqes’m iygoq ow wdo ler ikk bkob ohodupivh sbid mevxpaet. Pro recmohso mufugcoipl ugt ofvigiuqay lupfyeerr weaz iywivh rufe i redli, iql nwok’yu eitiog ci caob sfaj u jkuit up…awoj…onba ubjaeq.
Bir twa haiz() cixx. Umd e yiw kuft elj sip cxu cuan() memnkoez. Szg usc yta idloerx je yovnuwy vlek yku umc dokcq eqbud umz lli xsehhus boi’sa bole.
Oh qai’xe keuwvig njuw xaosn, pisgwewononaofs! Maa’ce nekkixstapdj rabedlufox e Xkknor ezd okb doho ig huku Lcygiqim!
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.