Search code examples
pythonif-statementnameerror

NameError: name 'C' is not defined` error Converting Temperature


I'm working on this Python code to convert Fahrenheit to Celsius and the second code that converts Celsius to Fahrenheit. I wrote each code the same way, using (if/else) but whenever I try to make the first condition true. For example, when temperature F = -400 I get a NameError: name 'C' is not defined error.

I tried changed the line position for C so it runs before the last print line. But still no luck. The second code part that converts C to F runs without this error. I tried putting the equation for C after the last print line but still the same error.

Is this something that I may be missing on the first part that may be preventing me from making the first condition true?

I'm running Python 2.7.10 and using Terminal on Mac OS X El Capitan (10.11)

Convert Fahrenheit to Celsius:

F = int(raw_input("Enter Temperature In Fahrenheit:")) 

if F >= (-459.67):

    print "Temperature in absolute zero cannot be achieved"

else: 

    C = F - 32 * (0.555556) 
print "The temperature is %.1f" 'C'  % C 

Convert Celsius to Fahrenheit:

C = int(raw_input("Enter Temperature In Celsius:"))

if C <= (-273.15):   

    print "Temperature in absolute zero cannot be achieved" 

else:                                                        

    print "The temperature is %.1f" 'F' % F                 
F = C * (1.8) + 32  

Solution

  • As people said, there are many errors. One solution is:

    F = float(raw_input("Enter Temperature In Fahrenheit:"))
    if F <= (-459.67):
        print "Temperature in absolute zero cannot be achieved"
    else:
        C = F - 32 * (0.555556)
        print "The temperature is %.1f" 'C'  % C
    
    # ----------------------------------------------------------
    
    C = float(raw_input("Enter Temperature In Celsius:"))
    if C <= (-273.15):
        print "Temperature in absolute zero cannot be achieved"
    else:
        F = C * (1.8) + 32
        print "The temperature is %.1f" 'F' % F