python习题Word格式.docx
《python习题Word格式.docx》由会员分享,可在线阅读,更多相关《python习题Word格式.docx(49页珍藏版)》请在冰豆网上搜索。
![python习题Word格式.docx](https://file1.bdocx.com/fileroot1/2022-11/26/51902f22-990e-487d-a42d-734294c3853e/51902f22-990e-487d-a42d-734294c3853e1.gif)
hello"
anddescribeyourresult.Makenoteofwhenyouseethequotationmarksandwhenyoudon’t.
8.Typeprintcheesewithoutthequotationmarks.Theoutputwilllooksomethinglikethis:
9.Traceback(mostrecentcalllast):
10.File"
line1,in?
NameError:
name'
cheese'
isnotdefined
Thisisarun-timeerror;
specifically,itisaNameError,andevenmorespecifically,itisanerrorbecausethenamecheeseisnotdefined.Ifyoudon’tknowwhatthatmeansyet,youwillsoon.
11.Type'
Thisisatest...'
atthePythonpromptandhitenter.Recordwhathappens.
Nowcreateapythonscriptnamedtest1.pywiththefollowingcontents(besuretosaveitbeforeyoutrytorunit):
'
Whathappenswhenyourunthisscript?
Nowchangethecontentsto:
print'
andrunitagain.
Whathappenedthistime?
WheneveranexpressionistypedatthePythonprompt,itisevaluatedandtheresultisprintedonthelinebelow.'
isanexpression,whichevaluatesto'
(justliketheexpression42evaluatesto42).Inascript,however,evaluationsofexpressionsarenotsenttotheprogramoutput,soitisnecessarytoexplicitlyprintthem.
2.13.Exercises¶
1.Recordwhathappenswhenyouprintanassignmentstatement:
2.>
>
printn=7
Howaboutthis?
print7+5
Orthis?
print5.2,"
this"
4-2,"
that"
5/2.0
Canyouthinkageneralruleforwhatcanfollowtheprintstatement?
Whatdoestheprintstatementreturn?
3.Takethesentence:
AllworkandnoplaymakesJackadullboy.Storeeachwordinaseparatevariable,thenprintoutthesentenceononelineusingprint.
4.Addparenthesistotheexpression6*1-2tochangeitsvaluefrom4to-6.
5.Placeacommentbeforealineofcodethatpreviouslyworked,andrecordwhathappenswhenyoureruntheprogram.
6.Thedifferencebetweeninputandraw_inputisthatinputevaluatestheinputstringandraw_inputdoesnot.Trythefollowingintheinterpreterandrecordwhathappens:
7.>
x=input()
8.3.14
9.>
type(x)
10.>
x=raw_input()
11.3.14
12.>
13.>
14.'
Theknightswhosay"
ni!
15.>
x
Whathappensifyoutrytheexampleabovewithoutthequotationmarks?
Describeandexplaineachresult.
16.StartthePythoninterpreterandenterbruce+4attheprompt.Thiswillgiveyouanerror:
bruce'
Assignavaluetobrucesothatbruce+4evaluatesto10.
17.Writeaprogram(Pythonscript)namedmadlib.py,whichaskstheusertoenteraseriesofnouns,verbs,adjectives,adverbs,pluralnouns,pasttenseverbs,etc.,andthengeneratesaparagraphwhichissyntacticallycorrectbutsemanticallyridiculous(seehttp:
//madlibs.orgforexamples).
3.8.Exercises¶
1.Usingatexteditor,createaPythonscriptnamedtryme3.py.Writeafunctioninthisfilecallednine_linesthatusesthree_linestoprintnineblanklines.Nowaddafunctionnamedclear_screenthatprintsouttwenty-fiveblanklines.Thelastlineofyourprogramshouldbeacalltoclear_screen.
2.Movethelastlineoftryme3.pytothetopoftheprogram,sothefunctioncalltoclear_screenappearsbeforethefunctiondefinition.Runtheprogramandrecordwhaterrormessageyouget.Canyoustatearuleaboutfunctiondefinitionsandfunctioncallswhichdescribeswheretheycanappearrelativetoeachotherinaprogram?
3.Startingwithaworkingversionoftryme3.py,movethedefinitionofnew_lineafterthedefinitionofthree_lines.Recordwhathappenswhenyourunthisprogram.Nowmovethedefinitionofnew_linebelowacalltothree_lines().Explainhowthisisanexampleoftheruleyoustatedinthepreviousexercise.
4.Fillinthebodyofthefunctiondefinitionforcat_n_timessothatitwillprintthestring,s,ntimes:
5.defcat_n_times(s,n):
<
fillinyourcodehere>
Savethisfunctioninascriptnamedimport_test.py.Nowataunixprompt,makesureyouareinthesamedirectorywheretheimport_test.pyislocated(lsshouldshowimport_test.py).StartaPythonshellandtrythefollowing:
fromimport_testimport*
cat_n_times('
Spam'
7)
SpamSpamSpamSpamSpamSpamSpam
Ifalliswell,yoursessionshouldworkthesameasthisone.Experimentwithothercallstocat_n_timesuntilyoufeelcomfortablewithhowitworks.
4.13.Exercises¶
1.Trytoevaluatethefollowingnumericalexpressionsinyourhead,thenusethePythoninterpretertocheckyourresults:
1.>
5%2
9%5
3.>
15%12
4.>
12%15
5.>
6%6
6.>
0%7
7%0
Whathappenedwiththelastexample?
Why?
Ifyouwereabletocorrectlyanticipatethecomputer’sresponseinallbutthelastone,itistimetomoveon.Ifnot,taketimenowtomakeupexamplesofyourown.Explorethemodulusoperatoruntilyouareconfidentyouunderstandhowitworks.
2.ifx<
y:
3.printx,"
islessthan"
y
4.elifx>
5.printx,"
isgreaterthan"
6.else:
7.printx,"
and"
y,"
areequal"
8.Wrapthiscodeinafunctioncalledcompare(x,y).Callcomparethreetimes:
oneeachwherethefirstargumentislessthan,greaterthan,andequaltothesecondargument.
9.Tobetterunderstandbooleanexpressions,itishelpfultoconstructtruthtables.Twobooleanexpressionsarelogicallyequivalentifandonlyiftheyhavethesametruthtable.
ThefollowingPythonscriptprintsoutthetruthtableforanybooleanexpressionintwovariables:
pandq:
expression=raw_input("
Enterabooleanexpressionintwovariables,pandq:
"
)
print"
pq%s"
%expression
length=len("
%expression)
printlength*"
="
forpinTrue,False:
forqinTrue,False:
print"
%-7s%-7s%-7s"
%(p,q,eval(expression))
Youwilllearnhowthisscriptworksinlaterchapters.Fornow,youwilluseittolearnaboutbooleanexpressions.Copythisprogramtoafilenamedp_and_q.py,thenrunitfromthecommandlineandgiveit:
porq,whenpromptedforabooleanexpression.Youshouldgetthefollowingoutput:
pqporq
=====================
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse
Nowthatweseehowitworks,let’swrapitinafunctiontomakeiteasiertouse:
deftruth_table(expression):
length=len("
printlength*"
forpinTrue,False:
WecanimportitintoaPythonshellandcalltruth_tablewithastringcontainingourbooleanexpressioninpandqasanargument:
fromp_and_qimport*
truth_table("
porq"
pqporq
Usethetruth_tablefunctionswiththefollowingbooleanexpressions,recordingthetruthtableproducedeachtime:
1.not(porq)
2.pandq
3.not(pandq)
4.not(p)ornot(q)
5.not(p)andnot(q)
Whichofthesearelogicallyequivalent?
10.EnterthefollowingexpressionsintothePythonshell:
11.TrueorFalse
12.TrueandFalse
13.not(False)andTrue
14.Trueor7
15.Falseor7
16.Trueand0
17.Falseor8
18."
happy"
and"
sad"
19."
or"
20."
21."
Analyzetheseresults.Whatobservationscanyoumakeaboutvaluesofdifferenttypesandlogicaloperators?
Canyouwritetheseobservationsintheformofsimplerulesaboutandandorexpressions?
22.ifchoice=='
a'
:
23.function_a()
24.elifchoice=='
b'
25.function_b()
26.elifchoice=='
c'
27.function_c()
28.else:
29.print"
Invalidchoice."
30.Wrapthiscodeinafunctioncalleddispatch(choice).Thendefinefunction_a,function_b,andfunction_csothattheyprintoutamessagesayingtheywerecalled.Forexample:
31.deffunction_a():
32.print"
function_awascalled..."
Putthefourfunctions(dispatch,function_a,function_b,andfunction_cintoascriptnamedch04e05.py.Atthebottomofthisscriptaddacalltodispatch('
).Youroutputshouldbe:
function_bwascalled...
Finally,modifythescriptsothatusercanenter‘a’,‘b’,or‘