0

How would I loop this code to make it so that the user inputs the number of friends they have, their names, and in the end, the program will be able to output the information? This is what I have so far, but I believe it's incorrect.

Friends = int(input("Please enter number of friends")
for i in range(Friends):
    Name = input("Please enter friend number 1:")
3
  • 3
    Append the names to a list. BTW, your prompt will say friend number 1 for every friend. Commented Jun 1, 2018 at 6:26
  • Is there a way to make it say friend number 2 after a loop? Commented Jun 1, 2018 at 6:28
  • 1
    These are all things you should learn from a Python tutorial. Commented Jun 1, 2018 at 6:30

4 Answers 4

2

Append each name to a list, then print the list. And use string formatting to put an appropriate number in the prompt.

friendList = []
Friends = int(input("Please enter number of friends")
for i in range(Friends):
    Name = input("Please enter friend number %d: " % (i+1))
    friendList.append(Name)
print(friendList)
Sign up to request clarification or add additional context in comments.

Comments

0

Loop using the number of friends, and store the name for each of them:

friend_count = int(input("Please enter number of friends: "))
friend_list = []
for friend_index in range(friend_count):
    name = input("Please enter friend number {}: ".format(friend_index + 1))
    friend_list.append(name)

print(friend_list)

Comments

0

Here a try using list comprehension:

Friends = int(input("Please enter number of friends :"))
Names = [input("Please enter friend number {}:".format(i)) for i in range(1,Friends+1)]
print(Names)

Comments

0

You can use raw_input, from the documentation

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.

Code

name_array = list()
num_friends = raw_input("Please enter number of friends:")
print 'Enter Name(s): '
for i in range(int(num_friends)):
    n = raw_input("Name :")
    name_array.append((n))
print 'Names: ',name_array

Comments

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.