I have written a basic program that outputs my friends’ favourite programming languages. I now need to tidy the grammar so that where a friend has only one favourite language, the output reads “favourite language is” instead of “favourite languages are”
I was advised to “check length of language list, if length 1 use singular form, if 2 or more use other form, set these to a single variable that can be dropped into the print statement” Unfortunately I have no idea how to do that.
for name, languages in favourite_languages.items():
print(f"\n{name.title()}'s favourite languages are:")
for language in languages:
print(f"\t{language.title()}")
I found this post due to me having the same issue. This is mentioned in Python Crash Course (3rd edition) page 109.
The other user helped me so many thanks to Steven.
Here’s my code which seems to work, perhaps someone could leave feedback if its wrong or there’s an easier way:
favourite_languages = {
'jen': ['python', 'rust'],
'sarah': ['c'],
'edward': ['rust', 'go'],
'phil': ['python', 'haskell']
}
for name, languages in favourite_languages.items():
if len(languages) == 1:
print (f"\n{name.title()} favourite language is:")
for language in languages:
print (f"\t{language.title()}")
else:
print (f"\n{name.title()} favourite languages are:")
for language in languages:
print (f"\t{language.title()}")
The 2 branches of the if statement end with the same for loop, so that could be moved out of the if statement like this:
for name, languages in favourite_languages.items():
if len(languages) == 1:
print (f"\n{name.title()} favourite language is:")
else:
print (f"\n{name.title()} favourite languages are:")
for language in languages:
print (f"\t{language.title()}")