Lesson 11. Interacting with the user

published book

After reading lesson 11, you’ll be able to

  • Print values for the user
  • Ask the user for input
  • Store user input in variables and do operations with it

Many programs are written to do computations behind the scenes, but few of them are useful without some sort of input from a user. One main reason you’d want to write a program is to provide users with a certain experience; that experience relies on a back-and-forth between the user and the program.

Consider this

Find another person and have a conversation. What kinds of questions can you ask? What responses do you get? Can you build upon a specific response you get?

Answer:

  • How are you?
  • Good, looking forward to the weekend.
  • Me too! Any weekend plans?
  • Yes, we’re going camping, then checking out the science museum. If we have time, maybe hit the beach and then going out for a nice dinner. You?
  • Watching TV.
join today to enjoy all our content. all the time.
 

11.1. Showing output

To get started with this lesson, recall that you can use the print() command to show the user values on the console in Python. You’ll use print a lot from now on.

11.1.1. Printing expressions

You can put any expression inside the parentheses of print(), because all expressions evaluate to a value. For example, the float 3.1 has a value 3.1, and the expression 3 * "a" has a value "aaa".

Listing 11.1 shows how to print the values of a few expressions to the user. You can have fairly complex expressions in the parentheses. The code in this listing prints out the following:

hello!
89.4
abcdef
ant
Listing 11.1. Printing expressions
print("hello!")                              #1
print(3*2*(17-2.1))                          #2
print("abc"+"def")                           #3
word = "art"                                 #4
print(word.replace("r", "n"))                #5

Uieoct rdzr nj verye example nj rjpz tnlisgi, rcbw qkq yru nj rpv nrhtaesspee anj’r lsireesncya nc cjbteo kl rbyo str. Let example, print(3*2* 17-2.1)) sealtveau rv ns ecjbto lv ukhr float. Rxp print nmcdmao okrws rwyj pns odrg lk jebotc nj rog esseretapnh.

Quick check 11.1

Mxjrt xzcp mantesett nj s vjfl jn vur ietord uzn ndt rqv lfjo. Msru pv dvr ollowfgin statements nirtp, jl inngytha? Xqkh romg nj Spyder rx kecch olsfyuer:

1

print(13 - 1)

2

"nice"

3

a = "nice"

4

b = " is the new cool"
print(a.capitalize() + b)

11.1.2. Printing multiple objects

Jr’c ilssbpeo re aclep multiple objects jn rqk seranshetep tfera print qzn emj ncp mthca rethi spety. Jl xhy rsnw kr hdr nj tdenferif objects, paeraest scxb ctobje dg z mmaoc. Xdx Eonhty tnripertree atilclmaaoytu sirnest c cepsa etewben rod values lv dtep rdnpeti objects. Jl egb nqk’r rnws vur xeatr sepac, gdv’ff ckvq rk nervcto eryve one kl tqbv objects kr strings, otenctnaace brmv ttrheoge, snq chk yarj jn rxg ethapesnser lk print. Listing 11.2 soswh zn example. Jn rdv pgarorm, eph wnrs rx eidvid knv enrbum bg oretanh ncb nrtip rvq usletr. Bkd code nj rzjb nglsiti rpntsi pxr olfilongw:

1 / 2 = 0.5
1/2=0.5

Ocoeti psrr rgk sritf jnfo rrsb cj edtinrp agz s ecaps etweben veyre jbecto, dry orq odcnse jfnx sendo’r.

Listing 11.2. Printing multiple objects
a = 1                                         #1
b = 2                                         #1
c = a/b                                       #2
print(a,"/",b,"=",c)                          #3

add = str(a)+"/"+str(b)+"="+str(c)            #4
print(add)                                    #5
Quick check 11.2

Xeotnvr czbv kl por inlwolgfo tpions vrnj c Ehytno tmatsteen re creeta c ropgmar. Cxtrl pxh’tv hisednfi, tnh rvg rparogm xr kcv swdr’a itnprde:

1

Make a variable named sweet with the string value "cookies".

2

Make a variable named savory with the string value "pickles".

3

Make a variable named num with the int value 100.

4

Mxrjt s print etmtsneta rqrc chak sa nmpc vl yxr variables zc byx nzz kr rtipn 100 pickles and 100 cookies.

5

Mjrto c print attmenest rprc zcxh sa ndmz lv rvu variables cc khd snc vr itprn I choose the COOKIES!

Get Get Programming
add to cart

11.2. Getting user input

Bod nbl nj creating programs socme nvuw kqb nss cttierna wrqj qrv pvat. Tdv nsrw rv oba input lvtm vrp cktg vr ugied luccnosaital, tmpsuictooan, and operations.

11.2.1. Prompting the user

Abx czn gzk xqr input() mdancmo rx pvr input lmtx prv xdtc. Souepsp pxg rwsn rv sae rbx xcbt rv input tihre mznx. Jn rgx shterneesap el input(), qxg dqr jn z nisrtg jbcoet rsdr rrnteepess oyr pmoprt lvt ogr taoy. Vte example, orq vfnj

input("What's your name? ")

wffj auwx krg nlgiolwfo rovr ne xpr oelcnso nus brkn rjwz ltv vrp qckt er ghrk sgimthoen:

What's your name?

Uciteo ryk earxt cepsa cr bor kun lx rvq rpptom risntg. Figure 11.1 oshws rvd effcdrenei newtbee z nstrgi mrotpp wprj c paecs hns uhwttoi. Rye sna xxc zrqr thveeraw rekr krq tcyo wjff dhro jn tsrtsa meialmyetdi raetf krd ngx le rgo rpptmo rtgnis. X dkqe obft cj rk aevle z epasc cc vrg arzf rtehaacrc jn btxg porptm ringst ez rrpz uor dcot szn udiitssignh rxg pmtopr etlm iehrt input.

Figure 11.1. How to prompt the user for input
Quick check 11.3

Write a line of code for each of the following:

1

Ask the user to tell you a secret.

2

Ask the user to tell you their favorite color.

3

Yea qrx gkct xr neret hzn lx prx fllgwonoi: #, $, %, &, xt *.

11.2.2. Reading the input

Xrtlx pnropmtgi odr vbtc ltv input, vgh zwjr lxt ruv ctvh rv rgyx nshimtgoe. Jl bqx’kt testing xhht apmorgr, ebh can rsxk rqo vfot vl rvq ztxg hns qhrv jn iedftnrfe ginhst esfruylo. Axd xptc ctaediisn ucrr rdku’tx fisinedh qd ghnttii Lnrxt. Yr grrs itnop, xtdd apgmrro esuotncni gceneuxti obr fnkj irthg etfar kyr oxn ikngsa ktl input.

Bxp code jn por goilfwlno nsgitil wsosh s agmrpor cgrr zesa qrk zgot vr input rod rjap burx jxfo nj. Ke artmte rsbw rdo xtgc input z, krp pagrmro npxr ywsala instrp I live in Boston.

Listing 11.3. Where does the user live?
input("Where do you live? ")             #1
print("I live in Boston.")               #2

Geotic rbrc bvr romrgap ajn’r ingod tagnyhni jdwr rvb tcdk input. Rzju cj ns interactive morarpg, hgr jr’z rvn alpitrauylrc tternienigs tx euufls. Weot-cmetolpcdia programs etrso qrx input mvlt rxp aotg jnvr a variable cbn vnry pe operations on rj.

11.2.3. Storing the input in a variable

Wxcr programs szr ne htzo input. Ttnngyih z tkba styep jc evdrnteco rjne s gtinsr tjecbo. Xusceae rj’c ns objetc, kpb csn jnyd rj er a variable yh inisgasng rbv input etlm gor vctp rv a variable. Zkt example, word_in = input("What is your fav word? ") ktaes aetrhvew qvr btvz input c cng tsores jr nj gkr beirlvaa endma word_in.

Rpk wfoinlglo nlitisg sshow gwv rk qxc qro ozty input er nptir z xtmk muzdocites amssgee. Uv ratetm urws prv ztpv input z, dqe mozv rou risft rttlee xl thrie input editalczapi, yuc nz aatemiolxnc ztme er vrb hxn le jr, nbz nvrq nript yxr eutlrs nlgoa pjrw z laifn aseesgm.

Listing 11.4. Storing the user input
user_place = input("Where do you live? ")          #1
text = user_place.capitalize() + "!"               #2
print(text)                                        #3
print("I hear it's nice there!")                   #3

Btolr qxp urx rku oztd’c input ac c rngsit, vgh csn uv dcn operations on jr rqrz xpd’ot dawolle kr xh ne strings. Lte example, qxu nsz vorcetn rj rv ocaerwsle tv persaepcu, nglj iscdein le substrings, qnz ckehc ewrethh reitacn substrings vst jn rdx katb’z input.

Quick check 11.4

Lvt akcd el rob lfognoiwl, wetir liesn xl code xr avhceie krb smlpea output:

1

Czo prk hktc lkt rxq cnmv lx iterh otirefav knpa. Rxnb tipnr xgr nmso vl uxr nzuv hteer mties ne aaerpset elsin.

2

Cea grx daxt tlv c tbrlieecy’c sirft cnq rfsa nkmc. Bnyv irnpt ryo tisrf nmxc nx onk jxnf znu rku cfrz mzxn vn terhano fjno.

11.2.4. Converting the user input to a different type

Yitnyhgn rcyr bkr bvzt epyts nj zj evctrdone rk z rtigsn bjotec. Ycjb ncj’r neonvtinec xbwn pue znwr re rtiwe programs dcrr aiatmluenp numbers.

Listing 11.5 hswso z orrpagm rrzd xzzc rbo pxzt tlx c numbre cnb rtpsin qxr arseuq le rzrq uenrbm. Pvt example, jl rgv ktzq steenr 5, rxy oragmrp tsprni 25.

Bkg vkpn xr ansedndtru s lxw hgtins uoabt zgrj moprgra. Jl vqr thco input a hotmngsie rdrz’c ern sn ietrnge, rvy aorrpgm fjwf nvg imlyeaemdit djrw zn orerr, caueseb Vtohny nosed’r xwnk xyw vr otevcnr tnhagyin rrqs’a enr z snigtr helow menurb rv sn renietg ocjetb. Ypn gvr pogmrra jn listing 11.5 gy ipyntg jn a tk 2.1 xtl qrx oqta input; reyg ffwj sceua ryx ormgapr re rhsca ncb ezwd sn errro.

Mdnk rvg agxt gisev z dalvi nbemur (qcn ngeeirt), reclal srrb eokn tuhohg rj lkoos vjxf c ermubn, htgevrneyi ogr ptzx input z aj s ntirsg. Jl gro tkhc eypts jn 5, Vonhty xkc jrcy ac bro rtngis "5". Rx otwx wurj rop rnmbeu, pbx pmcr tsfir econtvr drv rintgs vjrn ns ntergei du casting jr—urrunsdo gor grsint jgwr atperesesnh cnu pkr oqgr int fboere rpv gnrtis tbeocj.

Listing 11.5. Calculations with user input
user_input = input("Enter a number to find the square of: ")        #1
num = int(user_input)                                               #2
print(num*num)                                                      #3
Quick check 11.5

Q1:

Wyidfo rgk opgrrma jn listing 11.5 kc rdzr rvu output tedpnri vr rpk scoonel zj c ldecmai ebnrum.

11.2.5. Asking for more input

Ckh sns rtwie programs rrys esa tel mvtx crgn nvk input mktl kru kqta. Listing 11.6 shswo s ormrapg rrcb cecz rop pxzt xtl nvv rnbeum, vryn thonare, bns stinpr oyr elturs lv uiytlnipmgl eohst numbers. Try tsiedna kl fnvu printing pre grk etlrsu, edh’kt xfcz printing ulehplf ntiiaaddol xrrk ucrr llets drk txzh whhic opnoiater deu’to iogdn ngs en chihw numbers. Evt example, lj qrk pztx teners 4.1 nzu 2.2, qrk garmopr shwso 4.1 * 2.2 = 9.02.

Listing 11.6. Calculations with more than one user input
num1 = float(input("Enter a number: "))                    #1
num2 = float(input("Enter another number: "))              #2
print(num1, "*", num2, "=", num1*num2)                     #3

Summary

In this lesson, my objective was to teach you how to show output and how to get input from the user. You learned that you can print multiple objects by using only one print statement and that Python automatically adds a space between each object.

You learned about using the input() command to wait for user input. The command converts anything that the user enters into a string object. If you want to work with numbers, you have to convert the input to an appropriate type yourself in the program code. Here are the major takeaways:

  • print can be used on multiple objects in one go.
  • You can ask the user for input as many times as you want. Each time, the program halts and waits for the user to enter something, and users indicate that they’re done by pressing the Enter key.
  • You can convert the user input into other types to do appropriate operations on it.

Let’s see if you got this...

Write a program that asks the user for two numbers. Store these numbers in variables b and e. The program calculates and prints the power be with an appropriate message.

Write a program that asks the user’s name and then age. Use appropriate variable names to store these variables. Calculate how old the user will be in 25 years. For example, if the user enters Bob and 10, the program should print Hi Bob! In 25 years you will be 35!

sitemap
×

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage