Search code examples
pythoncaseletter

Function to create lower case words (convert upper to lower letters) doesn't work as expected


I don't see why the following Python code prints out a sentence containing UPPER letters... Please explain! :)

def lower(text):
    text = text.lower()

example = "This sentence has BIG LETTERS."
lower(example)
print(example)

Output will be:

This sentence has BIG LETTERS.

Solution

  • Your function doesn't return anything , you need to return the word :

    def lower(text):
        text = text.lower()
        return text
    

    Demo:

    >>> example = "This sentence has BIG LETTERS."
    >>> lower(example)
    'this sentence has big letters.'
    

    if you mean why the following doesn't work :

    lower(example)
    print(example)
    

    you need to know that variables inside the functions has local scope and with call lower(example) the example doesn't change globally !