Download The Python range() function, for in loops

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Addition wikipedia , lookup

Mathematics of radio engineering wikipedia , lookup

Series (mathematics) wikipedia , lookup

Transcript
CompSci101-PrinciplesofProgramming
2
Learningoutcomes
! Attheendofthislecture,studentsshould:
!  understandthePythonrange()func/onandbeabletouseittodefineasequenceof
values
!  understandthefor…inloopstructureusedwiththerange()func/on
!  beabletodefineafor…inrange()looptoimplementcounter-controlledrepe//on
!  beabletoconvertafor…inrange()loopintoanequivalentwhileloopandviceversa
COMPSCI11
PrinciplesofProgramming
Lecture13–rangefunc/on,for…inrange()loops
CompSci101-PrinciplesofProgramming
! Fromlecture12
3
Recap
def get_legal_user_num(lower, upper):!
!prompt = "Enter a number (" !
!prompt = prompt + str(lower) + "-" + str(upper) + "): "!
!number = int(input(prompt))!
!
!
!return number!
!
def main():!
!print(get_legal_user_num(0, 6))!
!print(get_legal_user_num(10, 20))!
!print(get_legal_user_num(1, 2))!
!
main()!
4
ThePythonrange()func/on
! ThePythonrange()func/ondefinesasequenceofintegervalueswithin
boundaries.
! Therange()func/onhasthefollowingsyntax:range(start,stop,step)
!  aloopisusedforimplemen/ngrepeatedtasks
!  beabletodesignandwritePythonwhileloops
!while number < lower or number > upper:!
! !number = int(input(prompt))!
CompSci101-PrinciplesofProgramming
Enteranumber(0-6):-1
Enteranumber(0-6):8
Enteranumber(0-6):6
6
Enteranumber(10-20):13
13
Enteranumber(1-2):3
Enteranumber(1-2):0
Enteranumber(1-2):2
2
wherethethreeargumentsare:
start-thelowerbound(included)ofthesequencedefined,
stop-theupperbound(excluded)ofthesequencedefined,
step-theincrementbetweeneachnumberinthesequencedefined.
! Someexamples:
! range(1,10,2)definesthesequence1,3,5,7,9
! range(5,20,6)definesthesequence5,11,17
! range(14,4,-3)definesthesequence14,11,8,5
! range(0,7,1)definesthesequence0,1,2,3,4,5,6
CompSci101-PrinciplesofProgramming
5
CompSci101-PrinciplesofProgramming
ThePythonrange()func/oncon/nued
ThePythonrange()func/oncon/nued
range(start,stop,step)
range(start,stop,step)
! Thestepcannotbe0:
! IfthestepisomiWed,thedefaultstepis1.
!  range(0,7,0)givesanerror
! range(0,7)definesthesequence0,1,2,3,4,5,6
! range(4,-1)definesthesequence4,3,2,1,0
ValueError:range()arg3mustnotbezero
! Ifthestepisnega/vethenthestartvalueshouldbegreater
thanthestopvalue.
! IfboththestartandthestepareomiWed,thesequencestarts
! range(14,4,-3)definesthesequence14,11,8,5
! range(4,14,-3)definesanemptyrangeofnumbers
from0withastepincrementof1.
! range(5)definesthesequence0,1,2,3,4,
! range(7)definesthesequence0,1,2,3,4,5,6
6
! Ifthestepisposi/vethenthestartvalueshouldbesmallerthan
thestopvalue.
! range(14,4,3)definesanemptyrangeofnumbers
! range(4,14,3)definesthesequence4,7,10,13
NotethatprinCngarangeobjectdoesNOTprintthedefinedsequenceofintegers,i.e.,
print(range(6))doesNOTprintthenumbers012345
CompSci101-PrinciplesofProgramming
7
Itera/on–for…inloops
! Thefollowingwhileloopexecutesexactly100/mes(forcount=0to
count=99).Thevariable,count,controlsthenumberof/mesthe
loopbodyisexecuted. count = 0!
while count < 100:!
!print("Programming is fun!")!
!count = count + 1!
CompSci101-PrinciplesofProgramming
!print("Programming is fun!")!
for number in range(0, 100):!
!print("Programming is fun!")!
print("Done!")!
forcountinrange(…):
! Thefor…inrange(…)loopprovidesacompact
statement1
structureforcounter-controlledloops.
statement2
statement3
for count in range(0, 100):!
… !print("Programming is fun!")!
Programmingisfun!
print("Done!")!
Programmingisfun!
Programmingisfun!
…
Done!
8
Itera/on–for…inloops
! Notethatinthefor…inlooponthepreviousslidethenameusedfor
theloopvariablecanbeanyidenCfier.Thefollowingtwosec/onsof
codebehaveinexactlythesameway.
for value in range(0, 100):!
Programmingisfun!
Programmingisfun!
Programmingisfun!
…
! Notethatinthefor…inloopsabove,theloopbodyisexecutedfor
eachvalueintheseriesofnumbersdefinedbytherange()func/on.In
thebodyoftheloop,theloopvariabletakesoneachvalueofthe
seriesofnumbersdefinedbytherange()func/on,e.g.,
15
for number in range(3, 7):!
20
!print(number * 5)!
25
30
0
for value in range(0, 5):!
1
!print(value)!
2
3
4
CompSci101-PrinciplesofProgramming
9
CompSci101-PrinciplesofProgramming
Givetheoutput
10
Completetheloops
! Completethefor…inrange()loopsothattheoutputis:
def print_output():!
!total = 0!
!for number in range(9, 20):!
! !if number % 2 == 0 or number % 3 == 0:!
! ! ! total = total + 1!
!
!print(total)!
!
!
def main():!
!
!show_output()!
!
!
main()!
CompSci101-PrinciplesofProgramming
71013161922!
for
in
!print(number, end = " ")!
!
print()!
! Completethefor…inrange()loopsothattheoutputis:
302520151050-5-10!
for
in
!print(value, end = " ")!
!
print()!
def double_each_year(start_amt, num_years):!
!
!
!
def main():!
! print("After 4 years:", double_each_year(24, 4))!
!print("After 3 years:", double_each_year(235, 3))!
!print("After 5 years:", double_each_year(15, 5))!
!
main()!
StarCngwith:24
1:48
2:96
3:192
4:384
AYer4years:384
CompSci101-PrinciplesofProgramming
StarCngwith:235
1:470
2:940
3:1880
AYer3years:1880
StarCngwith:15
1:30
2:60
3:120
4:240
5:480
AYer5years:480!
12
Completethefunc/on
! Usingafor…inrange()loopcompletetheprint_series()
func/onwhichprintsaseriesofnumbersstar/ngfromthe
parametervalue,start_num.Thesecondnumberprintedisthe
firstnumberplus1,thethirdnumberisthesecondnumberplus2,
thefourthnumberisthethirdnumberplus3,andsoon,e.g.,a
seriesof8numbersstar/ngfromthenumber2is:
:!
11
Completethefunc/on
! Anamountdoubleseachyear.Usingafor…inrange()
loopcompletethedouble_each_year()
func/onwhichprintsthegrowthoftheparameter,
(start_amt) forthegivennumberofyears
(num_years).Thefirstlineprintedbythefunc/on
isthestar/ngamount.
Eachlineoftheoutputisnumberedstar/ngfromthe
number1.Thefunc/onreturnsthefinalamount.
:!
235812172330
+1 +2 +3 +4 +5 +6 +7
def print_series(start_num, how_many):!
!
!
!
!
def main():!
!print_series(2, 8)!
!print_series(5, 12)!
!print_series(16, 9)!
!
!
main()!
235812172330
568111520263341506071
161719222631374452!
CompSci101-PrinciplesofProgramming
13
CompSci101-PrinciplesofProgramming
whileloopvsfor…inloops
! Counter-controlledwhileloopscanbeconvertedintofor…inrange()
loopsandviceversa.
count = 0!
while count < 100:!
!print("Programming is fun!")!
!count = count + 1!
for count in range(0, 100):!
!print("Programming is fun!")!
!
! Notallwhileloopscanbeexpressedusingafor…inrange(…)loop
(onlytheonesforwhichweknowexactlyhowmany/mestheloop
bodyistobeexecuted).
! Allfor…inrange()loopscanbeexpressedaswhileloops.
CompSci101-PrinciplesofProgramming
Convert-whileloopfor…inloop
! Convertthefollowingwhileloopintoafor…inrange()loop:
counter = 12!
while counter < 260:!
!print(counter)!
!counter = counter + 10!
!
for num in range(45, 3, -5):!
!print(num * 2)!
!
!
top = 6!
bottom = 0!
count = 0!
total = 0!
!
while bottom < top:!
!count = count + 1!
!total = total + top + bottom!
!bottom = bottom + 2!
!!
print("count:", count,"sum:",total)!
!
!
!
!
!
!
CompSci101-PrinciplesofProgramming
Sameoutput?
count = 0!
total = 0!
!
for bottom in range(0, top + 1, 2):!
!count = count + 1!
!total = total + top + bottom!
!
print("count:",count,"sum:",total)!
!
!
!
! Convertthefollowingfor…inrange()loopintoawhileloop:
15
! Dothefollowingtwoloopsgivethesameoutput?Ifnot,whatis
thedifferenceinoutputandwhatisthechangewhichneedstobe
madeifIwouldliketheoutputtobethesame?
top = 6!
14
16
Completethefunc/on
! Aperfectnumberisanintegerthatisequaltothesumofitsdivisors
(including1,excludingthenumberitself),e.g.,28=1+2+4+7+14.
Completetheget_sum_of_divisors()func/onusingafor…in
range()loopfortheitera/on.
def get_sum_of_divisors(number):!
!
!
def check_perfection(number):!
!if number == get_sum_of_divisors(number):!
!
!print(number, "is a perfect number")!
!else:!
!
!print(number, "is NOT a perfect number")!
!
def main():!
!check_perfection(28)
!!
28isaperfectnumber
!check_perfection(54)
!
!! 54isNOTaperfectnumber
!check_perfection(496)!
496isaperfectnumber!
!
main()!
CompSci101-PrinciplesofProgramming
17
CompSci101-PrinciplesofProgramming
Completethefunc/on
! Theget_series_sum()func/onreturnsthesumofthedesired
numberoftermsoftheseries: e.g., get_series_sum(4)returnsthesumofonehalfplusone
quarterplusoneeighthplusonesixteenth.Completethefunc/on
def get_series_sum(num_terms):!
Terms:1,sum:0.5
!
Terms:2,sum:0.75
!
Terms:3,sum:0.875
!
Terms:4,sum:0.9375
!
Terms:5,sum:0.9688
!
Terms:6,sum:0.9844
!
Terms:7,sum:0.9922
!
Terms:8,sum:0.9961
def main():!
Terms:9,sum:0.998!
!for num in range(1, 10):!
!
!comment = "Terms: " + str(num) + ", sum:"!
!
!print(comment, get_series_sum(num))!
main()!
18
Whichtouse,whilelooporfor…inloop?
Whichtypeofloopshouldyouuse?
! Awhileloopismoregeneral.Itcanbeusedtohandlerepe//onof
ablockofcodeagivennumberof/mesandalsotohandleuser
controlledrepe//ons,e.g.,whenthenumberof/mestheloopis
executeddependsontheuserinput(oronacondi/onwhich
dependsonarandomnumber).
! Afor…inrange()loopismorecompactanditisusedforrepea/nga
blockofcodeagivennumberof/mes.Itisusefulforprocessinga
blockofcodeforasequenceofvalues.
CompSci101-PrinciplesofProgramming
19
Summary
! InaPythonprogram:
!  thePythonrange()func/onisusedtodefineasequenceofvalues
!  afor…inrange()loopcanbeusedtoimplementcounter-controlledrepe//on
!  afor…inrange()loopcanbeconvertedintoawhileloopandviceversa
!  afor…inrange()loophasthefollowingsyntax:
for a_variable in range(
!statement1!
!statement2!
!…!
):!
CompSci101-PrinciplesofProgramming
20
ExamplesofPythonfeaturesusedinthislecture
def get_divisor_sum(number):!
! !div_sum = 1!
! !middle_num = number // 2!
! !for num_to_check in range(2, middle_num + 1):!
! ! !if number % num_to_check == 0:!
! ! ! !div_sum = div_sum + num_to_check!
!!
! !return div_sum!
!
def fun_stuff():!
! !total = 0!
! !for number in range(9, 20):!
! ! !if number % 2 == 0 or number % 3 == 0:!
! ! ! !total += 1!
!
! !print(total)!