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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With