Python 中的 if/else 循环问题 [英] Issues with a if/else loop in Python
问题描述
我正在尝试用 Python 制作这个 Pig 拉丁语翻译器,它运行良好,直到我试图缩小它的大小.
I am trying to make this Pig Latin translator in Python and it was working well until I tried to downsize it a bit.
有人可以看看这段代码并告诉我为什么,当我在开头输入一个没有元音的单词时,它仍然会在这个 if 语句中打印元音"代码?
Can someone please take a look at this code and tell me why, when I type in a word without a vowel at the beginning it will still print the "vowel" code in this if statement?
代码:
pyg = 'ay'
original = raw_input('Enter a word: ')
low_original = original.lower()
if len(low_original) > 0 and low_original.isalpha():
print low_original
if low_original[0] == 'a' or 'e' or 'i' or 'o' or 'u':
print "vowel"
pyg_vowel = low_original + pyg
print pyg_vowel
else:
print "consonant"
pyg_cons = low_original[1: ] + low_original[0] + pyg
print pyg_cons
else:
print 'empty'
推荐答案
您需要单独检查所有元音.
You need to do a check for all the vowels separately.
目前,您的 if 条件评估为:-
Currently, your if condition is evaluated as: -
if (low_original[0] == 'a') or 'e' or 'i' or 'o' or 'u':
or
返回其条件中的第一个真值,此处为 True
或 e
,具体取决于您的第一个条件是 True 还是不是.现在,由于 'e'
被评估为 True
,所以两个值都是 true
,因此您的条件将始终为 true代码>.
or
returns the first true value in its condition, which will either True
or e
here, depending upon your first condition is True or not. Now, since 'e'
is evaluated to True
, so both the values are true
, hence your condition will always be true
.
你应该这样做:-
if low_original[0] in 'aeiou':
或:-
if low_original[0] in ('a', 'e', 'i', 'o', 'u'):
这篇关于Python 中的 if/else 循环问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!