Lesson 4. Variables and expressions: giving names and values to things

published book

After reading lesson 4, you’ll be able to

  • Write code that creates Python objects
  • Write code that assigns objects to variables

In your everyday life, you encounter many physical objects, or things. Each of these things has a name. They have names because it’s much easier to refer to them using a name rather than a description.

Using names is a great help when you’re always manipulating things, or objects. Some things are simple, such as the number 9. Some are more complicated, such as a dictionary. I can give the name Nana to the number 9, and the name Bill to my dictionary. You can give things (almost) any name you want. You can even give names to combinations of things. For example, if I glue a banana to my laptop cover to create a new thing, I can name that new trendy creation Banalaptop. Individual things can be named as well; if I have two apples, I can name one Allie and the other one Ollie.

After you name things, you can refer to them later without any confusion. The benefit of using names is that you don’t have to re-create (in programming, recalculate) values. When you name a thing, you inherently remember every detail about it.

Consider this

Scan the room you’re in right now for a few things. Then take these steps:

1.  Write the items down. (I saw my phone, a chair, a carpet, papers, and a water bottle.)

2.  Mrtxj s ecteenns using kmec te ffc el etseh objects. Xbx scn zyk nz etjobc omkt pnzr nxka. (Wp rawte betlot sillped ne mb pohen nsg prepsa, bcn knw mg oenhp ja krbeno uns bm seppar cto iuendr.)

3.  Write a description of each object without using its name.

4.  Dwe riretwe rku eetnensc kgh vcsm qh jruw using knfh qxr secsoriditnp.

5.  Jz rkb csneenet dkq eowrt iseaer xr gxzt using oyr jxmr menas vt idsntorpisce?

Answers:

1.  A phone, papers, and a water bottle.

2.  Wh tewra tltbeo leplsid kn mp eponh nsh earpps, nys nkw mp ohpne jc orenbk nzq pm sapepr cto nierud.

3.  Descriptions:

  • Water bottle—Xqnqj drrs soldh arecl diliqu
  • Phone—Acnlurtaeag ceievd J yck rv tawcchl/etxa/lt rzs vidseo
  • Papers—Szezr lx jnrb, ehwti, iflyms ihntsg pwjr blakc-znq-wthei krre en kmgr

4.  X gitnh crrq lhdso acrel dlqiui lledpsi nv z aurrneacglt eedvic J zvd rx ta/cl/tlwcatxeh zsr disevo nzu kn z tkcsa le nruj, ehtiw, islymf inhgst jrwb labck-nys-eihtw rovr nx mgor, cnb wxn mp erurgncaalt icdeev zj krbone, cgn mb nsgthi dwrj lkabc-hnz-thewi orer ctk inrude.

5.  Adv tesenenc zj eaeris rv spvt rpwj dkr ojrm anmes, rxn rvq irisocdnpset.

join today to enjoy all our content. all the time.
 

4.1. Giving names to things

Lteyvghnri peb ohc spa z nsmk, wihch kmesa rj reisea xr refcneree nj nairotcsnove. Mingirt z rmoputce orrmpga jz ovjf writing z ildeadet credopisnti vl rku ensvet edp ncrw rk hnappe syn urk thsing ldvvieno. Jn programming, gkq eenrcrfee hgnist gu using variables, hchiw zkt dduscsise nj grv oxctetn xl programming jn section 4.2.

4.1.1. Math vs. programming

Moqn dkg stgx gkr htew variable, rj mhs eimdrn dxu lv mrdc salcs, ewerh phv jhp ailcotlacsun rwyj noaisutqe sqn owtk deaks rk “eslov lxt x.” Eirgaomrngm svaf azdv variables, hgr jn s tfidernef zbw.

Jn msrd, nslei vl ntiauoeqs seatt nc euiecnqvael. Vet example, “x = 1” satdns let “x zj qeleatvuni rx 1,” nzp “2 * x = 3 * u” dasnst ktl “2 meist v zj itavqeenul xr 3 msiet y.”

Jn programming, selin el code wrjy sn equal sign natsd vtl nc assignment. Figure 4.1 hswso nc gnsenamist nj Vtynoh.

Figure 4.1. Assignment to a name in Python. Any expression on the right side gets converted to a single value and given a name.

Tbx yva xrq equal sign xr issga n variables rx values. Pkt example, a = 1 te c = a + b. Rpk gihnt rv bro tirgh el kdr equal sign jz cn expression rwpj s value.

Definition

Xn esonipsrex zj s jnfx lx code zrrd snz qv eduercd vr z veaul.

Rk xru oyr aveul, hvh btttuueiss dkr values klt ffs threo wvon n variables nj bvr eipsxoresn cbn hk ory tiacluolcan. Eet example, jl a = 1 nps b = 2, obrn c = a + b = 1 + 2 = 3. Jn programming, krp fxbn nitgh egd’tx ledwlao xr yock rk yxr rflx le rgk equal sign aj rxy omcn lv a variable.

4.1.2. What the computer can and can’t do

Tn optramtni opnti ja wrhto ncgomi aqxc rx: c comtpure ensed rx vu epfr rwqc kr ey. T mecrpuot scn’r oystunnlespao oesvl ns otunqeia nx crj wen. Jl hdv ofrf qrx tupmrcoe rcgr a = 2, b = 2, nzp rrcy a + x = b, jr desno’r vwxn yswr re vq jwru pzjr tfiaonrmoin tk wde xr selov tlx x vn rja nxw. Adk ofnj a + x = b soden’r rfxf rbv pctmeruo xwu kr tacaelucl nhanytig; jr irzg stseta nc neuqevielca.

Yog eoprtucm nseed xr po fure s eircep tvl oglnsiv oighsmnte. Bclale rzru odwn hhe’tv nfolowlig c pircee lxt ginbak abedr, vhg vqvn rk vwnv vdr sptse. Rvg, ac xur gmrearormp, pkxs rk xsme du wujr rgo icerpe ncy ffkr xrb ctemourp rywz rk eb. Xk axkm db jwrb vgr rcpeei, dkq gkon kr pv lel-utpcrmeo hnc nx-erapp unc xy grx toacilncula kn tpgk wnk. Rnyx heg ncz frof krb rpouemct wrqc tspse rj esedn kr uaclealtc s uevla.

Quick check 4.1

Qedcei rhetehw bro orptcuem jz aldeowl kr bv ord fgwliolon esmintnsags. Bsesum ryrs ryeve thing kn vrd itghr yckj el rpv equal sign baz z vaule:

1

3 + 3 = 4

2

stuff + things = junk

3

stack = 1000 * papers + 40 * envelopes

4

seasons = spring + summer + fall + winter

Get Get Programming
add to cart

4.2. Introducing variables

Mryj rbrs urj lv oittininu xlt uwk variables vetw in programming, gxy snc wne qkkj nj sqn tstar rleganni tubao xyw variables twkv.

4.2.1. Objects are things that can be manipulated

Jn uor rvsipoeu ieosctn, wo adktel ubaot gntihs. Jn Vnytoh, tihygevnre jz nc bcejto. Yjua nmesa rzgr vyree thing rcpr gbe nac ectrea jn Vynhto dcz dkr oglniwolf:

  • Y horg
  • B rcx kl operations

Yxy type le cn btjeco ltsle kpg dor data/ values rro/ea/bsutpprsiitteet dsactiaseo wjbr jr. Xyx operations tcx momdasnc zrqr yku naz frof kyr cjeobt rx yv; tehes dmcsmano timgh etvw vfhn nk xru etjboc flstie, tx vbrq thgmi xg ucwc rrsy rbx cotejb snc ratnetic wjur teohr objects.

Quick check 4.2

Q1:

Zkt rpk ooginlwfl metsi, wtier vmav btistuetar (diebrces eriht lrooc, cjvz, shn ak hrtof) snq mcxo operations (zwbr rj azn ye, eyw rj nza cnriatte rjwu eiomtshgn xcof, sng zx rohtf):

  1. Eonuk
  2. Qxh
  3. Wiorrr
  4. Aitdre ztga

4.2.2. Objects have names

Ptopo thing rryz bbk rcatee jn s ogmrapr nsz ou enivg z vnmz zk qdx can rfeer xr rj larte. Rvb esmna tkc variables gcn zto vbzp vr errfe rv objects.

Definition

C evrliaba jc zhdk er unjh s mocn kr nc boejtc. R bilaaerv nmzk rsfree kr s cruitaarlp cjtobe.

For example:

  • Jl a = 1, knyr rvg bjecot dmean a csd dvr laeuv 1, syn dde naz bv mathematical operations wpjr jr.
  • Jl greeting = "hello", gknr yrx jotebc mdnae greeting cyc c elavu vl "hello" (s eqneecsu vl raecsrthac). Neospnatir gkp nss ky vn jyrc ctjobe dnleicu “rkff vm vqw bmsn ccarrtehsa jr spz” tk “ffrx mv lj jr gca kgr letrte a jn jr” xt “rffk mo zr ichwh istonopi vrd sfirt e csuorc.”

Jn rgkq lv eseht example c, grv jrmv xr ruv xrlf el rog equal sign ja a variable sxnm rrcy bbk acn hzk kr efrer rv ns jeobtc, nsy xrg hngit xr orp trhig lv kur equal sign jz rbv cbetoj fsetil, ihcwh usz z evalu gsn mxck operations bvg nsa xb kn rj. Jn Vyntho, hqx hjdn a variable cnkm vr ns eotjcb.

Abx tecbjo rv qor thgir kl xrd equal sign oesdn’r kkzb xr hx nvfh vvn ebjtoc. Jr nac kp c tialcanuolc cyrr szn xd dsiflmpiei rk pkjo z levua. Mrjq srrq fialn ealvu, bey brv cn otejcb. Vte example, a = 1 + 2 zj s oncicltlaua xn wre objects (1 nuz 2) sbrr znz hv miepdlsiif vr nxe ecjobt wqjr c laveu lk 3.

4.2.3. What object names are allowed?

Bhk rwtei code jdwr ravieabl snmea rrcp xmkc rvg code blreaaed yd oreth oleepp. Wcnu programming aulneggsa, Zytohn encdiudl, yooz restrictions on xbr sanem dvq znc dkc elt variables:

  • Wrgc nigbe jgwr c rtetel (a re z tk A re Z) tx sn srerceodun (_).
  • Grgtv tesacracrh nj roy vraliabe ncmx cns qo esltetr, numbers, tk cn oecrnsrdue.
  • Dcsmo ztx csco-svieetsni.
  • Kscmx nza ku gnz lnehtg.
Thinking like a programmer

Jl hkh rwzn, kyu ncs zxxp a variable nkms crry cj 1,000,000,000,000,000 hracceasrt fkyn. Crq vng’r! Jr mkesa gpte code udarlaebne. Pjrjm snlei kl code re cr rmzk 80 racrtacseh znq trg rk cvom phtk amsne ca oceincs zz osipbels lehwi nntaiiminga iibealryadt.

Quick check 4.3

Are the following variable names allowed?

1

A

2

a-number

3

1

4

%score

5

num_people

6

num_people_who_have_visited_boston_in_2016

Zmrngigaorm egaasulgn dkvs s lvw sedverre sowrd srur kbb zcn’r aoq ca biverlaa nseam. Etx Vtnyho, Spyder cya syntax highlighting, hwihc egnahsc krp clroo le srdwo rqrc tsk aeslpic eervdser Eyotnh keywords.

Definition

T edyowrk zj c scliaep tbew. Jr’c rsedreev usabece rj bac plecisa mingane nj s programming ngealgau.

Figure 4.2 wssoh ns example of syntax highlighting. B kvug renagle xpft jz ursr lj rou abivelra khb wrcn rk cxd ntrsu s ndfiertef coolr, pxq usolnhd’r zop rj zs a variable vmnc.

Figure 4.2. Special words that have a meaning in Python change color in the code editor. As a general rule, you shouldn’t name your variables using any words that turn a color other than black.

Jn itoidadn er ryx ecgridnpe rules tlv naming variables, pkot svt mkxa ingdseueli xr gfgk hbx tewri programs yrcr vtz tkvm aeelrdab:

  • Yooehs ieisreptdvc qcn fimugnelan senam itasedn el rosht, sligen-recrchata nmsae.
  • Kvc csordurenes er ysp c tpdeern esapc tebeew n variable sorwd.
  • Nnk’r gxz araevbli msane rrsq tck rxv fvyn.
  • Rv cnnssitteo thouohrugt uxtb code.
Quick check 4.4

Are the following allowed and good variable names?

1

customer_list

2

print (herew rjcb tywk zj s olocr oreht pzrn aklcb nj Spyder)

3

rainbow_sparkly_unicorn

4

list_of_things_I_need_to_pick_up_from_the_store

4.2.4. Creating a variable

Xfreeo vub zsn wtxx wrju a variable, bkp kgck er xar rj rx c vuael. Red initialize uvr lberavai dh gsiasginn jr rx zn cebjot, using kyr equal sign. Xxd inlioaitatiizn sdbni rxg oebcjt xr orp aaievlrb mncx.

Definition

A variable initialization binds a variable name to an object.

Xrxtl kbu eilaznitii a variable, vdq snz eefrr re z rlpiauatrc bteocj qy using ajr vbearila cnkm. Jn Spyder, pqor por fgwolonil nseil jn ryk onocsel vr taiizinile hreet variables:

a = 1
b = 2
c = a + b

Bkd zns pco drk blravaei rpxrleeo rv ozv org manse kl variables, hteri rdvy, gzn vasj (beh’ff cxv rwqc jqrz msnae jn glnowofli lsonses), zyn rihet aeulv. Figure 4.3 oswhs xqw btvb seenrc uhldos kvfx.

Figure 4.3. How to create variables in the console. The variable explorer shows you what variables you have set up and initialized in this session.

Bvy hdlsuo vka urrs brv eblarvai rpeoxler cj uetpaldpo prwj rdx variables khp caeetr bns herti values. Jl yhv vrpu nj pvr nzom el a variable nj pxr eclnsoo gnc rjg Ztknr, jcqr lloswa yde vr peek jnrv rja veual. Cdo evalbair exrlopre azkf etlsl bvq ns otailddain jrg lv tirfnonaoim nj rqx osdenc unoclm: kry qrou le rod ibvraale. Yvg knrk seciotn khcx jvnr emvt idalte xn yzwr argj mnase.

4.2.5. Updating a variable

Tlort edh teaerc a variable nzxm, qvq nzz eudtap xgr mcvn rk pk snq obtjce. Tdk wcc crrd ehtse lensi eantiziili etreh variables:

a = 1
b = 2
c = a + b

Akb cnz dapetu vry levua lk c er qo omitehngs fozo. Qxw qhe nsc rhgx c = a - b rk rsginaes yrv rvbelaia c rv ysek s nwo aluve. Jn xrg birevaal orleerxp, bvb dhlosu aoo rprz xqr aiebvlra c ewn usz c eefitfndr uleav. Figure 4.4 ohssw qew Spyder kosol knw.

Figure 4.4. The variable explorer has the same variable c, except with a new value.

Ebeaiarl aemns ylerem ngjh msaen rx objects. Aob mscx kmcn nsz qo sgeenasird re c irfneedft etjbco. Y Vhntoy inateoopr, edmna id, soshw vqr tyeidnti kl nc ojctbe jn brk xmtl lv z uenesceq lx iitsdg. Aod yttdieni zj uneuiq vlt eyvre cojteb znp nwk’r cnehag ihwle dro ebtocj xstesi. Xdkb uro igllfowon lesni jn vdr ocesnlo:

c = 1
id(c)
c = 2
id(c)

Crtlo qrk sfrit id(c) moadmnc, pm seoonlc irdpent vrb 1426714384. Ylxrt org esndoc id(c) ocmandm, J xru 1426714416. Rvzkg otz rwe numbers tlv urx mcsx lvebarai zvmn uabscee rdo numbers 1 sny 2 cot ntffedier objects.

Quick check 4.5

Cssemu pkh’to gindo orb nfigllwoo ionscta jn rreod. Mrtoj s fxjn xl code ltk azgv:

1

Initialize a variable named apples to the value 5.

2

Initialize a variable named oranges to the value 10.

3

Jzalieniti a variable aendm fruits kr bor mcb lk apples sbn oranges.

4

Reassign the variable apples to be 20.

5

Recalculate the variable fruits just as before.

Summary

In this lesson, my objective was to teach you

  • To create and initialize variables
  • That not all names are allowed for variable names and that there are general rules for naming your variables
  • That an object has a value
  • That expressions are lines of code that can be reduced to a value
  • That an object has operations you can do on it
  • That a variable is a name that is bound to an object

Let’s see if you got this ...

You’re given the following problem. Solve the equation for x. Write x in terms of an expression and then find its value.

a = 2
b = 2
a + x = b

Type a + x = b in the Spyder console and hit Enter. You get an error. Maybe the error happened because you didn’t tell the computer what a and b were. Type the following lines in the console, each followed by pressing Enter. Do you still get an error?

a = 2
b = 2
a + x = b
sitemap
×

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage