Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does the ".upper" function in a for loop, makes all of the letters upper and then change it back once it enters another if statement inside?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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'.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading