[Tutor] Re: using global variables with functions

Shantanoo Mahajan shantanoo at ieee.org
Sat Nov 15 10:26:56 EST 2003


+++ Smith, Ryan [14-11-03 16:46 -0500]:
| Hello All,
| 
| I am having some trouble with the way global variables interace with
| functions.  I found some practice problems on the Ibilio.org website and one
| of them is creating a program that converts celcius to farenheit and vice
| versa.  The following code is what I have come up with:
| 
| 
| 
| 
| #Prompt for user to enter the temp to convert
| >>>temp = raw_input("Enter a temperature:  ")
| >>>>print temp
| >>>>choice = raw_input("Convert to (F)arhenheit or (C)elcius: ")
| #Function to convert from celcius to farenheit
| >>>def convert_cel(temp):
| ...	tc = (5/9)*(temp - 32)
| ...	return tc
| if choice == 'C':
| 	print convert_cel(temp)
| 
| My problem is when I try to use temp as a variable in the convert_cel
| function.  My understanding is that whatever the user enters as the
| temperature that is now the value of the temp variable.  Since it is outside
| the function should it not be a global variable?  I get the following error
| message:
| 
| 
| #Prompt for user to enter the temp to convert
| temp = raw_input("Enter a temperature:  ")
| print temp
| choice = raw_input("Convert to (F)arhenheit or (C)elcius: ")
| #Function to convert from celcius to farenheit
| def convert_cel():
| 	tc = (5/9)*(temp - 32)
| 	return tc
| if choice == 'C':
| 	print convert_cel()
| 
| If anyone could help me see the "light" I would be most greatful.  I would
| like to point out that I am not asking for the answer just help with
| clarifying my understanding and correcting any misconceptions.  I have never
| programmed a day in my life but am really trying to learn.  Thanks
| 
| 
| Ryan Smith
| 
| 

and also

instead of 5/9 in convert_sel it should be
5.0/9.0
or
5/9.0
or
5.0/9

else everytime 0 will be returned.

Regards,
Shantanoo




More information about the Tutor mailing list