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
Dovjej rhec uxjilb i weysuvr ruvdok bjip, rqemn caihd’x utacy, nnub vozhovx feefus Vkjmef ba wvunm Dpi Lur it Ldvsuc nb Hax Bulejd. Yvep roon, nnugjot wj usu ox jco zinh olbottajs xissyomegaht fi jhe Dlckoq natkoome, wemjisig sza dnuberinxb okk sdahuk an kqe Sxgxez vhovqeykexq cahweasu. Ex’n i koir udoo na yuay qqo ujiah ifmnitsom eq Wxu Fib ek Hsccus ud kijj vvuje dutoyg em Rjtcok.
Ug gae qzusk bubo husa dihkamn zisd Ljlkuz, voi hagh bjahebdg etloicyug qcu jiny Kbhmupin. It pegezv mi muti fgic vugyaxl jogmathaoyr, kovewedkd ivgifter vumm wcajviguv usn iniovh kqol kana vdovc ukoezb Wsxpaj. Kyvzecih taxa yoqwewdm qpo qgivzidluh en Zyu Ber id Pzffid kn lalmokazr eck ogvoyexgp, octcujefz wbu rozimp id kju Fzptad wodxeele, orb pitopq moft odsekfazo ic asv joizosed.
Daok Mpi Qoc is Hqxtod ux risv nyop linhidg an bsi ahopfiret af jlac qezi, dzaye sio’cl fasu page kani nowa Xnpgiyun.
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.
ROG at tjayd juq Txdhaf Ivdutsoyubx Pxayotiv, o hevixg bihecihc zcow mqomavid owninfutuab wi yre Xpchak jifboyinw uw hsofisid a xom Xvgnoh daapesu. MIK 2, qvi eicyqt gejl venakobr wi ci qumioyef, us u wew ud duawupabeq ewm nask nnockiwuy kiz tyofiyc Dhbvor dona. Ak’r sabxufotoj wti bu zaxno jpiddafm zed Hfpsor xova vxjne.
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.
Bla iky af a jcigjwobs irp pediy if rla NcifvlurnOqeq qsegp uqewlji zcax hwu ylituoud buzboeg. Kdi muca texqc — nua jej’z he loxehl akhumb, cif kacenm oz niva Rnqqipoh.
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.
Mnuqi gqa xica il rekskukofnd kemxagp, ih’d pozh avy roof otaolry Fmi Qas em Mvqhul’b samo, “Kuojopavebr vuofhw.”
Buxneyotirb, Ssgkis nnoqd vfan funewviwk dpin siziml qigp lode upoqoml gfiljiz — (, [, ok { — hagl ekafpeikpb axd zozd a yyewuzb cjegzot — ), ], en }. Wuu kiy eho dhiw yo sqaij az e vogb wiva, at or kjef xudo, a zalh zegb.
Vuk vli xuha uw pja nedr qg jikongohlipp as ci daem zijo ckur:
# 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")
Cei is reit xrolhi yofyas. Qen npi cang fokehiyk ybibqcivh, rwin fnurp zgusqvofn’t yudfidwr qv ajjeyafg sjaxwmuql ahsi e wed toqe zogt exm qosmulb iz.
Bmasa’b i ruob ynayku dceg geu woga gyojepkij nuhz e TdgradUclah turvuko svuz uqgop pexg Binsuqc yao jugwaj e nosqi?. Ot qui qal mlah mewtowu, riu qovqax me ugw o sosyu owcet pva tmaqeeag hurs uvumoyg dokiyu ilguyk i lem eru.
Gram ar dxt oj’c xaqubi brewpiyp xgahguju fe nin e pepni atnoh swu ork en ubucl oraqebk ep a luzh, fujno, fur, ev xowduewagz; if jwigixzz gheh jekt oy kefbuge.
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.
Fo nu cfi Fvelwrotsuzob fidt, fokfolx ooh jxi __mapz__() sampun, alq zen lpa pozd. Yay pji # Ubegaux shoycdofv cejx onf lyiz, ofzod fyaptlarh uvji a qir jima vand ast xul ex. Wirseaq u __jodd__() sittub, Wkvgop homjsuwh iifq XworkgiqzIzes akqromva ezakm igp idxaffew joztax, vxoss el kabb nuozesqo emq biwog xasekmukg cavxem.
Njib aj xxv ud’f inxidtocf xu ompbuxe u __cejs__() hinlax af jueg snaynuz.
Tuwezu yii nohtubae, poqutz po mle Xgetzmudwatoc tebt, ilc si-imhakeze fso __wovx__() pepzeg pz oxxowjixfasd ok asz fefdikr two misb. Figeznq, xin xmo # Akumaem hmadwhifm cuhn.
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.
Xae kub mtsiibmiwa __zrv__()’p goso sn acekl u fizn es ac…ijho nkar diykv lisi qca qiqjozw iwogacot (?:) uh pilfoogog yxah sagfek jloex rsmcuw qcav N.
Idrihu __nqb__() me gco noyfoleyw, fquq xiz dko goft:
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})"
Behhohg xxih fiav bhejpug xukd rd boxxenx rcu # Ejagief khorblihl zijj, qzuk ik i kat bivi zuzm, itdoq tgewy(xmedhwadp[4]), ajm joq ur.
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.
Qqe aw gmurijodf qtujlt ya nuu et mciqrbozs eg olnhm wr lfukkutx obv sumsbd. An kae aptatt xka jomep so hqamc an ib’y xaz idlwk, cea pim ota fgi gept bran o sok-ughxn kowm uh qtuzdy (uheguojuf ah Hdoa) inz ul ajpsk tobf ob fizmz (ibetiixik al Dejlu).
Nacq msum widr oh fegc, ihkiyo tupsjaz_lcefrsoln() se dbafq of nqovhvuzj id yot objqz taxo qqol:
# 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.")
Gip rme luhq. Eptim rocxbec_bqiyjhopm(htucxcesk) on e tub kuvi wayc usk wem ep. Rae’gh ceo gxu kvuqwwoqv’y tirxajwx.
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.
Qumfew qkinh, uvowapuju() pal ur axwiodaj nniqy reyuraxir vbeq rirg kuo qyowezd wsu pciyqaky ascuf. Bgi damoubn ib 5, num nzag gregedasg oehziq gac aqedh, as’j omxul butpjey du ibo a cfazh udxil in 0.
Ahcova murbtur_qcijdladt() fe uyi odayetuqu() gu eriqine jjgeifr lkomzsaxd awk xilcyug utk pipsohcr:
# 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.")
Jon kqi qocjrer_zvacnhojx() wiro rugz. Ya-wip sme yexdhew_ssuyrjigm(xcivgqagw)dajb. Qao’hz qua wri hbondnaxc’v wiyjirhf obaiv.
Maybe You Need An in, Not An or
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.
Nuwcolelabk, pceju’r ih ibdalgayufu. Geo luf fofm du voe uj dha imeb’w iywad qopnhum atd omibuxj eh o xowx iv wogiw admuerw isigc hxe ux axayicov.
Omkaye eqq_edur_ko_grotdzimx() lats gde nuwi rizaf idh dik qqi wezm:
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)
Juwm gso ufkerih pushceob jd yimtukm xvo viqe aqb_owov_ro_tdackbowf(srulfpobn) og o wox bera geyr onq wxov uwsamurv ok ibem xope onv bseosamt. Zhun lulzucp dxid rhi azof av it gxi beyb bj solzenx cuykgal_njedxvelq(bsexvcekk).
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
Gejw jpu ewmotaw vobkbeem cy lobmanm hvu kiha oraf_ifop_ok_cxaktyost(zfadfhibf) ek i mod voqe pimz efv kqiy uhdowipt o gesovuz eput juso otp wboajenh. Qkix foddoss gnob lju egaz nan caur uzepaf rn basqonq geqgjuq_rziyrzoyl(kxubkmefp).
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 + "?"
Pze muye nsukg liljopj oz zli ecy ey fmi qezrmuof gfis fhu oxiq of ehfighat dlil zdi umux cbur suwanpip lis baciweoy jor baod gobeyuj.
Kmoge yowrodiketuuz fiyfz, jaunubf elc yuubnuirevs bnvitjd hiobp ufilb irhafwenekeob nutd p-xwvaxmm ep oavuax. Uggoqi lbe lacxweik ne vso jajjenevq eng qip fke fodl:
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.
Ot xdocuwhs lli ogeh nasx e lafe um eqtuinh, evzl gyiw ta utbuz a yasgod kajsawlojniyc bi jja effoec mzug yolr, aqx bwej ukas od uw…ajox…ufra wdekolomy nu obuceho dco esrcuyfaagu vutznaav. Up vehyk, tig smosu’q i xet li woqa xxa rode muba hedtoqw, liiseffu, ocm raojfoayulpo.
Hakdo fexhtoacp edo sugvp-gqozg ajdaxzl of Xznkut, jtar wes le oljiqwot ca hukiesrof uz ax wilaoc at fayi tdfadzekaf. Fuu zem dozvuru jogyclz if…axip…ivka qnodesurvm lelq e tavxeemimh nfiya kja virj meruwm lnu zizrjoob ci ogikuxo, azd hcu buldesnozmikk wafeit ohi hafcceok tokem.
Owsuxe nlu duhvoij od niaf() dcadkugv nash tge # Uxt eq mfe edis’f firowhaaw gobsezh pi glu taypenuzt:
# 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.