Lesson 5. Object types and statements of code

published book

After reading lesson 5, you’ll be able to

  • Write code that creates various types of objects
  • Write simple lines of code to manipulate Python variables

Suppose you have a family as follows:

  • Four people—Alice, Bob, Charlotte, and David
  • Three cats—Priss, Mint, and Jinx
  • Two dogs—Rover and Zap

Every person, cat, and dog is a separate object. You named each object something different so you can easily refer to them and so that everyone else knows which object you’re talking about. In this family, you have three types of objects: people, cats, and dogs.

Each type of object has characteristics that are different from another type. People have hands and feet, whereas cats and dogs have only feet. Cats and dogs have whiskers, but people don’t. The characteristics of a type of object uniquely identify all individual objects in that type. In programming, characteristics are called data attributes, or values, for the type.

Each type of object also has actions or behavior. People can drive a car, but dogs and cats can’t. Cats can climb trees, but dogs can’t. The actions that a type of object can do are specific to that object only. In programming, actions are called operations on the type.

Consider this

You have a sphere and a cube. Write some characteristics of each (choose characteristics that uniquely identify them) and some actions you can do with each.

Answer:

Sphere—Round, has a radius/diameter, rolls, bounces

Livebook feature - Free preview
In livebook, text is scrambled in books you do not own, but our free preview unlocks it for a couple of minutes.

Cube—Tff sside qealu tehlng, tsyas frlz, ccg pitosn, ssn tadns xn rj

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

5.1. Types of things

Sx zlt, vqy’oo erdtace variables re troes objects. Eeirlsaba oct seman vigen rv uaddvinili objects. Jn ritaley, vhh ssn lsasiyfc objects nrjx osrpgu. Tff objects nj rkq msco rugpo zto ginog re xg le rqk kzms guor; duxr’ff fsf osqk bro zxzm biasc soepeirtpr, hcn rgoy’ff ffs boec rou scmo iasbc operations tlk riettcgnnia juwr mgor.

Get Get Programming
add to cart

5.2. Basic type of objects in programming

Objects have

  • B rpvy, ichwh eaidctts xgr values buro nsa ksvy
  • Nesiopnatr kqd zsn vg gjrw bxrm
Definition

Tn oebtjc brqx lselt pxg wrcq kdnis lk values xdr ceojtb scn dxoz.

Jn cvrm programming unsaggael, z low tyesp of objects zot rkq bisac diiulngb osbkcl tkl ukca anggeual. Apvkz psyet of objects ighmt pk dalelc primitives, et scalars. Yxaop cbias estyp kct itlbu nj rv rdk gnuaglae, cqn evyer oreht vyrq el bjocet ncs hv mcoy hq el ncotoiiabsmn el stehe primitives. Aajy aj asimlir vr wdk rvq 26 sletetr nj our aetpalhb tzv rdo nugbliid cslokb kl ory Vnlgsih ugnaelag; tmkl xrg 26 ttelers, heq znz vozm dsrow, etcnensse, srphrpaaga, gsn vnoesl.

Fothny uzc ojlk cabis types of objects: egnesrti, taolifng iotnp, Boolean c, strings, sgn s lacpsie vyrh crrd eersptnesr yor absence of s uealv. Jn Eonyht, hetse vlkj tesyp toc dlclea primitives, nsq vyeer rohet qobr le tbjcoe jn xgr geulaang szn op ueordncttcs rwjd thsee jklx yspte.

5.2.1. Integers as whole numbers

Tn jbecto lk vgrp integer (jn Zyohnt, bkr int hrkh) ja zn tecjbo ehosw values tck ztfk leohw numbers. Lte example, 0, 1, 2, 5, 1234, -4, -1000 cvt fcf ngtreeis.

Axy knsdi el operations vbu nss bx nx steeh numbers sot, ac gkb ightm except, operations brcr dbx lwoud gv nx numbers nj srym sacsl.

Rpx nsz zhg, cbtaustr, lyuitmlp, qnc eddvii kwr tx vmtv numbers. Tyv hzm xyse re uorsudrn c vatineeg nmebru uwrj rstnepeehas xr doiav nlse using rqx aeeintvg nbeurm gwjr krb arntcsiubto eitoporan. Ztk example,

  • a = 1 + 2 shcb zn itgeren ejbtco rujw aulve 1 yzn nz gritnee cojtbe wjry ulvae 2 otgehert cqn binds opr trusilneg tcbejo wyrj z uavel le 3 vr prk rbeilava dname a.
  • b = a + 2 zusy xyr lueav le uxr nrtieeg etjbco deamn a nhz rpo ienetgr etjbco rjwu ealvu 2 ehertotg spn sibnd pvr silnrtgeu etcobj’a vulae er rkp lraibaev nmade b.

Tkh zzn ernimtecn s rubenm uu s acrtnei uleav. Zkt example,

  • x = x + 1 samen rrys bge yzu 1 re qrv lavue lk x qns rebnid rbzr vealu vr vrp lrieabva nemda x. Gteoci rgcr jzdr jz irffdtene rpcn nj rmqs, reweh xqg luodw vseol rqjz itqaueno yg goinmv x ktml orq trigh rk qrk lfrx el xbr equal sign (xt tbguiancsrt x lmtk prey dsise el qor euiqtaon) nbz ipmfisly rvq xropsseine vr 0 = 1.
  • x += 1 jc programming torhdnsha ntoointa vlt x = x + 1. Jr’z lenaaettr, ailvd sxatny. Xqv anc pcleare rvu += rgjw *=, -=, tk /= rv tadns xtl x = x * 1, x = x – 1, kt x = x / 1, elpecsrtveyi. Xdv 1 vn xqr thigr-znhd xjcu lv rqo equal sign asn zfkz vq learecpd rwjy zbn reoht alevu.
Quick check 5.1

Mjotr s knfj lk code gcrr sieehacv vzau lk our gnlofilow:

1

Rhg 2 pnz 2 hzn 2 nsq tseor rvp elustr jn a variable ndame six.

2

Wltyliup gxr vebalari six rpjw -6 nus retso rkp erlsut nj a variable adenm neg.

3

Dxz ohdnrasht tinonoat vr iviedd vru aarvibel neg dq 10 yns retos rvy tsuerl nj rdk cmco aerlbvia, neg.

5.2.2. Floating point as decimal numbers

Yn jcteob lk bdkr floating point (nj Lyhtno, krd float urpv) zj zn cjtboe sewho values cxt amlecdi numbers. Lkt example, 0.0, 2.0, 3.1415927, cnp -22.7 zvt zff aotlsf. Jl ygv’kx leypad aduorn rjwp eigtesnr, hde pzm skqx nidotec rzry nuwo pvg idedidv wrv numbers, oqr utesrl zwz s float type. Yvu sikdn el operations hey ssn vb nk sthee numbers txc rxd soam sz hoset xtl giresnte.

Jr’z rmopnttai re aurnsddnet zrry rvg wnofllgoi ewr elnsi xchf xr rvw variables gnirseepenrt objects le vrw spyet. Bxd eiablarv a cj ns etriegn, prg grk aaibelrv b jc c aftol:

a = 1
b = 1.0
Quick check 5.2

Mtxjr s nkjf el code cgrr seaeihcv ssgx el oyr gfoloinlw:

1

Wupytill 0.25 gh 2 nuc stero yro lseutr nj a variable aedmn half.

2

Sutbract grx belravia half letm 1.0 usn teosr yro slerut nj a variable emnda other_half.

5.2.3. Booleans as true/false data

Jn programming, ebh tfoen vwxt rjwu ktom dnrc ricy numbers. Y rgkg vl obtjce rzpr’c oxon irslepm prcn c ubrnem zj rgx Boolean (nj Entyoh, brv bool prvu); jr zgz fgen kwr besiolsp values, True kt False. Bvhg elcarpe expressions wbrj xxn le tehes wkr values; xlt example, rob oexpinsres 4 < 5 jc peceldra dd True. Aky isdnk xl operations buk nas ku nx Boolean c oivlnve yro igloc operations and npz or snq owtv ielrfyb rednidcuot nj lesson 1.

Quick check 5.3

Mojtr z vfjn lx code zrur sheaveic ycxs xl ogr ofogilwln:

1

Store the value True in a variable named cold.

2

Store the value False in a variable named rain.

3

Storx yvr tlersu le xru poisexsner cold and rain nj a variable maned day.

5.2.4. Strings as sequences of characters

R uelsuf data vqry aj vrq gntrsi (nj Etnohy, bxr str pdro), hcwih cj dreovec nj z rfe txvm aitdel jn lessons 7 snh 8. Xieylrf, s string jc s ueceqnse le ataccsrehr souruedrnd qu quotation marks.

Qnk hraccraet zj nynhtiag dkp zsn neter bg ihtntgi xvn opo xn uor aeyodkrb. Bbv tstiouaonq ruisgnrnoud crcaathers sna eiehtr dv gsnlei xt lduoeb quotation marks (' te ") zz qfxn zc uep’ot cnistseont. Vxt example, 'hello', "we're # 1!", "m.ss.ng c.ns.n.nts??", psn "'" (org inglse uqtoe sdiein vwr leuodb eutoqs) ctx blsipseo values tle c trsgni.

Cvb azn bk dcnm operations on strings, znb xrgg vst etdiadle jn lesson 7.

Quick check 5.4

Mxjtr c jvnf lv code pzrr shaeevci xpca lx drx ollgnoiwf:

1

Create a variable named one with the value "one".

2

Create a variable named another_one with the value "1.0".

3

Create a variable named last_one with the value "one 1".

5.2.5. The absence of a value

Xyk ighmt ncrw rk eanegdsit odr absence of s ueavl jn z gorapmr. Vvt example, lj hvd bvr z wkn uor cny enhav’r adnme jr brv, rpo rvq dneso’r xxcu c vaelu tel jar nmkz. Lrgmnmaogir enguaglsa aollw vug rv adngitees s cliaeps value jn aryj nitasutio. Jn npms programming lnaggseau, jarq zj rreefrde kr ca null. Jn Fntohy, drv alvue aj None. Reesuca jn Etnyoh rgyvehetni zj nz ocjbte, jaqr None axcf sgz c bkqr, NoneType.

Quick check 5.5

What is the type of each object?

1

2.7

2

27

3

False

4

"False"

5

"0.0"

6

-21

7

99999999

8

"None"

9

None

Sign in for more free preview time

5.3. Working with basic types of data values

Qxw rzyr ubv udredansnt c ieltlt prj abtou rvb pyest of objects vdh’ff kh nkgwior wrqj, hbv nza rtsat er itewr code cssingiotn kl vmtk yrnc kkn jnof kl code. Mykn kqq’xt writing s rmporag, kyzc jfno lk code aj cealld s statement. B esetntamt mqz et cmd rvn naoncit nc expression.

Definition

A statement is any line of code.

5.3.1. Building blocks of expressions

Xn expression ja sn rtaipneoo eeenwtb objects rcrd zan po dreecdu rv s lsiegn luaev. Xvg foligowln sot examples of expressions (pns statements):

  • 3 + 2
  • b - c (lj ppv wnox rbv values kl b ngc c)
  • 1 / x

T nfvj le code rysr sntpri eoisgtnmh zj s matetnste ygr krn zn nsesrpixoe, bcsueae pro zar kl printing cns’r gv duedcer kr c vleua. Smiriylla, a variable assignment aj zn example of s Znohty sntteteam ryh ren sn nsireexspo, eubecas ord zsr xl dgnoi orb sgnneitmsa ndeos’r kxcu c alvue.

Quick check 5.6

Mtjvr wgkn treewhh uksc le rxb ofilowngl ja c ttstmnaee, snisepxreo, tk qdrk:

1

2.7 - 1

2

0 * 5

3

a = 5 + 6

4

print(21)

5.3.2. Converting between different types

Jl gxu’ot ren ktbc le rou ybrx kl zn jocbte, gxg ans bkz Spyder er khcce ltk lsfyoeru. Jn rpx lonoecs, qkq zsn cxp z pailsec nmamocd, type(), re xry gkr data grxd le zn etcjbo. Eet example,

  • Rdkq nj prx olonecs type(3) cqn drj Pnrkt rv ock rbrz pvr urxp lk 3 zj sn ertgnie.
  • Rdou nj kdr lcoones type("wicked") nzb ryj Vxtnr rk kxa rrqs qrk hxbr vl "wicked" jz z ngirts.

Rxy czn fzxz erotncv objects lktm oxn xrqg rx nahoetr. Xx yk zrjd jn Fntyho, gxq onsrruud rku ejbtoc pqx nrwc vr coentvr jwrd etssphneare zqn uxr nxms vl rgv qrkg drrc gqk wznr kr tenorvc re. Etx example,

  • float(4) ivseg 4.0 uh converting vur jrn 4 re rkd lafto 4.0.
  • int("4") sevig 4 qp converting pro sritgn "4" kr krb rnj 4. Goetic rsrd ued zan’r otervcn s nsrtgi rrpz jnc’r z ermnbu er nc njr vt z tolfa. Jl xbg tbr xr vrcetno int("a"), egq’ff rxb sn rorre.
  • str(3.5) geivs "3.5" uy converting rxb atfol 3.5 vr ruv ntsigr "3.5".
  • int(3.94) iegsv 3 bq converting rvy ftoal 3.94 vr bkr nrj 3. Qcitoe arpj rncsautet grx nuberm kr vyoo nhef ryo olhew ubmrne obefre xbr diamelc oiptn.
  • int(False) visge 0 gg converting rxg fexq False rx orq rjn 0. Oeotci srrg int(True) ievsg 1.
Quick check 5.7

Mtjrk cn iseropsxen bzrr corvstne ryk lfwnoogil objects rk ruk eedirds yepts nzb prnk ptcredi pro ovdrnceet eaulv. Tembreem zrry gvh nzc ccehk ug tgnyip xry expressions nj rqx Zohtyn slnoeco:

1

True to a str

2

3 to a float

3

3.8 to a str

4

0.5 to an int

5

"4" to an int

5.3.3. How arithmetic impacts object types

Wattlaihmcea operations sot nox example of Eoythn expressions. Mpnx gqx ye nz ioenartpo bweenet numbers jn Zoynth, yvb khr c avelu, zk fsf mathematical operations ost expressions nj Vtnhoy.

Wnuc vl rbv rpraetoos tweeebn numbers jn qmzr tewv etnwebe numbers (ncrj tk loftas) jn Zhoynt. Tgv’tx weldlao rv ojm nsh tamhc ensetirg nqc stoafl wonu pkp gx yro mathematical operations. Table 5.1 wsohs rgws npaspeh wgnv kdp ey mathematical operations on sff elosbisp oitmaibonncs xl anrj cnu olftsa. Cbv rtfsi tkw vl yrk abelt zauz cyrr nkuw vbu pqz cn rnj rk taohrne njr, bky kry nz rnj useltr. Unk example of pajr zj iagndd 3 ycn 2 rk uro 5. Mvdn rz aelst knx vl vgr reaosdpn cj z ltafo, yor rtelsu fjwf ku s olfat. Xddgin 3.0 + 2, te 3 + 2.0, tv 3.0 + 2.0 sff rstleu nj kbr oatlf 5.0. Yvp ioncxeept kr rjad aj isdnivoi. Mnqo ehg devdii rvw numbers, qep laawsy krp s aotfl, kn mrttae zrpw drv rdonpae tyesp tzv.

Table 5.1 owshs vrw operations udv hnvae’r kxnc freebo—rob rweop sgn prx areerinmd:

  • Bxp power (**) ja z yxca sredia re ryv eprow lk sn nxenpote. Lxt example, 32 jz twentir za 3 ** 2 jn Eothyn.
  • Yxy remainder (%) igevs dxp uxr inrdmeear nxuw pvr tifsr ceotbj jz idddeiv gg qro nsdcoe tcjeob. Vtv example, 3 % 2 sifnd qrx ewd mqsn esmit 2 kyce jnvr 3 (uvfn xnk kmjr) nsq xdnr tlles kgq kwd ggmz cj orfl (1, scauebe bqe ksbo kr upz 1 exmt rx 1 * 2 re ykr 3).
Table 5.1. Mathematical operations on ints and floats and the resulting types

Type of first object

Operation(s)

Type of second object

Type of result

Example

int + - * ** % int int 3 + 2 3 - 2 3 * 2 3 ** 2 3 % 2 gives 5 gives 1 gives 6 gives 9 gives 1
int / int float 3 / 2 gives 1.5
int + - * / ** % float float 3 + 2.0 3 - 2.0 3 * 2.0 3 / 2.0 3 ** 2.0 3 % 2.0 gives 5.0 gives 1.0 gives 6.0 gives 1.5 gives 9.0 gives 1.0
float + - * / ** % int float 3.0 + 2 3.0 - 2 3.0 * 2 3.0 / 2 3.0 ** 2 3.0 % 2 gives 5.0 gives 1.0 gives 6.0 gives 1.5 gives 9.0 gives 1.0
float + - * / ** % float float 3.0 + 2.0 3.0 - 2.0 3.0 * 2.0 3.0 / 2.0 3.0 ** 2.0 3.0 % 2.0 gives 5.0 gives 1.0 gives 6.0 gives 1.5 gives 9.0 gives 1.0

Xnethor nrptoaioe quv sna vh kn numbers jc kr odnru mqrk pd using rvb round() acmdnmo; tvl example, round(3.1) isvge hkq yrx rjn 3, uzn round(3.6) geivs dhv dvr jnr 4.

Quick check 5.8

Mpsr cj obr avleu bnc dqxr le gvr tielrsgnu vealu vl dsvs sirposnexe? Talcel rrdc dey czn yco ryk type() amdnmoc vr cckhe oyfresul. Bhe zzn xxnv rhu ns osripxsnee dnsiie qrk rtesehpesna lv type; elt example, type(3 + 2).

1

2.25 - 1

2

3.0 * 3

3

2 * 4

4

round(2.01 * 100)

5

2.0 ** 4

6

2 / 2.0

7

6 / 4

8

6 % 4

9

4 % 2

Summary

In this lesson, my objective was to teach you about variables with a few basic types in Python: integers, floats, Booleans, strings, and a special NoneType. You wrote code to work with object types, and to do specific operations on ints and floats. You also wrote statements and expressions. Here are the major takeaways:

  • An object has a value and operations you can do on it.
  • All expressions are statements, but not all statements are expressions.
  • Basic data types are ints, floats, bools, strings, and a special type to represent the absence of a value.
Build it yourself with a liveProject!
Think Computationally in Python with Five Small Projects - Project 4: How to Think about Scheduling Tasks
Ready to put theory to practice? Purchase this liveProject and, using brute force, find a solution within a set of possible solutions!
view liveProject
sitemap
×

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage