python - Printing from a dictionary -
for school homework assignment, have write code following:
write program test knowledge of scientific names of animals. program should read in these scientific animal names animals.txt , ask user multiple lines of input. example animals.txt shown below:
arachnocampa luminosa,glow worm pongo abelii,sumatran orang-utan felis lynx,lynx spheniscus humboldti,humboldt penguin
animals.txt contain 0 or more lines, each line describing animal. each line contains 2 values, separated comma (,). left hand side of comma contains scientific name of animal, , right hand side of comma contains common name animal.
your program should read in these scientific animal names animals.txt , ask user multiple lines of input. each time, program should ask user enter scientific name of animal. if scientific name exists in data read in animals.txt, program should print out common name animal. otherwise, if scientific name unknown, program should print out not know animal. example:
scientific name: spheniscus humboldti that's humboldt penguin! scientific name: callithrix pygmaea don't know animal. scientific name: arachnocampa luminosa that's glow worm! scientific name:
below code i've written far. guys can see in example, if animal in list, should print out common name of animal (not scientific one). when run code, prints out correctly first 2 in teh example, when input 'arachnocampa luminosa', gives out 'that's humbolt penguin'.
animals = {} in open('animals.txt'): sname, cname = i.split(',') animals[sname] = cname x = input('scientific name: ') while x: if x in animals: print("that's " + cname.rstrip() + "!") else: print("i don't know animal.") x = input('scientific name: ')
what doing wrong causes , how fix it?
you doing wrongly, printing last value read .txt
- cname
. should information common name scientific name dictionary. example -
while x: if x in animals: print("that's " + animals[x].rstrip() + "!")
also suggestions, not loop on file -
for in open('animals.txt'):
you should explicitly open , close file, can use with
statement here. example -
with open('animals.txt') f: in f: sname, cname = i.split(',') animals[sname] = cname
with
statement handle closing of file you, when block ends.
Comments
Post a Comment