[Tutor] Question

Prayash Bhuyan bhuyanprayash18 at gmail.com
Tue Apr 11 07:02:38 EDT 2023


Loop forever if the name is not in the list

On Tue, 11 Apr, 2023, 2:28 pm Alan Gauld, <learn2program at gmail.com> wrote:

> Forwarding to list, please always use ReplyAll when responding.
>
> On 11/04/2023 07:42, Prayash Bhuyan wrote:
> > group is just a variable where I am storing the randomly generated
> number
> >
> > import random
> > names=["ayush","bhargav","nayan","money","niju"]
> > counter=0
> > while True:
>
> This is not needed. You start the loop by going into the for loop then
> immediately exit the while loop. The while loop is not doing anything.
>
> >   for name in names:
> >     name=input("what is your name: ")
> >     name=name.casefold()
> >     group=random.randint(1,5)
> >     counter+=1
> >     if name in names and counter<=len(names):
> >       print(name,"your group is",group)
>
> The counter is not needed, you will only go round the loop as many times
> as there are names in the list, there is no need to count them or to
> check against the list size. counter will always be less than or equal
> to len(names).
>
> Also, you are generating the group number every time, not just if the
> name is in names. That's wasteful but does no harm.
>
>
> > name is in the list it should randomly generate a group number from 1-5
> > and then again promt the user for next name
>
> And thats what your code does.
>
> >  but if the name is no there
> > in the list it should repromt for the next name but in doing so it
> > shouldnot consider it to be a iteration of its own
>
> And this is not there. When the if test fails there is no else part to
> catch the error so your code just goes to the start of the next for loop
> iteration. You need to add an else clause.
>
> Something to consider is how often should it prompt if the name is not
> in names? Will it just offer one more chance or will it loop forever?
>
>
> > --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>


More information about the Tutor mailing list