Issues with a if/else loop in Python

前端 未结 6 1846
萌比男神i
萌比男神i 2020-12-04 03:37

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 t

相关标签:
6条回答
  • 2020-12-04 04:21

    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'):
    
    0 讨论(0)
  • 2020-12-04 04:21

    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'
    
    0 讨论(0)
  • 2020-12-04 04:22

    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'):
    
    0 讨论(0)
  • 2020-12-04 04:22

    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'

    0 讨论(0)
  • 2020-12-04 04:26

    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'
    
    0 讨论(0)
  • 2020-12-04 04:36

    replace the if statement with

    if low_original[0] in ['a', 'e', 'i', 'o', 'u']
    
    0 讨论(0)
提交回复
热议问题