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