Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
511 views
in Technique[技术] by (71.8m points)

if statement - Issues with a if/else loop in Python

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'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'):

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...