[Tutor] Noob to Python - Need help with Variables

lonetwin lonetwin@yahoo.com
Thu Jun 5 08:23:01 2003


Hey Tony,

On Thursday 05 June 2003 04:35 pm, Tony Stevenson wrote:
>  Hi All,
>
> I am completely new to programming, so I thought I would start with Python
> as it comes highly reccomended, and have seen it do some very smart
> things.
>
> Anyway, I am trying to re-write our somewhat painful DOS Batch File
> Logon Scripts.
>
> I am currently using   print os.environ["USERNAME"]   to obtain the
> username environment variable.
>
> Now I will be using this entry several times throughout the script, so I
> "thought" I would need to create a variable in python.  But after trying
> this
>
> >>> user = "print os.environ['USERNAME']"
> >>> print user
>
> This is what is returned....
>
>
> print os.environ['USERNAME']
>
>
>
> So I can see that the "variable"??? user, it not executing the print
> os.environ command.  Instead is it using it as a text entry.
 And that is correct, because by including the quotes you are telling python 
treat the contents within these quotes as a string.

Think about this -- what would happen if you were to say 

>>> print "os.environ['USERNAME']"
instead of 
>>> print os.environ["USERNAME"] 
as you say you have been using.
     ......Ok, so now we know that the quotes are unnecessary ...so should 
this work ??

>>> user = print os.environ["USERNAME"]
   File "<stdin>", line 1
    user = print os.environ["USERNAME"]
               ^
SyntaxError: invalid syntax
>>>

ummm ...apparently not. what could be wrong ?? well, python reads this as

>>> user =            print os.environ["USERNAME"]
       ^^^^^^^              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Assign to the           The  result of the statement print
variable user

which basically is one of the laws that most (all ??) programming languages 
follow - Evaluation occurs before assignment.
     However, in this case the 'print' statement does not *evaluate* anything, 
it just prints stuff, so, there is nothing to assign. So how do you assign 
something to a variable without having to evaluate anything. well ...you just 
go ahead and assign :)

>>> user = os.environ["USERNAME"]

HTH
Peace
Steve

-- 
Never be afraid to tell the world who you are.
                                     - Anonymous