【发布时间】:2017-03-21 09:57:02
【问题描述】:
除两件事外,此程序中的所有内容都按预期工作。如果您输入一个男孩名字,它将正确打印所有内容,除了它会添加打印行“(名字)未在前 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()
【问题讨论】:
-
打印
(boy) was not ranked in the top 100 girl names不是编程行为吗?因为 Python 的索引为 0,所以它减一。 -
我想是这样,但我不想这样。如果使用男孩名,则不应打印前 100 名女孩的行
标签: python python-3.x