godlikesuperbob 发表于 2022-4-5 20:02:45

keys()

favorite_language = {"jen":"python","sarah":"c","edward":"ruby","phil":"python"}
friend = ["phil","sarah"]
for a in favorite_language.keys():
    print(f"Hi {a.title()}")

    if a in friend:
      language = favorite_language.title()
      print(f"\t{a.title()}, I see you love {b}!")

Hi Jen.
Hi Sarah.
Sarah, I see you love Python!
Hi Edward
Hi Phil
Phil, I see you love Python!

这里的Python应该是C才对,为什么是Python? 貌似是最后一行语句出问题 print(f"\t{a.title()}, I see you love {b}!"),我把那个b改成language就对了,不知道为什么?不是说键与值的变量名随便起吗?

isdkz 发表于 2022-4-5 20:05:55

你那里写 b 是会报错的吧,b 变量根本就不存在

python爱好者. 发表于 2022-4-5 20:06:49

哪里定义了 b?

godlikesuperbob 发表于 2022-4-5 20:28:33

isdkz 发表于 2022-4-5 20:05
你那里写 b 是会报错的吧,b 变量根本就不存在

没有报错,我run module之后的结构是
favorite_language = {"jen":"python","sarah":"c","edward":"ruby","phil":"python"}
friend = ["phil","sarah"]
for a in favorite_language.keys():
    print(f"Hi {a.title()}")

    if a in friend:
      language = favorite_language.title()
      print(f"\t{a.title()}, I see you love {b}!")
运算结果:
Hi Jen
Hi Sarah
        Sarah, I see you love python!
Hi Edward
Hi Phil
        Phil, I see you love python!

godlikesuperbob 发表于 2022-4-5 20:31:56

python爱好者. 发表于 2022-4-5 20:06
哪里定义了 b?

我前一个代码块里a,b也没定义,但是结果出来,所以我试了下这个代码块结果这个代码块出了问题,不知道为什么?
favorite_language = {"jen":"python","sarah":"c","edward":"ruby","phil":"python"}
for a,b in favorite_language.items():
    print(f"{a.title()} is favorite language {b.title()}")
运算结果:
Jen's favorite is Python.
Sarah's favorite is C.
Edward's favorite is Ruby.
Phil's favorite is Python.         这个a,b我没定义,但是结果却能在run module后出来

isdkz 发表于 2022-4-5 20:38:29

godlikesuperbob 发表于 2022-4-5 20:28
没有报错,我run module之后的结构是
favorite_language = {"jen":"python","sarah":"c","edward":"ruby ...

你用的是 pychram ?如果是 pychram 的话有可能你执行的是上一次的代码

godlikesuperbob 发表于 2022-4-5 20:48:29

我懂了
波 = {"jen":"python","sarah":"c","edward":"ruby","phil":"python"}
friend = ["phil","sarah"]
for a in 波.keys():
    print(f"Hi {a.title()}")

    if a in friend: #意思是如果a在friend里就执行
      language = 波.title()
      print(f"\t{a.title()}, I see you love {language}!")   这里应该是language才对{:10_256:}
页: [1]
查看完整版本: keys()