Python项目打印输出不正确,索引关闭一个

时间:2017-03-21 01:41:29

标签: python python-3.x

除了两件事之外,一切都在这个程序中有效。如果您输入一个男孩名称,它将正确打印所有内容,除非它会添加打印行"(名称)未被列入前100名女孩名称...."输入女孩名字时的结果相同。有关如何让它停止的任何想法?还有' pos'返回的是一个 - 我可以添加一个计数器来修复它吗?

 try:
        boyfile = open("boynames2014.txt", "r")
        girlfile = open("girlnames2014.txt", "r")
        boynames = [line.strip() for line in boyfile]   #read the content to a list
        girlnames = [line.strip() for line in girlfile] #read the content to a list

except IOError:
    print("Error: file not found")


#Input gender
#search names in lists

gender = input("Enter gender (boy/girl): ")
if gender == "boy" or gender == "girl":
    name = (input("Enter name to search for: "))
else:
    print("Invalid gender")


if name in boynames:
    pos = boynames.index(name)
    print(name, "was ranked #", pos, "in 2014 for boy names")
else:
    print(name, "was not ranked in the top 100 boy names for 2014")


if name in girlnames:
    pos = girlnames.index(name)
    print(name, "was ranked #", pos, "in 2014 for girl names")
else:
    print(name, "was not ranked in the top 100 girl names for 2014")



boyfile.close()
girlfile.close()

2 个答案:

答案 0 :(得分:0)

无论性别是什么,您都会针对nameboynames检查girlnames

我建议添加一个条件:

if gender == "boy":
    if name in boynames:
        pos = boynames.index(name)
        print(name, "was ranked #", pos, "in 2014 for boy names")
    else:
        print(name, "was not ranked in the top 100 boy names for 2014")

elif gender == "girl"    
    if name in girlnames:
        pos = girlnames.index(name)
        print(name, "was ranked #", pos, "in 2014 for girl names")
    else:
        print(name, "was not ranked in the top 100 girl names for 2014")

答案 1 :(得分:0)

您正在检查男孩和女孩的名字,无论性别如何,您可以添加另一个条件来检查gender

if gender == "boy" and name in boynames:
    pos = boynames.index(name) + 1
    print("{} was ranked #{} in 2014 for boy names".format(name, pos))
elif gender == "girl" and name in girlnames:
    pos = girlnames.index(name) + 1
    print("{} was ranked #{} in 2014 for girl names".format(name, pos))
else:
    print("{} was not ranked in the top 100 {} names for 2014".format(name, gender))

至于pos为1关,这是因为列表被索引为0。这意味着第一个项目从索引0开始,第二个项目从索引1开始,依此类推。因此,如果您的排名从#1开始,那么您只需要将其抵消1。

pos = boynames.index(name) + 1

最后我建议您在阅读后关闭try/except内的文件,因为您不在代码中的任何其他位置使用它们,因此无需将其打开。