对于学校的家庭作业,我们必须编写一个代码来完成以下任务:
Write a program to test your knowledge of the scientific names of animals. Your program should read in these scientific animal names from animals.txt and then ask the user for multiple lines of input. An example animals.txt is shown below:
Arachnocampa luminosa,Glow Worm Pongo abelii,Sumatran Orang-utan Felis Lynx,Lynx Spheniscus Humboldti,Humboldt Penguin
animals.txt will contain zero or more lines, each line describing an animal. Each line contains two values, separated by a comma (,). The left hand side of the comma contains the scientific name of an animal, and the right hand side of the comma contains the common name for the animal.
Your program should read in these scientific animal names from animals.txt and then ask the user for multiple lines of input. Each time, your program should ask the user to enter a scientific name of an animal. If this scientific name exists in data you read in from animals.txt, your program should print out the common name for that animal. Otherwise, if the scientific name is unknown, your program should print out that it does not know that animal. For example:
Scientific name: Spheniscus Humboldti That's the Humboldt Penguin! Scientific name: Callithrix Pygmaea I don't know that animal. Scientific name: Arachnocampa luminosa That's the Glow Worm! Scientific name:
下面是我到目前为止写的代码。正如你们在示例中看到的,如果动物在列表中,那么它应该打印出动物的通用名称(而不是科学名称)。当我运行代码时,它会正确地打印出示例中前两个的代码,但是当我输入'arachnocampaluminosa'时,它会给出'That's the Humbolt Penguin'。你知道吗
animals = {}
for i in open('animals.txt'):
sName, cName = i.split(',')
animals[sName] = cName
x = input('Scientific name: ')
while x:
if x in animals:
print("That's the " + cName.rstrip() + "!")
else:
print("I don't know that animal.")
x = input('Scientific name: ')
我做错了什么导致这一点,我该如何修复它?你知道吗
如果这样做是错误的,那么总是打印从
.txt
-cName
读取的最后一个值。你应该从字典里得到关于学名的通用名的信息。示例-还有一些建议,像这样循环一个文件是不好的-
您应该显式地打开和关闭文件,您可以在这里使用
with
语句。示例-with
语句将在块结束时为您处理文件的关闭。你知道吗相关问题 更多 >
编程相关推荐