Where am I going wrong with Sentinel or break in this Python code -
okay program done keeps running. need figure out sentinel or break needs go. have far in python. program suppose read pres on list , print them. there slice removing first 2 , last two.then prints list size 6 , proceeds give me 6 pres in alpha reverse order. have working other repeating end indefinitely. there has while loop display elements in list returned playlist.
pres = ['kennedy','johnson','nixon','ford','carter','reagan',\ 'bush','clinton','bush','obama'] pres2 = pres[2:8] def main(): names in pres: print(names) pr3=playlist(pres2) while playlist !='6': pr3 in pres2: print(pr3) def playlist(pr): size = len(pr) print('list size now', size) pr.sort() pr.reverse() return pr main()
now should when run it.
kennedy johnson nixon ford carter reagan bush clinton bush obama list size 6 reagan nixon ford clinton carter bush
but instead after list size 6, last 6 presidents keeps repeating. , needs read vertically on own line.
it appears have problems understanding basics of programming. encourage read again courses had read.
nevertheless, here explanations:
playlist
function.while playlist !='6'
loop verifying function object not string. different, so. if want compare result of function, have call it:playlist(pr)
, execute function , return list can store in variable.your
playlist
function returninglist
object. why try compare'6'
? moreover,'6'
not length of list. string.6
length of list int.why use
while
loop since want 6 presidents being displayed once? not make sense. loop actions need repeated unknown number of times.as
pres2
slicedpres
@ beginning, length 6. length has never been higher, , assuming loop had been drafted, code inside never have been executed.when use
for
loop iterate trough list, variable written afterfor
used alias represents current object iterated list.for pr3 in pres2:
weird defined variable calledpr3
. if want display president inside list, usefor name in pr3
did before.
let me show enhanced version of function, hoping manage understand better how works:
def main(): # print 10 presidents name in pres: print(name) # print size of list contains 6 presidents # then, sort list, reverse , return # new list store pr3 pr3 = playlist(pres2) # print 6 reverse sorted presidents name in pr3: print(name)
did it? have absolutely no need use loop.
Comments
Post a Comment