了解循环中的if语句

2024-10-17 06:31:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在通过Python课程学习Treehouse的一些例子,我很难理解下面的代码。你知道吗

据我所知,我们正在"You got this!"中循环。但是,我不确定if语句实际上在做什么;有人能给我解释一下吗?你知道吗

for letter in "You got this!":
    if letter in "oh":
        print(letter)

Tags: 代码inyouforif语句this例子
3条回答
for letter in "You got this!":

Will loop through every letter in the string:

first iteration: Y
second iteration: o
third iteration: u ....you get how this works

在每个循环(或迭代)期间,如果字母是“o”或“h”,它将打印该字母。你知道吗

letter in "oh"实际上只是letter in ['o', 'h']的一种(不易引起误解的)速记

所以它贯穿了“yougotthis”中的每个字母,如果字母是“o”或“h”,它就会打印出来。我在IDE中运行了代码,这就是我得出的结论。我的代码打印o o h

相关问题 更多 >