I seem to be missing a crucial piece here. - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


I seem to be missing a crucial piece here.

kratosaurion7kratosaurion7 Posts: 3Member
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:
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.

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 :(


  • blemidonblemidon Posts: 22Member
    You can declare a variable with None value (It's the same as NULL in c), it means 'Nothing':
    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-
  • kratosaurion7kratosaurion7 Posts: 3Member
    Nice, it worked perfectly ! I wonder why no one bother to explain this stuff in every beginner's book I read >.^ Ah well.
  • blemidonblemidon Posts: 22Member
    Using global vars for getting data from a function is not the preferred way.

    You can try:

    name = None

    def getUsrName():
    name = 'someone'
    return name

    name = getUsrName()

    It's nicer.

    Imre Horvath
  • blemidonblemidon Posts: 22Member
    This post has been deleted.
  • acetechcnacetechcn Posts: 28Member
    This post has been deleted.
Sign In or Register to comment.