Home > Mobile >  I'm having serious problems understanding this particular concept of a "for loop"
I'm having serious problems understanding this particular concept of a "for loop"

Time:11-28

I'm sorry my question might seem dumb, I'm very new to programming in general. so in the program below, I'm finding it difficult to understand why the expression "translation = translation g" actually replaces the vowels with g.

def translate(phrase):
    translation = ""
    for letter in phrase:
        if letter in "AEIOUaeiou ":
            translation = translation   "g"
        else:
            translation = translation   letter
    return translation


print(translate(input("type the word you9 wish to translate: ")))

take for instance I have a code like this

translation = "dog"
print(translation   "g")

this expression should print out dogg. so why is the " " sign in the previous program performing a replace instead of an addition?

CodePudding user response:

Let's go from the start

The line for letter in phrase: means that every letter in a word will be processed. So if the input string, for example, is 'dog', it will iterate it three times, d, o, and g.

Next, the line

if letter in "AEIOUaeiou ":
    translation = translation   "g"

means that if a letter is a vowel, you will append a g to the translation, instead of the vowel in the letter. Continuing the example of input 'dog' as a string, when the letter 'o' is processed it will append 'g' to translation.

It seems that you want to append g to the end of the string, this code should work just fine.

ddef translate(phrase):
    translation = ""
    check_vowel = False
    for letter in phrase:
        if letter in "AEIOUaeiou ":
            check_vowel = True
        translation = translation   letter
    if check_vowel:
        translation = translation 'g'
    return translation


print(translate(input("type the word you9 wish to translate: ")))

The code will check if a vowel is in a string. If it is in a string, then it will change the bool variable check_vowel to True. Then it will append g to the end. By the way, this task could be accomplished easily by using regex

import re

input_word = input("type the word you9 wish to translate: ")

if re.search("[aiueoAIUEO]",input_word):
    input_word = input_word 'g'
print(input_word)

CodePudding user response:

Because of your else condition. The if condition is not satisfied so it goes to the else part where the value of translation is "" which is an empty string. Adding g with the empty string returns you g as simple as it is.

  • Related