strings in the global section

Tim Chase python.list at tim.thechases.com
Thu Oct 12 13:58:28 EDT 2006


Phoe6 wrote:
> I write a script:
> #!/usr/bin/python
> astring = "This is a String"
> 
> def fun1():
>         astring = "I modify it in fun1"
> def fun2():
>         astring = "I modify it in fun2"
> def main():
>         print astring
>         fun1()
>         print astring
>         fun2()
>         print astring
> if __name__ == '__main__':
>         main()
> 
> And I am expecting the output to be:
> This is a String
> I modify it in fun1
> I modify it in fun2
> 
> But it is not so. It always prints This is a String. astring declared
> outside all the functions, is not in global section and values be
> overwritten by functions accessing it?
> 
> - How is this working?
> - What should I do to overwrite the string variable in the global
> section within functions?

http://docs.python.org/ref/global.html

def fun2():
	global astring
	astring = 'hey, I've changed!'

-tkc








More information about the Python-list mailing list