I am a beginner in Python and I have written this simple code but there are some errors that I could not resolve 🙁
Please can someone help me ?
//initialization
str = None
var = None
def setvar(val):
""" Sets the global variable "var" to the value in 'val' """
if val:
print "setting variable 'var' to '$val'" // we want to print the value of 'val'
else:
print "un-setting variable 'var'"
var = val
return
if __name__ == 'main':
try:
setvar(" hello world! ") // use this function to set the 'var' variable
var.strip() // we want the leading and trailing spaces removed
print str(var)
except:
print "something went wrong"
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
setvarshould be indented from thedef. 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 thanmain, in those situations where you’re running this script.And, finally, you have made
stra null variable so you can’t call it like a function.The following works fine:
One other thing which may or may not be a problem. If you want to print the value of
valin that firstprintstatement, you don’t use$val. Instead, you could have something like: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 🙂