2

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.
admdrew
  • 3,790
  • 4
  • 27
  • 39
keyx
  • 567
  • 1
  • 4
  • 5

2 Answers2

2

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 !

Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • @keyx: that's because you never assign the result of the `lower()` function to anything. – Martijn Pieters Dec 10 '14 at 22:20
  • Ok, I see that your way will return my sentence with lower letters. Works. But I just wanted to change the string example to the lower version of that string (example.lower()). What's the way to do that? You code will also result in example unchanged (check print(example))! – keyx Dec 10 '14 at 22:24
  • @keyx do you want to change it inside the function globally ? – Mazdak Dec 10 '14 at 22:27
  • @Kasra: Yes, I think you just found my problem. I wanted to change it forever. With the function. This seems to be a no-go / not possible / against the rules? :D – keyx Dec 10 '14 at 22:29
  • 2
    @keyx, strings are immutable so you cannot change the string globally, you would have to reassign example to the output of lower – Padraic Cunningham Dec 10 '14 at 22:30
  • Tanks @PadraicCunningham . – Mazdak Dec 10 '14 at 22:31
  • Thank you all, I think that helped doing one of the first programming steps. ;) – keyx Dec 10 '14 at 22:34
0

Use built in functions, directly:

print example.lower()

Don't wrap it or reinvent it !

meda
  • 45,103
  • 14
  • 92
  • 122