[Tutor] repeat a sequence in range

Peter Otten __peter__ at web.de
Sun Feb 12 12:01:18 CET 2012


Michael Lewis wrote:

> I am trying to repeat a certain sequence in a range if a certain even
> occurs. Forgive me for not pasting my code; but I am not at the machine
> where it's saved.
> 
> Basically, I want to get user input and append that input to a list only
> if the input is not already in the list. I want to do this x amount of
> times, but if the user input is already in the list, then I want to repeat
> that step in range(x).
> 
> At the prompt, I want to ask the user for:
> 
> Name 1:
> Name 2:
> Name 3:
> etc....
>  but if the user input for Name 3 was the same as the user input for Name
> 2, then I want to ask the user again for Name 3 instead of continuing to
> Name 4.
> 
> How can I do this?

Well, you are describing the algorithm pretty clearly: keep asking for a 
name until the user enters a name that is not in the list of names already.
Here's a straightforward implementation:

>>> names = []
>>> for i in range(1, 4):
...     while True:
...             name = raw_input("Name %d: " % i)
...             if name not in names:
...                     names.append(name)
...                     break
...             print "Name %r already taken" % name
...
Name 1: Jack
Name 2: Jack
Name 'Jack' already taken
Name 2: Jack
Name 'Jack' already taken
Name 2: Jim
Name 3: Jack
Name 'Jack' already taken
Name 3: Jim
Name 'Jim' already taken
Name 3: Joe
>>> names
['Jack', 'Jim', 'Joe']




More information about the Tutor mailing list