[Tutor] hi...

broek at cc.umanitoba.ca broek at cc.umanitoba.ca
Sun Aug 24 16:24:12 CEST 2008


----- Message from betopm at live.com.mx ---------
     Date: Sun, 24 Aug 2008 01:31:28 -0500
     From: Alberto Perez <betopm at live.com.mx>
Reply-To: Alberto Perez <betopm at live.com.mx>
  Subject: [Tutor] hi...
       To: tutor at python.org


> run a program in interactive mode, the program run very good, but if  
>  run in not interactive mode not show me error, but the return of   
> function returns no value, this is the source code:
>
> def suma(no1,no2):       total=no1+no2
>    return total
> print 'hola'
> opcion=input()
> if opcion==1:
>    print 'suma'
>    a=input()     b=input()>
>    suma(a,b)
>
> the result of this code is:
>
> hola
> 1
> suma
> 5
> 7
>>> total
> Traceback (most recent call last):  File  "<pyshell#0>", line 1, in  
> <module>    totalNameError: name 'total'  is not defined>>>
>
> why this happens??? what I did wrong??? and why run very good in


Hi,

Welcome to python and the tutor list.

An earlier response pointed out that you need to bind the returned  
value to total as in
> total = suma(a, b)
but I thought a bit of explanation might help. In your function, you  
define total. That makes `total' a name in the scope of the function.  
That means that `total' can be seen by code in your function, but not  
code outside of your function.

This might seem confusing now, but in the long run, it makes life  
easier. How? Well, you can define all sorts of names in the body of  
your functions without having them clutter up the name-space of your  
overall code. That makes things cleaner. It also makes them less error  
prone. If total defined in  your function was visible everywhere by  
default, then you would have to make sure that your function didn't  
define any names that higher level code did. (You'd have to make sure  
that total defined in a function didn't overwrite total defined  
outside of the function.)

You can make names defined in functions be globally available, but  
until you've got some experience, don't do that. (Arguably, once you  
have experience, don't do that then either ;-)

Hope that helps some,

Brian vdB


More information about the Tutor mailing list