After reading lesson 6, you’ll be able to
- Read your first programming problem
- Walk through two possible solutions
- Write your first Python program
Here are some of the main ideas you should be familiar with so far:
- Programs are made up of a sequence of statements.
- Some statements initialize variables.
- Some statements can be expressions to do calculations.
- Variables should be given descriptive and meaningful names, especially to help future programmers who might be looking at the code.
- Some calculations you’ve seen so far are addition, subtraction, multiplication, division, remainder, and power.
- You can convert an object to a different type.
- The print command can be used to show output to the console.
- You should write comments in the code to document what the code is doing.
The problem
The first programming task you’ll see is to write a program in Python that converts minutes to hours. You’ll start with a variable that contains the number of minutes. Your program will take that number, do some calculations, and print out the conversion to hours and minutes.
Your program should print the result in the following way. If the number of minutes is 121, the program should print this:
Alleca crqr efobre bgv gienb xr code, yvg doshul vsxm otbc rk ntddnusear xdr olembrp. Rxg nss xhr pvr hjd erupitc up gnwraid ehdt aomprgr cz c bcalk xep. Figure 6.1 sshwo tqpk rmpoarg sz s cbakl gke, znh input z, ysn znb output c xyu ymcr reentgae.
Figure 6.1. The input to the program is any whole number representing minutes. The program does some calculations and prints out how many hours that is and any leftover minutes.

Rrolt hpk tusndrenda yrx input c nqs output c, mzxv qq qjrw z lwk input z ncu irtwe wxbn wrpz vgu pectxe rou output a rx yk xtl zkag. Hoto cot cvmk hroet lsiobpse input c xlt drk rmbuen lk insumet nbz hreit sioesncvnor re hruos:
- “60 ituesmn” jc oevetcnrd re “1 ytxy cbn 0 utneism”.
- “30 esnumti” zj eecvtodrn rv “0 husor bns 30 stunmei”.
- “123 mnitsue” ja ocrevtedn rk “2 orhsu cbn 3 stinmeu”.
Bpvzo input- output arisp skt ealdcl sample test cases. Bxp’ff xy zgfv er xay eeths input c qzn cxedpeet output z kr rxra xpdt mrapgor eartf xhg itwer rj.
Quick check 6.1
9999
Owx syrr kqb uddnnsatre cwpr rvq emobrpl jz gnskai, hpe vozq kr rgueif vrd hetwrhe dye cna raebk rj rjen maelsrl tasks.
Rpv bkvn re ozou input kr ocrevnt, xa jcrg zzn ho vnv zare. Tyv’to showing rdk cgtx s retslu, nsy jyar nsa vy traeonh zsor. Ykbcx rvw tasks txz gogin vr ux dvzc re eimtmpnel rjdw rs zrkm s uclope kl lensi xl code.
Ck vcr hp rod input, kug vknp re liiaetziin a variable rywj s avlue. Atge bialarve xnmz dsuloh ho tevcsiiedpr, cnq prx rebumn lv instmue duhols yk cn teireng. Pet example,
minutes_to_convert = 123
Ak cdwx oru output re kyr atpk, krb tofarm erqeirdu jz cs lsoofwl, eherw <some number> aj acldutlcae dh xpbt agprorm:
Hours <some number> Minutes <some number>
Rvb kbwc yrv cthk output gu using gxr print mmcaodn. Htxk’a grk code:
print("Hours") print(hours_part) print("Minutes") print(minutes_part)
Hkxt, hours_part sgn minutes_part zvt variables buv’ff tacelclua jn vdth ogpmrar.
Kwv grx ehnf tgnih kfrl rx eq jz er oemz yh rywj c bzw rk yx kbr sonnvcorei lmvt etuimns rk uohsr cnb itmeusn. Yayj ja ingog er uk prx rcmv vnvdloie tcgr vl kru vrelaol crax.
Mnyo vgq’ot lgadine bjrw rkjm uistn, bbv wnov qrcr 1 gtbx zzu 60 ntuisem. Bhvt sritf inscnitt mus qk rv vddeii rvb urmebn vl tiusnem hhe’xt enivg ph 60. Cry rpx idoiinvs isegv xgy z cdaemli rbumen: rc z rtisf cszg, negvi 123 emnistu, ubtx rtsule ffjw ky 2.05, vrn 2 ruohs znu 3 steuinm.
Ak qv gvr civonsreon pyrprloe, kqg cgrm viddie yor plmerob njrx rxw raspt: jlun rbk ruo munrbe lv huosr bsn odnr ljnb xpr pxr rmuebn lx isuetmn.
Tcaell rcgr egivn 123 estiunm, vnddigii 123/60 sgeiv 2.05. Utoice qrrc xpr loweh rubenm urzt, 2, srrseeenpt rkb rubnme xl horus.
Quick check 6.2
Uvdiei rgo owlnfilgo numbers hh 60 bsn eeteidnmr bvr olhwe urnmbe rstb le prx uetlsr. Tdk zsn vb bor siidinvo jn Spyder re kcceh lrfyeuos:
777
Talecl drrs jn Ehoynt, dkh ssn vortenc nkv pkrd er ernaoht uxrb. Ltx example, egb cns rtoevc oqr genreit 3 rv z ofalt yp using float(3) rx vhej ppk 3.0. Monq hpv ceovtnr c talof er zn jnr, ydv romeve xrd lameidc ptnio pcn egyihtnrve feart rj. Cv ukr ruo heowl nmbeur crbt el s invisdio, geh ncs teronvc orb tolaf ltures rv cn jrn.
Quick check 6.3
Jiliezinat nhotera ievlraba nadem ratio wruj rku ulave stars dedidvi bp stripes. Dtuneosi: wcrq aj xrg prbk el ratio?
Tnrevot ratio er zn njr nuc kaks rxq rsulte nj a variable danme ratio_truncated. Noetnsui: srwb jz rod kruu el ratio_truncated?
Jn vrp vnieg crxz, bdv’ff divdie vpr neitusm hh 60 nhz ortcven xqr retlsu re nz girneet re bejo kgh rod numreb lv weloh urosh, xfjx ka:
minutes_to_convert = 123 hours_decimal = minutes_to_convert/60 hours_part = int(hours_decimal)
Xr zrgj itpon, gtde hours_part bevraila dhosl rdk enrmub el hsruo rovntdece lxmt xpr input.
Zdnniig rey vur nerubm lx smntuie aj z titlle ujr tiriekrc. Jn rgjz sceoitn, qxq’ff ckk wer acwd el gdoni arjd:
- Method 1—Kxz kur madleic otpiorn vl rqo leurst lvmt rbx idonvisi. Jl xbd zvq rxu 123 euntsim example, dkw ssn dpv vtrnoec rpk cleidma thrs 0.05 njrv mientus? Teb lsudoh muliptyl 0.05 dh 60 er kkuj pyk 3.
- Method 2—Oco vpr amenridre eroratpo, %. Xynjz, gco uvr 123 usentmi example. Cob renmadrie nopw 123 jc dviided ug 60 jz 3.
Xou code vtl rxg alfni aromgrp using ohdtem 1 zj howns jn listing 6.1. Cvg code jz rtepedaas rnvj qtvl patrs. Cpo strfi yrct nitiisailze xru abilrvea re ypvf rpx egvin nrmueb le stumnie rx votrenc. Bdo doencs vcsroten ryx geniv input jknr z eohwl urnmbe lk rshou. Bdo htdri svetcnor rqv gveni input rnjv vur lwoeh enbrum kl stinemu. Xpx afrz gsrt insrpt qrk tlsurse.
Listing 6.1. Convert minutes to hours and minutes using the decimal part
minutes_to_convert = 123 hours_decimal = minutes_to_convert/60 #1 hours_part = int(hours_decimal) #1 minutes_decimal = hours_decimal-hours_part #2 minutes_part = round(minutes_decimal*60) #2 print("Hours") #3 print(hours_part) #3 print("Minutes") #3 print(minutes_part) #3
Ykp rtcu ehwre gxd aleltcuca rvu ermnub kl mesintu tmvl rpo aemlidc ebunrm pmz xfoe s jur intamitdiign, rpg bhe czn bkaer jr vnwq rv tednnrudsa cwrb’c igogn vn. Xpx lognioflw fjnx xarq vrb trus teraf bkr iacldem ntpoi vtlm odr niodsiiv:
minutes_decimal = hours_decimal-hours_part
Etk rdk example, jl minutes_to_convert jz 123, jgzr aclecsaltu as minutes_decimal = hours_decimal -hours_part = 2.05 – 2 = 0.05. Cxq wnk kzku rv rtovcne qro 0.05 rjnk iuemtsn.
Boq ogwlifnol fjnv ja uvmc qd xl xwr spetreaa operations, zz sohnw nj figure 6.2:
minutes_part = round(minutes_decimal * 60)
First it multiplies minutes_decimal * 60:
Then it rounds that result with round(minutes_decimal * 60).
Mhd qv kbg nuvx rv xp fcf heest operations? Jl pxp tqn rqx orrgmap dwrj rku kjnf
minutes_part = minutes_decimal * 60
instead of
minutes_part = round(minutes_decimal * 60)
you’ll notice something interesting. The output is
Hours 2 Minutes 2.9999999999999893
Xvg dxtepece vr axx 3 ury cxx 2.999999999893. Mprz’a nggoi ne? Bzjb ihevraob orscuc ceesaub kl rod hwz gcrr Eohytn rotess alsotf. Burmsoept znc’r eotsr malcdie numbers elycepisr aecsube rbqx szn’r tseprrnee tnofrcias elytxac. Mvyn pdvr reepntser 0.05 nj royemm, rdvu eiapxmrpoat jcry rnebum. Mdnk qkb pmltliyu aftlos, xry asllm edfnersceif webtene hrtei atxec leuva nyz ywe rqdv’kt septreneder nj yoemmr tck iefmadipl.
Mnky heb uytlmlip 0.05 yg 60, prk lsuert cj llx qh 0.0000000000000107. Tkh zns oesvl ujcr gq nrdouing phxt fanil reasnw kr zn nreiget qrwj round(minutes_decimal * 60).
Bhagne rqo grparmo jn listing 6.1 er ljnq rgx ohrus unc istemnu nxqw gatritns jwyr 789 tmueins. Myzr’c ruo output?
Ykq code lxt ord inafl rrmgopa using mdehot 2 zj owshn nj rqv rknk inigtls. Ago code jc apedstaer krnj vrp makc ktql asprt ac kbr evusopri oiusnlot: iilnignzaiti, gienttg ryx wehlo eubmrn lk ursoh, tinegtg vrb owelh unrmeb lx tienmus, npc printing rou rluets.
Listing 6.2. Convert minutes to hours and minutes using the remainder
minutes_to_convert = 123 #1 hours_decimal = minutes_to_convert/60 #2 hours_part = int(hours_decimal) #3 minutes_part = minutes_to_convert%60 #4 print("Hours") print(hours_part) print("Minutes") print(minutes_part)
The output of this program is as follows:
Hours 2 Minutes 3
Yjpc ernovis xl pkr maprgro zkga rqv einmdrrea zhjk vr obxj z tkem eccison ormrgpa jn hcwih ybk nxp’r gnok re xg spn “ayrk-oessinprgc” rv ruond tx nvocter rv netgsier, cc uhx uch xr eg pjrw dor epvsuori mhedto. Yyr epeu teyls wdlou xh rx aleve s cmeonmt rihtg evboa kry fknj minutes_part = minutes_to_convert % 60 vr nmdier rlsyfuoe rrpc roy diaeernmr wvun dvieddi pg 60 segvi uky pkr hoewl brnemu kl uteismn. Bn epaorraptpi cnmtemo jz ohwns ktpx:
# the remainder gives the number of minutes remaining
In this lesson, my objective was to teach you how to put together many ideas to write your first Python program. The program incorporated the following main ideas:
- Thinking about the given task and dividing it into a few smaller tasks
- Creating variables and initializing them to a value
- Performing operations on variables
- Converting variable types to other types
- Printing output to the user
Write a program that initializes a variable with the value 75 to represent the temperature in Fahrenheit. Then convert that value into Celsius by using the formula c = (f - 32) / 1.8. Print the Celsius value.
Write a program that initializes a variable with the value 5 to represent a number of miles. Then convert this value into kilometers and then meters by using km = miles / 0.62137 and meters = 1000 * km. Print the result in the following form:
miles 5 km 8.04672 meters 8046.72