a = input("Name of 1st Fruit: ")
b = input("Name of 2nd Fruit: ")
c = input("Name of 3rd Fruit: ")
d = input("Name of 4th Fruit: ")
e = input("Name of 5th Fruit: ")
f = input("Name of 6th Fruit: ")
l = (a,b,c,d,e,f)
print(l)
编写一个程序,将七个水果存储在用户输入的列表中...... 这里我们使用输入函数输入七个水果的名称,我们必须将名称存储在一个列表中。 之后我们要做什么?
正如 @azro 在评论中提到的,最好循环并直接存储到列表中,而不是创建 7 个不同的变量,例如:
fruits = []
for i in range(1,8):
fruits.append(input(f"Name of Fruit {i}: "))
print(fruits)
结果:
Name of Fruit 1: Melon
Name of Fruit 2: Apple
Name of Fruit 3: Orange
Name of Fruit 4: Banana
Name of Fruit 5: Citrus
Name of Fruit 6: Plum
Name of Fruit 7: Mandarin
['Melon', 'Apple', 'Orange', 'Banana', 'Citrus', 'Plum', 'Mandarin']
您可以使用for循环来避免重复代码。
append
方法会将每个水果添加到水果列表中。
fruits = []
for i in range(7):
fruit = input("Name of Fruit: ")
fruits.append(fruit)
print(fruits)
list = []
v = ["1st", '2nd', '3rd', '4th', '5th', '6th', '7th']
for i in v:
a = input("Enter name of " + v[i]+"fruit:")
list.append(a)
print(list)
你应该在for循环和
append
的帮助下直接将它存储在列表中,我按照你需要的方式做了它。
这是一个使用列表理解的简单单行代码。
fruits = [input(f'Enter Fruit {x} \n') for x in range(1, 8)]
与
while
循环交替,将 7 个输入存储到列表中
fruits = list()
while len(fruits) < 7: fruits += [input(f"Name of #{len(fruits)+1} Fruit: ")]
print(fruits)
输出:
Name of #1 Fruit: apple
Name of #2 Fruit: banana
Name of #3 Fruit: grape
Name of #4 Fruit: mango
Name of #5 Fruit: pear
Name of #6 Fruit: lemon
Name of #7 Fruit: lime
['apple', 'banana', 'grape', 'mango', 'pear', 'lemon', 'lime']
不是正确的答案,请给出问题的确切答案,我们提出的问题,结果不正确,请正确地完成您的工作,先生/女士