简体   繁体   中英

How would I loop this on Python?

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:")

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)

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)

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM