Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add values in the list using for loop in python? [duplicate]

What I am trying to do here is to ask the user to enter any number and then ask the user to enter any names, then store this input in a list.

However, when I enter any number, it asks to enter name only one time and shows the output in list:

def main():
    # a = 4
    a = input("Enter number of players: ")
    tmplist = []
    i = 1
    for i in a:
        pl = input("Enter name: " )
        tmplist.append(pl)

    print(tmplist)

if __name__== "__main__": 
    main()

output:

Enter number of players: 5
Enter name: Tess
['Tess']

What I want is, for loop should run 5 times and user entered 5 values get stored in a list.

like image 661
PRK Avatar asked Oct 19 '15 05:10

PRK


People also ask

How do you add a repeated element to a list in Python?

Using the * Operator The * operator can also be used to repeat elements of a list. When we multiply a list with any number using the * operator, it repeats the elements of the given list.

Can you have duplicate values in a list Python?

A Python list can also contain duplicates, and it can also contain multiple elements of different data types. This way, you can store integers, floating point numbers, positive or negatives, strings, and even boolean values in a list.


1 Answers

You need to convert the number of players to integer and then loop for that much amount of times, you can use the range() function for this . Example -

def main():
    num=int(input("Enter number of players: "))
    tmplist=[]
    for _ in range(num):
        pl=input("Enter name: " )
        tmplist.append(pl)

    print(tmplist)
like image 150
Anand S Kumar Avatar answered Sep 23 '22 06:09

Anand S Kumar