Wednesday, October 29, 2008

Funny Sayings Restraunts

013) The global variables

As we have studied, when you create functions state variables (known as local variables) they are all 'inside the function block with instead declare global variables that can be used in all the functions. Some examples:

EXAMPLE OF ERROR NOT GLOBAL VARIABLE:
 
final calcoloeta () :
year = 2008
tuoanno = input ( "In what year were you born : )
age = years - tuoanno
print " Hai ", eta ," anni "
calcoloeta ()
print " Siamo nell' anno ", anno #si richiama la variabile
#anno


Output:
  
In che anno sei nato: 1985
Hai 23 anni
Siamo nell' anno
Traceback (most recent call last):
File "prova.py", line 25, in
print "We're in 'year', year
NameError: name 'year' is not defined

What's happening? The interpreter returns error because the line print "We're in 'year," year we try to recall the year that variable within the function as a local variable is then valid only inside the function the problem can be solved by declaring years as a global variable:
 
final calcoloeta () :
global years year # becomes a global variable
years = 2008
tuoanno = input ("What year were you born : )
age = years - tuoanno
print" You " age, " years "
calcoloeta ()
print "We are in ' years, years # # relies on the variable
years

In this case there should be no mistakes because years although a variable within a function and "uttilizzabile all" thanks to global.

0 comments:

Post a Comment