0

I am finding it difficult to loop my raw_input over and over again until the right answer is entered (Im a noob)

here is the question:

write a Python program that takes in a user input as a String. While the String is not “John”, add every string entered to a list until “John” is entered. Then print out the list.

Example program run (what should show up in the python console when you run it):

Enter your name : <user enters Tim>
Enter your name : <user enters Mark>
Enter your name: <user enters John>
Incorrect names: [‘Tim’, ‘Mark’]

and this is my code:

answer = "John"

nameString = ['']

nameInput = raw_input("Enter a name")

if nameInput in answer:

    print nameString

else:

    nameString.append(nameInput)

I'm not entirely sure what code should be written to achieve this loop.

Mark Vergottini
  • 5
  • 1
  • 1
  • 4
  • 1
    Use `nameString = []` instead. Your version is a list with 1 empty string as the first element. Also you shoul use `if nameInput == answer:` because `answer` is not a list. – Kamejoin Oct 28 '15 at 19:15
  • 1
    You have the wrong order for the operands to `in` - it's `if needle in haystack` not `if haystack in needle`. – tripleee Oct 28 '15 at 19:21
  • http://sopython.com/canon/8/prompting-the-user-for-input-until-you-get-a-valid-response/ – tripleee Oct 28 '15 at 19:22

2 Answers2

0

Create an empty list like this:

nameString = [ ]

Use a loop to redundantly take input from the user.

If a certain condition met, break out from the loop with break statement.

Otherwise, as the nameInput is wrong, add it to the list.

A solution could be like below:

 nameString = []

 while(True):
     nameInput=raw_input("Enter a name")
     if nameInput!="john":
         nameString.append(nameInput)
     else:
         break

 print "Incorrect Names:" , ",".join(nameString)
Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57
0

You know you need to loop, but you're not sure how many times. This is a natural place to use a while loop.

answer = "John"
nameString = []

nameInput = raw_input("Enter a name")

while nameInput != answer:
    nameString.append(nameInput)
    print nameInput = raw_input("Enter a name")
print("Incorrect Names: ", nameString)
Alecg_O
  • 892
  • 1
  • 9
  • 19