Reputation: 1
I'm new to Python and just started learning Python at the end of January. I'm currently on page 110 of Python Crash Course (Chapter 6: Dictionaries). In the favorites languages program, I try to include an if statement inside of a dictionary's for loop to see each user has more than one favorite language with len(languages) method, then produce different results based on the user's number of languages. Here my code and the result:
**favorite_languages = {
'jen': ['python','c'],
'lucas': ['python'],
'veronica': ['c','ruby'],
'jack': ['haskel','go'],
}
for name, languages in favorite_languages.items():
if len(languages) == 1:
print(f"\n{name.title()}'s favorite language is : {language.title()}")
else:
print(f"\n{name.title()}'s favorite languages are: ")
for language in languages:
print(f"\t{language.title()}")**
I expected the result that if the user has a single favorite language, the code will print out:
"{user}'s favorite language is : {language.title()},
or else:
"{user}'s favorite languages are: {language.title()}"
And here is the result:
Jen's favorite languages are:
Python
C
Lucas's favorite language is : C
Veronica's favorite languages are:
C
Ruby
Jack's favorite languages are:
Haskel
Go
As far as I concerned, the code runs well, except that in Lucas's favorite language result was different. The result said Lucas's favorite language is C instead of Python like I wrote it in the program.
I would appreciate it if anyone helps me out on this.
Upvotes: 0
Views: 277
Reputation: 1
Problem solved! Correct code:
**favorite_languages = {
'jen': ['python', 'ruby'],
'sarah': ['c'],
'edward': ['ruby', 'go'],
'phil': ['python', 'haskell'],
}
for name, languages in favorite_languages.items():
if len(languages[0]) == 1:
print(f"\n{name.title()}'s favorite language is ")
else:
print(f"\n{name.title()}'s favorite language are: ")
for language in languages:
print(f"\t{language.title()}")**
Thanks everyone!
Upvotes: 0
Reputation: 49330
The only place you defined language
- singular - is when you loop through each language of someone who likes multiple languages. If Lucas had been the first in the list, it would've produced an error. As it is, language
at that point was still on Jen's latest favorite of C. To fix this, use languages[0]
when checking for a single favorite language.
Upvotes: 3