0
empty_string = ''
string_1 = 'beta'

def sample(x):
    empty_string = empty_string + 'alpha'
    return x

why doesn't:

empty_string = 'alpha'

i'm confused why empty_string is still empty after i add to it in the function

1
  • @Ashwini's answer is good, however, it's usually better to make string functions return a new string, and the caller can update variables if they want. So def alphaize(s): return s + 'alpha' and then outside the function empty_string = alphaize('foo'). Commented Sep 24, 2012 at 21:38

1 Answer 1

5

use global empty_string inside function, then only you can modify a global variable:

def sample(x):
    global empty_string
    empty_string = empty_string + 'alpha'
    return x
Sign up to request clarification or add additional context in comments.

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.