[Tutor] Re: using global variables with functions

Shantanoo Mahajan shantanoo at ieee.org
Sat Nov 15 10:22:51 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
| 
| ------------------------------

the above prog. didn't work for. it gave TypeError

instead of raw_input, try input.
raw_input ---> string
input ---> integer

or if you want to use raw_input, in convert_cel

change
tc = (5/9)*(temp - 32)
to
tc = (5/9)*(int(temp) - 32)
or maybe
tc = (5/9)*(float(temp) - 32)


Regards,
Shantanoo



More information about the Tutor mailing list