Hi everyone, this is my first post here. I've started python a few days ago and having programmed in VB for a couple years I'm fooled by this new language. There are a couple of concepts that I may be missing. I'm reading "A Byte of Python" which is a very good book, but I don't know why the author did not answer those questions in his book.
1) When I declare a variable in the global field (which I apparently HAVE to give it a value, even if I am only going to decide what value to assign later in the program) and when I modify it from a function it stays the same. Here is an example:
[code]
name = ""
#The variable that I want to use later
def getUsrName():
name = raw_input("Please enter your name.
Choice: ")
#This is where I assign it a value, but it doesn't modify the global one. Instead working on its own copy.
greetUsr(name)
#The workaround I found is to link functions with functions, instead of going through each one in the global field.
[/code]
Also, is it possible to declare a variable but not give it a value ? Because if the user chooses the value of the variable I have to do Value = raw_input("Choose a value") at the declaration time, which is inconvenient.
Any way around those problems?
* I call "Global Field" the place that the code is resting outside every function. I don't know the proper name for this yet
Comments
name = None
for tuples, dirs, arrays you can do this:
t = ()
d = {}
a = []
If you want to change a global var from function, use global:
name = None # it's empty, but declared
def getUsrName():
global name
name = 'someone'
This changes the global name to 'someone'
Hope this helps:
Imre Horvath
Regards: -blemidon-
You can try:
name = None
def getUsrName():
name = 'someone'
return name
name = getUsrName()
It's nicer.
Regards:
Imre Horvath