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)
write a program to store seven fruits in a list entered by the user... here we use input function to input the seven fruits name and we have to store the names in a list. after that, what we have to do?
CodePudding user response:
As mentioned by @azro in the comments, it's better to loop and store directly into a list instead of creating 7 different variables, for example:
fruits = []
for i in range(1,8):
fruits.append(input(f"Name of Fruit {i}: "))
print(fruits)
Result:
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']
CodePudding user response:
you can use a for loop to avoid repeating code. The append
method will add each fruit to the fruits list.
fruits = []
for i in range(7):
fruit = input("Name of Fruit: ")
fruits.append(fruit)
print(fruits)
CodePudding user response:
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)
you should directly store it in list with the help of for loop and append
and i made it how u needed it be.
CodePudding user response:
Here's a simple one liner using list comprehension.
fruits = [input(f'Enter Fruit {x} \n') for x in range(1, 8)]
CodePudding user response:
Alternate with while
loop to store 7 inputs to a list
fruits = list()
while len(fruits) < 7: fruits = [input(f"Name of #{len(fruits) 1} Fruit: ")]
print(fruits)
Output:
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']