Home > Software engineering >  Does the ".upper" function in a for loop, makes all of the letters upper and then change i
Does the ".upper" function in a for loop, makes all of the letters upper and then change i

Time:01-17

So I am following a Youtube guide about python coding and i'm just a little bit confused about the following code:

def translate(word):

    translation = ""

    for letter in word: 
        if letter.upper() in "AEIOU":
            if letter.islower():
                translation = translation   "r" 
            else:
                translation = translation   "R" 
        else:
            translation = translation   letter
    return translation

print(translate("Hello World"))
#will print out “Hrllr Wrld”`

so it's a translation function where it will change all the vowels in a string into the letter 'r'. The part which is not clear to me is here:

if letter.upper() in "AEIOU":
        if letter.islower():
            translation = translation   "r" 
        else:
            translation = translation   "R" `

Shouldn't it be that all the vowels will be change into a capitalized 'R' because of the function "letter.upper()" even if the vowel that was in the string is not capitalized? and once that happens then wouldn't it be that python will never enter the "if letter.islower():" if statement?

CodePudding user response:

letter.upper() does not change the value of letter variable. It simply returns a new (temporary and unnamed) variable that is an uppercase version of letter. You then test this new variable with in statement, but the letter variable is unchanged and can be used further.

For example, if letter was 'e', then letter.upper() returns 'E', but letter itself still remains 'e'.

CodePudding user response:

In the first line - "if letter.upper() in "AEIOU":" the upper() converts each letter to uppercase and returns it to "if" operator. However, it does not saves the result in variable "letter"

Hence in second line - "letter.islower()" always check for it's initial case.

Example:

word = "Hello"
for letter in word:
    if letter.upper() in "AEIOU":
        print('The value of variable letter is ->', letter)
        temp = letter.upper()
        print('The value of variable temp is', temp)
  • Related