-2

I am trying to create a program in python 3.4 that uses a list to store the names of some notable celebrities. I want to use a loop to prompt the user for the names and to add them to the list. When the user enters "done" the loop should stop. The program should then output the number of celebrities entered. Finally, the program should use another loop to display the celebrity names, each on its own line, and "done" should NOT be in the celebrities list

def main():
    with open("celeb1.txt", "w") as Celeb:

    def Celebrites():  

Celeb =  ["Johnny Depp', 'Gary Busey', 'Tommy Lee Jones"]:

#file for saving names.


#write the list to the file

.writelines(Celeb1.txt)
#close file
outfile.close()


main() 
Suresh Kamrushi
  • 15,627
  • 13
  • 75
  • 90

1 Answers1

0

Given below is the code you have asked for. If you can post your code we can look for errors in it.

lst = []
while(1):
    name = input("enter celebrity name:") # read name of celebrity
    if name == "done":
        break;
    else:
        lst.append(name) # add name to list
# len(list) to find length of list
print(len(lst))
# print names in loop
for item in lst:
    print(item)
Johny
  • 2,128
  • 3
  • 20
  • 33
  • It's a bad idea to use `list += [name]` -- use `list.append(name)` instead. Also, your `for` loop should just look like `for item in list: print(item)`. – rmunn Oct 02 '14 at 03:25
  • @rmunn can you tell me the reason to use `list.append(name)` instead of `list += name` – Johny Oct 02 '14 at 03:31
  • Short version: because the `+=` version is very easy to get wrong (for example, you got it wrong in your comment just now -- it should have been `list += [name]` instead of `list += name`). The `list.append(name)` version is clearer. – rmunn Oct 02 '14 at 03:37
  • Also, there are subtle differences between how `+=` behaves on lists and how it behaves with other values like integers. `i = i + 1` and `i += 1` are equivalent. But `list = list + [item]` and `list += [item]` are NOT equivalent, and this can be the source of much confusion and subtle bugs. See http://stackoverflow.com/q/2347265/2314532 and http://stackoverflow.com/q/15376509/2314532 for two examples of that confusion. Using `list.append(item)` is a much better habit to get into: using `+=` will end up biting you in the long run. – rmunn Oct 02 '14 at 03:40
  • Finally, one more comment: because the name `list` is used in Python for creating a new list from some other set of ordered values (e.g., if you have a tuple in a variable named `t`, you can convert it into a list by calling `list(t)`), it's a bad idea to name your own variables `list`, as then you no longer have access to Python's built-in `list` function. It's better to name your variables something like `lst`, or `thelist`, or `mylist`, or anything other than the word `list`. – rmunn Oct 02 '14 at 03:42
  • @rmunn Thnk you for ur comments. I have done the changes you have told. – Johny Oct 02 '14 at 03:47