简体   繁体   English

如何在 CodeHS 8.4.4: How Many Names 中打印名称?

[英]How do I print the names in CodeHS 8.4.4: How Many Names?

This is what I'm supposed to do:这是我应该做的:

The first part of this exercise is the same as the first part of How Many Names?本练习的第一部分与有多少个名字的第一部分相同? in the Control Flow module.在控制流模块中。

Some people have just a first name and a last name.有些人只有名字和姓氏。 Some people also have a middle name.有些人也有中间名。 Some people have five middle names.有些人有五个中间名。

Write a program that asks the user how many names they have.编写一个程序,询问用户他们有多少个名字。 (If they have a first name, two middle names, and a last name, for example, they would type 4.) Then, using a for loop, ask the user for each of their names. (例如,如果他们有一个名字、两个中间名和一个姓氏,他们将输入 4。)然后,使用for循环,向用户询问他们的每个名字。 Store the names in a list.将名称存储在列表中。

Then, use slices to separately print the person's first name, middle name(s), and last name.然后,使用切片分别打印此人的名字、中间名和姓氏。

An example run of your program might look like this:程序的运行示例可能如下所示:

Number of names: 4
Name: Nora
Name: Stanton
Name: Blatch
Name: Barney
First name: Nora
Middle name(s): ['Stanton', 'Blatch']
Last name: Barney
Your program should work regardless of how many middle names the person has!

Hints提示

The index -1 may come in handy in a couple places.索引 -1 可能在几个地方派上用场。 You'll need to use the str function to print the middle names.您需要使用str函数来打印中间名。

I have found the correct answer to this problem.我找到了这个问题的正确答案。 Here it is:这里是:

name_amount = int(input("How many names do you have? "))
namelist = []
index = 0
for i in range (name_amount):
    name = input("Name: ")
    namelist.append(name)
    index += 1
print "First name: " + namelist[0]
print "Middle names: " + str(namelist[1:-1])
print "Last name: " + namelist[-1]

You issue is in this line here:您的问题在此行中:

print "Middle names: " + namelist[1:-1]

When you have more than 1 middle name namelist[1:-1] will be a list at least 2 long.当您有超过 1 个中间名时, namelist[1:-1]将是一个至少 2 长的列表。 The + you use in this line is trying to concatenate the string "Middle Names: " with the list ["middlename1","middlename2"] and Python doesn't know what to do here so it thrown the exception:您在这一行中使用的+试图将字符串"Middle Names: "与列表["middlename1","middlename2"] ,Python 不知道在这里做什么,所以它抛出了异常:

TypeError: cannot concatenate 'str' and 'list' objects

To fix this and get the format you want for the middle names ( Middle name(s): ['Stanton', 'Blatch'] ) you need to tell python to turn the list into a string with str() so your line should be:要解决此问题并获得所需的中间名格式( Middle name(s): ['Stanton', 'Blatch'] ),您需要告诉 python 使用str()将列表转换为字符串,以便您的行应该是:

print "Middle names: " + str(namelist[1:-1])

This will force python to turn your list into a string that can be concatenated and printed.这将强制 python 将您的列表转换为可以连接和打印的字符串。

还要在要打印的行周围添加括号,例如:

print("Middle names: " + str(namelist[1:-1]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM