I am trying to make this Pig Latin translator in Python and it was working well until I tried to downsize it a bit.
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?
CODE:
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.
Currently, your if condition is evaluated as: -
if (low_original[0] == 'a') or 'e' or 'i' or 'o' or 'u':
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
.
You should do it like this: -
if low_original[0] in 'aeiou':
or: -
if low_original[0] in ('a', 'e', 'i', 'o', 'u'):
You should replace the string:
if low_original[0] == 'a' or 'e' or 'i' or 'o' or 'u':
with:
if low_original[0] in ('a', 'e', 'i', 'o', 'u'):
The if is alwasys returning True!
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] in ['a' , 'e' , 'i' , 'o' , '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'
The problem is in 'if low_original[0] == 'a' or 'e' or 'i' or 'o' or 'u':' - first is not pythonic second is not giving you not what you expect.
Try to update your code to:
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] in ('a', 'e', 'i', 'o', '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'
将if语句替换为
if low_original[0] in ['a', 'e', 'i', 'o', 'u']
The condition in this if
will always evaluate to True
.
if low_original[0] == 'a' or 'e' or 'i' or 'o' or 'u':
print "vowel"
pyg_vowel = low_original + pyg
print pyg_vowel
It's the same as if (low_original[0] == 'a') or 'e' or 'i' or 'o' or 'u'
You should use something like if low_original[0] in 'aeiou'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.