简体   繁体   中英

Python skipping my if statement

For some reason, this code doesn't work:

def pyglatin(word):
    output = ""
    wordlenedit = len(word)-1
    wordlen = len(word)
    fixer = 0
    while fixer == 0:
        for i in word:
            if i == 'a' or i == 'e' or i == 'o' or i == 'i' or i == 'u':
                fixer = 1
            else:
                wordlenedit -= 1
    else:
        output = word[wordlenedit:wordlen:1] + '-' + word[0:wordlenedit:1] + 'ay'
        return output

To see the issues, click here . The problem appears to be that it's skipping the if statement that identifies vowels, but I'm not sure why. This results in some very odd outputs.

Your function does not work because you walk through the word, decrementing the splitting index for each consonant you encounter, starting at wordlenedit = len(word)-1 .

At the end of your for loop, wordlenedit is equal to (length of the word) - 1 - (number of consonants) . The function will only work if the first index of vowel in the word (starting at 0) is equal to the number of vowels - 1.

Also, the while loop is useless here, as you walk through the entire word in the for loop. It is even worse than that: the while loop will be an infinite loop if you have a word with no vowels (like "fly", as you don't check the "y")

This is a corrected version of your function, using the keyword break :

def pyglatin2(word):
    output = ""
    wordlenedit = 0
    wordlen = len(word)
    for l in word:
        if l == 'a' or l == 'e' or l == 'o' or l == 'i' or l == 'u':
            break
        else:
            wordlenedit += 1

    output = word[wordlenedit:wordlen:1] + '-' + word[0:wordlenedit:1] + 'ay'
    return output

However this function can be written in a much more concise/simple way, using Regular Expressions , like this:

import re
def pyglatin3(word):
    # Get the first index of one of these: a, e, i, o, u
    start = re.search("[aeiou]", word).start()

    # Split the word
    return word[start:] + "-" + word[0:start] + "ay"

If you want to do this without using regular expressions, the simplest way is to use enumerate :

def pyglatin(word):
    for i, ch in enumerate(word):
        if ch in 'aeiou':
            return word[i:] + '-' + word[:i] + 'ay'

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM