Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
569 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...