1

I'm somewhat new to python - I at least thought I had a solid understanding of the syntax but can't seem to figure out why this function does not work.

I want to write a function to capitalize the letters of a string.

string = 'Bryan'

def caps(word):
    word.upper()

caps(string)

What am I not understanding here? Seems basic to me but can't figure it out. Any help would be appreciated!

5 Answers 5

6

You need to specify a return explicitly.

replace

word.upper()

with

return word.upper()

If no return statement is specified, None is returned by default, Hence the result.

string = 'Bryan'

def caps(word):
    return word.upper()

returning_value = caps(string) #Note that you need to catch the returning the value. 
print returning_value
Sign up to request clarification or add additional context in comments.

Comments

3

You need to do two things:

  1. Because str.upper returns an uppercase copy of the string on which the method was called, you need to return word.upper() from function caps and then

  2. Reassign the variable string to that return value.

Here is how your script should look:

string = 'Bryan'

def caps(word):
    return word.upper()

string = caps(string)

print string  # Print the new uppercased string

Demo:

>>> string = 'Bryan'
>>> def caps(word):
...     return word.upper()
...
>>> string = caps(string)
>>> print string
BRYAN
>>>

Comments

1
string = 'Bryan'

def caps(word):
    word.upper()

caps(string)

I think you are missing a print command.

def caps(word):
        print word.upper()

If you want value back in a variable then you will have to return the value in function and assign it to a variable.

def caps(word):
        return word.upper()

string = caps(string)

Comments

1

You have to remember to ask yourself, what do I want this function to do? In many cases, you might want it to give you the result. eg return

string = 'Bryan'

def caps(word):
    return word.upper()

newstring = caps(string)
print newstring

In some cases you may just want the function to do what you were going to do anyway.

string = 'Bryan'

def pcaps(word):
    print word.upper()

pcaps(string)

Comments

0

This can also work too. You can assign the word.upper() to a variable and still call it word.

def caps(word):

 word = word.upper()

 return word

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.