The most common answer to 8.4.4 How Many Names? is:
nn = int(input(“How many names do you have?:”))
namelist = []
for i in range (nn):
name = input(“Name:”)
namelist.append(name)
print (“First name:” + namelist[0])
print (“Middle names:” + str(namelist[1:-1]))
print (“Last name:” + namelist[-1])
This script correctly collects a series of names based on the user’s input, then identifies and prints the first name, any middle names, and the last name separately.
To ensure compatibility with Python syntax, let’s adjust the quotation marks to standard ASCII characters:
nn = int(input("How many names do you have?: "))
namelist = []
for i in range(nn):
name = input("Name: ")
namelist.append(name)
print("First name: " + namelist[0])
# Convert the list of middle names to a string, separated by spaces for readability
middle_names = ' '.join(namelist[1:-1])
print("Middle names: " + middle_names)
print("Last name: " + namelist[-1])
This script:
- Prompts the user for the total number of names they have.
- Iterates that many times, each time appending the provided name to
namelist
. - Prints the first name directly.
- Joins any middle names (i.e., all names except the first and last) into a single string separated by spaces before printing. This approach assumes there may be more than one middle name.
- Prints the last name directly.
Note: This approach assumes the user has at least two names (a first and last name). If there’s a possibility of users having only one name, you might want to add checks to handle such cases gracefully.