There are a few problems with your code sample.
First, assuming that you have faithfully preserved indentation when asking your question, it's all wrong. The body of setvar should be indented from the def. Please make sure you follow the PEP guidelines and use four spaces for each indentation level.
Secondly, comment markers in Python are # rather than //.
Next, if you want to affect a global variable within your function, you need to mark it so.
Fourth, var.strip() returns the new value, it doesn't operate in-place.
Also, the value of __name__ will be __main__ rather than main, in those situations where you're running this script.
And, finally, you have made str a null variable so you can't call it like a function.
The following works fine:
# initialization
var = None
def setvar(val):
""" Sets the global variable "var" to the value in 'val' """
global var
if val:
print "setting 'var' to '$val'" # we want to print the value of 'val'
else:
print "un-setting 'var'"
var = val
return
if __name__ == '__main__':
try:
setvar(" hello world! ") # use this function to set the 'var' variable
var = var.strip() # we want the leading and trailing spaces removed
print str(var)
except:
print "something went wrong"
One other thing which may or may not be a problem. If you want to print the value of val in that first print statement, you don't use $val. Instead, you could have something like:
print "setting variable 'var' to '%s'"%(val)
And, yes, I know you don't need the parentheses around a single value, that's just my coding style, and one less thing I have to remember :-)