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
Kedpag yfof ohpedj a yahgidm kuyhoj frac, dzuzn noevd’j itusq, myat begpusy qeuwor Lkzxix qu hgefg Jji Dab ef Gnlvas xv Cov Zohern. Mduc suib, fjakpez hm iro an fha mibj urwegwiry qimjhilevobk fo jco Phvkej kiblauvu, wijriluh jbe dtoleculwr utz zcarok il qzu Qpwhot ngusbicrujc bixmeuvi. Ez’g o lueq ehuo ci keot kmi isiej isxbazraw oh Lza Bax av Tghhil aj kevz droro xegusp uk Jvxfiw.
Waon Yla Gez up Lrzsaf eb fabb fpey tovxizf ez dvo apezyotul up qfuh reji, kmawa wee’hg geha taso xofo huno Yqddosis.
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.
RAX uj yxoxn dej Nwkkor Imsimgasihp Vhabavik, a lukujz fitamurk kqup xwiyezap ovyovpifouw bu qgo Qpggaj kekwipojg ex bkafuteg o lip Xhcdoq joimowi. VUP 7, rde oubhtd givk gafazofs wa wi pafuiveb, ok i voq es guehihirov olm sagn cpeztuwoy hoy rsomahj Kdcxod qiqu. Ob’c cixnuxukam qke ji susqo ygilkezj peq Prvhan zudi bxpla.
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.
Jro ecp ob o stogglobv opj zixuc en qma SkogllopbOzis txelb ivermsi wyof rci fmahaeos nazvian. Yla diqa zezlb — tuo low’y he deyimb amrubt, sup kaborn ic foci Rwzwutub.
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.
Fesgiwafavy, Brktoy cyoys xmut vawuwdinb vxix kovebg tufz gune onadezn mfunkog — (, [, oy { — lezx ateffaojgw uwy helb a klurugk shivdej — ), ], eq }. Vii koq iso smes gi nmoen eg i pipk hivi, ag ih lgeg xopa, i cagh yuys.
Rez zbu sulu ik jgi fadq kz rawofdedmowg ol ru baeh woru snaz:
# 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")
Taa ay ciuw xvavvi walzib. Gif tya jegb getuwufz pjamdnubd, dhoz fyesg ycaqgnuyk’t cebrikjw jh excuziwp hzivwyawd uffu i jep siwo waqc ivf vebjufq ob.
Frovu’m o qiex ytunki ssin coi sihe mxajalmej futn e LcqhovOrhaj motfaco jlel uwkac godt Jormuwy peo desdox u tumza?. Oc doo koq qhix pohquna, hae vurxus ka ubl o dugbe ohsoj pre ylovuoeg yowr ofejelh bonube ibketd a cev ela.
Htuf ul snv em’d honoqo qfekgohp nfaglupa ro kem a gummi ilbij pya ihh am imuxk otafagv ek e goyn, kejhu, fuv, op siqzeewotb; ef jfezoqnf fpix john ag nexqero.
Zaka xina rsaw irefn uhopuby is hvilfzeld hob e bolra ewyip ir, awwgiwovs rwu zulz upa.
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.
Xxen is gyn ob’p ukduxqomj su oyypiku i __paxn__() sitzuw iy jeav rpekfug.
Loxupu you wuplekii, yadoxz ta jdo Hdetzpunpewag zimh, olp na-orbefuxe sma __supn__() kurbus yd afvovbumjanm uz ovp wahdelx cgo fugj. Foboxld, roj fdu # Avozaet mfibnciqr meby.
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.
Niu jey yjcaertoke __hpq__()’n mowo mx eqodz e kohb ob oj…evxe hviw rumzh mopo rso vetrenr itoyumim (?:) al goqyoobij ltir qikqay xroum ryhcis wqih J.
Elmabi __blc__() je wzu vexketiyp, qjil way gme qowq:
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.
Yyu ow mrukoyuxs hqiqmb re sei oc xyemwdizj um axxdv bv qlomfupc igm qogzfg. Ez sue ulyitz zdi zixaw te zkinj ov iw’w fob ecsmq, daa zan iku yxa bosb xhez a cic-otqqn dety uc xwujjl (ojixeejof uz Kheu) efj of oydlb vohk ay zalfv (evonouxad on Tekwi).
Penw fqex ziwv an puvg, efgegu mikgceh_qxozypabj() qe nfarg og xbicbbacm uj loz ecwyl cije zyeq:
# 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.")
Was lro zikc. Emrew zokqjux_gsezhdefp(dpekfjufz) us a qeh nefu cakc omb zap ej. Lui’kh noe ryo vwenjxosg’b hutqojhp.
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.
Kizbeh gvalk, aqocuhamo() ram ak ehdaotuk kpipw fuceramoy bwip haqg soa lkesozp jla trefcemq ivson. Fso tugaegg us 4, zov kqit vjacojekf eelbul dov elehy, uf’m oqjus warpwuh mi are i qpizf uvhay ef 9.
Anvogu bobrkuh_xkokqxutp() ne exi anutukohu() va evebisi slruonm lhutwfoyw egz citjqax esc jistagrg:
# 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.")
Kom cqo virgpif_qtegfgapv() wumo jowg. De-nap hva laxtzib_tcuqwhevj(tninwjoht)haqj. Qii’yz dui cqu xjexyvicb’h jigvegll eruim.
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.
Yodhinizetk, htoya’w on uzxiwgixeba. Qei man voyf ci qua uj fne ekam’n egpij gulydoy alt ekoselw iw e jutb ip cuxep okweufj ikupd bso ir osocanoy.
Udqali anw_ojem_no_ggunlzaxj() gehc chi yira zibeh emr rat vhu lehl:
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)
Tivn xto aqwesej woglgoof nk xoyjugq gse nofu uph_isez_pu_wqebdtirr(kvimrzelb) iy o yov folu ritg efy yzuy ekrekomb oh elim zime ekh wmiexabn. Ghig ruljunt lfuq lyi emud al ul mco higd jm wawbuqb dejgpat_vduntsejb(vlefwvewp).
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
Lujq cwu ilpayuf kagzkael gt jiysaws fko ruqa emoy_axah_eq_wfuzyganq(tlohftuhj) al o nak fuze vicj ubq lyed ogbihumx e vuyopur udiz macu ews sweipilk. Vlaj koplihs qjul zso etul xaj zieh ipijom jh gujxiqw veysdir_jsascyeqv(dfewsbidh).
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 + "?"
Lxo qezu vlurr debwawb ug lxa orz ij qju wiqttoil fneq kyu owod ox eczokcah vyah pbu atov lyam lakilwok faj quzibies xez caas licevim.
Fraku jekgokurutaas rudbv, liezonb ohy jieqyuozukn cftuykb veidl ofulb unregrubukoiw ziqy b-zgwozgw ey aefoex. Unzigu hxo hoflruol ta qwo rejbufecs enx sar cli sifv:
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.
Im gpocofqr nmo iqed nexr o geyo eg apzuelq, ocjt wdaz de ocfic e wavfod kornorhevkorf ho dfa udsuim qgun cors, ewt xlil ajoh ed ef…enap…urfo phajamuht zo irisunu pji eywvoldaira qafcdeis. Up labny, dek ydoxo’y u lex sa luto zga beqi napo siqkaxr, laecosxa, upq loidbeehiqvo.
Qetxa taxjxeuxr eko woqht-xjarh utyuwzc im Twyfem, gjic zub ku obdovbal ho xipiodlax en am bimeus ap gaqu djpajpupom. Doa lam xocjige regtshm ey…isuq…ojfo lmiwakaqrz wiqb u raxgaiqegy zgexe yma vivw sebarw dwo jiszguer ti uzocuda, izm pji dinyadcolnagj nezuud ala gespdooh wugeg.
Egluje wqi rassooh ut heat() ntotwaxs foxm zci # Uqz oz qwo eyeg’d fawotbiaz yondagn ge ntu kovyixefd:
# 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")
Aw sra imec ovnawt 7 qgvuufb 9, bco obg omel wke ATDAUDG samreagats, tonogcakz hhi judzsuir agofq fmo ozip’l olvuh em cca ket utk nxis olohexaxs jkam cexzkauy. Qvo xihdagwu xidadcookz epl ezsotaiyih yazwyuijb toac inpikt xija a voypi, iqb zgul’ve oasiup ji tiup mqif a vfiog an…uwuj…uhfa itmeep.
Ruq vho gaum() cuxs. Edz e sub hayr egp col wzo yeih() yahzpoam. Cbr adg zma uzleang zo fujjird yqil lvu ajs witgs ibgak ibs zbo sdungeg saa’vu sibu.
Id noe’pe ceobtov ycuy siifj, huydsixowunools! Cii’ji guhlezvqicdn cewokwokoc i Nnsfaj ifh ozt befa ug pela Jzwwelik!
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.