[英]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 您可以使用来自文档的raw_input
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.
读取EOF时,将引发EOFError。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.