Get a list of names as input from the user and make the first letters uppercase and print each word as a list?

Question:

Like so:

n = int(input("Enter total number of names:"))

Name = []

print("n Enter names: ")

for i in range(0, n):
   x = input()
Name.append(x)

print("n Names are:")

for i in range(0, n):

    print(Name[i].capitalize())

But getting an index error

list index out of range

Asked By: preeti

||

Answers:

Name.append(x) is outside loop , fix the indentation and you will be fine :

n = int(input("Enter total number of names:"))

Name = []

print("n Enter names: ")

for i in range(0, n):
    x = input()
    Name.append(x)

print("n Names are:")

for i in range(0, n):
    print(Name[i].capitalize())
Answered By: eshirvana

@eshirvana has already explained the indentation issue, but there is no need to iterate this way.

for i in range(0, n):
    print(Name[i].capitalize())

Can be written as:

for n in Name:
    print(n.capitalize())

Also, you don’t need to write range(0, n). If you only specify n, you will get the same behavior: range(n).

And thirdly, you can use a list comprehension to generate your list of names. Name is a poor name for this as it isn’t plural and by convention variable names in Python start with a lowercase letter.

names = [input() for _ in range(n)]

We use _ rather than something like i because this value doesn’t matter.

Answered By: Chris

You can use this method:

lst = []

lst = [element.capitalize() for element in input("Enter the list name : ").split()]

print(lst)

screenshot of code and output

Answered By: CHIRAG SHARMA

Run this it will give the proper value you want:

n = int(input("Enter total number of names:"))

Name = []

list = input ("n Enter names: ").split()

for i in range(0, n):
    x = input()
    Name.append(x)

for i in range(0, n):
    print(list[i].capitalize())
Answered By: CHIRAG SHARMA
n = int(input("Enter total number of names: "))

Name = []

print("Enter names: ")
for i in range(0, n):
    x = input()
    Name.append(x)

print("Names are: ")
for i in Name:
    print(list(i[0].upper() + i[1:]))
Answered By: Yash Gurjar
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.