在 for 循环中嵌入 or 语句的 if 语句遇到问题
Having trouble with an if statement with an or statement embedded in a for loop
random_characters = "adak"
for letter in random_characters:
print(letter)
if letter == "a":
print("Vowel")
...作为输出发出:
a
Vowel
d
a
Vowel
k
如果我在 if 语句中只包含一个字母,代码运行正常。但是,如果我通过 or 语句再添加一个...
a
Vowel
d
Vowel
a
Vowel
k
Vowel
每次迭代后打印“元音”。
我要从字里行间看出你犯了一个很常见的错误:
if letter == "a" or "e":
因为这会产生您看到的结果。原因是,即解释为
if (letter == "a") or "e":
并且由于“e”始终为 True,因此始终采用 if
。如果要与多个字母进行比较,请使用 in
:
if letter in ("a","e","i","o","u"):
尽管在这种情况下,您也可以这样写:
if letter in "aeiuo":
random_characters = "adak"
for letter in random_characters:
print(letter)
if letter == "a":
print("Vowel")
...作为输出发出:
a
Vowel
d
a
Vowel
k
如果我在 if 语句中只包含一个字母,代码运行正常。但是,如果我通过 or 语句再添加一个...
a
Vowel
d
Vowel
a
Vowel
k
Vowel
每次迭代后打印“元音”。
我要从字里行间看出你犯了一个很常见的错误:
if letter == "a" or "e":
因为这会产生您看到的结果。原因是,即解释为
if (letter == "a") or "e":
并且由于“e”始终为 True,因此始终采用 if
。如果要与多个字母进行比较,请使用 in
:
if letter in ("a","e","i","o","u"):
尽管在这种情况下,您也可以这样写:
if letter in "aeiuo":