[Tutor] Beginner problem: name 'convertToFahrenheit' is not defined
Alan Gauld
alan.gauld at btinternet.com
Fri Aug 15 07:50:09 CEST 2008
"Joseph Bae" <joeturf at gmail.com> wrote
> temp = input("Enter A Number : ")
> convertTo = raw_input("Convert To (F)ahrenheit or (C)elsius? : ")
>
> if convertTo == "F":
> convertedTemp = convertToFahrenheit(temp)
> print "%d Celsius = %d Fahrenheit" % (temp, convertedTemp)
> else:
> convertedTemp = convertToCelsius(temp)
> print "%d Fahrenheit = %d Celsius" % (temp, convertedTemp)
>
> def convertToFahrenheit(t):
> tF = (9.0/5.0) * (t + 32)
> return tF
>
> def convertToCelsius(t):
> tC = (9.0/5.0) * (t - 32)
> return tC
>
> convertedTemp = convertToFahrenheit(temp)
> NameError: name 'convertToFahrenheit' is not defined
>
> This is most likely a very simple error, but can someone please
> clarify for
> me why it's behaving this way?
Others have explained that you need to execute the function
definitions before Python sees the name. You can do this in
two ways depending on taste.
1) As suggested move your main code below the function definitions.
2) move your main code into a function - traditionally called main()
then call main as the last line of your code.
The second method has two advantages:
1) It maintains the top-down design style if thats your preferred
style
2) It makes it much easier to make the file into a reusable module.
It has two minor disadvantages:
1) The extra function call (main() ) slows things down by a tiny
amount
2) the extra indentation level of being inside a function reduces the
page
width slightly
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list