[Tutor] using global variables with functions
Smith, Ryan
rsmith at cff.org
Fri Nov 14 16:46:49 EST 2003
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
More information about the Tutor
mailing list