Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

python - Value in an Output where it shouldn't be

I am trying to condition this output so that each string is printed and formatted equally with the exception of "sarah". I've got this to work with the wording of her output being unique as she has only 1 "favourite language". However, now her language "C" is also in Jen's favourite language list when it shouldn't be. I tried using an elif/else in place of the 2nd if and got an invalid syntax error. I don't know how this is happening, thanks.

favourite_languages = {
    "jen": ["python", "ruby"],
    "sarah": ["c"],
    "edward": ["ruby", "go"],
    "phil": ["python", "haskell"],
    }
    for name, languages in favourite_languages.items():
    if len(languages) != 1:
        print(f"
{name.title()}'s favourite languages are:")
    for language in languages:
        print(f"{language.title()}")
    if len(languages) == 1:
        print(f"
{name.title()}'s favourite language is:")
        print(f"{language.title()}")

output:

Jen's favourite languages are:
    Python
    Ruby
    C

Sarah's favourite language is:
    C

Edward's favourite languages are:
    Ruby
    Go

Phil's favourite languages are:
    Python
    Haskell

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would put the condition if len(languages) == 1 first. You can then use an else statement for the others. Also, when len(languages) == 1, you get the language name with languages[0] rather than language

for name, languages in favourite_languages.items():
    if len(languages) == 1:
        print(f"
{name.title()}'s favourite language is:")
        print(f"{languages[0].title()}")
    else:
         print(f"
{name.title()}'s favourite languages are:")
         for language in languages:
             print(f"{language.title()}")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...