0
# Let's create a file and write it to disk.
filename = "test.dat"
# Let's create some data:
done = 0
namelist = []
while not done:
    name = raw_input("Enter a name:")
    if type(name) == type(""):
        namelist.append(name)
    else:
        break

For the Python code above, I tried, but could not break from the while loop. It always asks me to "Enter a name:", whatever I input. How to break from the loop?

2
  • 3
    Input you receive from a user will always be string input unless you convert it. Commented Mar 18, 2012 at 15:33
  • To debug this, you could have added some print statements, like print name, repr(name), type(name), print type(""), print type(name) == type("") and so on, which would have shown the problem. You can seldom go wrong by strewing print statement around. Commented Mar 18, 2012 at 15:38

2 Answers 2

4
# Let's create a file and write it to disk.
filename = "test.dat"
# Let's create some data:
namelist = []
while True:
    name = raw_input("Enter a name:")
    if name:
        namelist.append(name)
    else:
        break

This breaks when entered nothing

Sign up to request clarification or add additional context in comments.

Comments

1

This is because raw_input always returns a string, i.e., type(name) == type("") is always true. Try:

while True:
    name = raw_input("Enter a name: ")
    if not name:
        break
    ...

1 Comment

Thank you both of youe! The code is fetched from other's webpage, so it is with bug!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.