[Tutor] global and local vaiables

Kent Johnson kent37 at tds.net
Mon Oct 24 03:19:51 CEST 2005


Jason wrote:
>   i know that when you define a variable in a function it is defined as 
> a local variable.
> and that when you type return variable it will set the value of that 
> variable to a global variable and that it will then exit the function

No, the return statement doesn't set a global variable, it sets the value that is returned from the function. The caller may assign this to a global variable or some other type of variable or ignore it. For example:

 >>> def foo():
 ...   x=3
 ...   return x
 ...

foo returns the value 3 but it isn't bound to any name:
 >>> foo()
3
 >>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'x' is not defined

We can give any name we want to the returned value:
 >>> y=foo()
 >>> y
3

Still no global x:
 >>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'x' is not defined

We can call foo() from another function and use the return value there:
 >>> def bar():
 ...   z=foo()
 ...   print z
 ...
 >>> bar()
3

No global x or z - they are local to the functions that use them:
 >>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'x' is not defined
 >>> y
3
 >>> z
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'z' is not defined

> but say i wanted to define variable x as a global variable and then do 
> something else in the function
> how would i do that?

Use the global statement if you must...usually it's better to find a solution that doesn't require global variables.
> 
> to be a bit more specific i have this function:
> 
>    1. |def sign_in(number,account,password):|
>    2.     if number.has_key(account) and number[account]==password:
>    3.         account = account+".txt"
>    4.         load_numbers(numbers,account)
>    5.         display_menu()
>    6.         return account
>    7.     else:
>    8.         print "Either the account name or password was wrong,\nplease remember that the account names are CASE SESITIVE"
> 
>    9.         print
>   10.         welcome()
> 
> and i need to return account as a global variable before display_menu()

Why? If display_menu() is using account, why not just pass it as an argument to account? In this specific case, you are already passing account as a parameter to sign_in(). If you make account a global variable as well you will get a syntax error.

Can you say a little more about what you are trying to do with the global variable?

Kent
-- 
http://www.kentsjohnson.com



More information about the Tutor mailing list