[英]NameError: name 'C' is not defined` error Converting Temperature
[英]Python converting temperature error
我嘗試編寫此代碼將溫度從華氏溫度轉換為攝氏溫度,反之亦然。
try:
temperature=raw_input ("Enter temperature in numerals only")
temp1=float(temperature)
conversion=raw_input ("Convert to (F)ahrenheit or (C)elsius?")
def celtofah():
temp2 = (9/5)*temp1+32
print temp1," C = ",temp2," F"
def fahtocel():
temp2 = (5/9)*(temp1-32)
print temp1," F = ",temp2," C"
if conversion == F:
celtofah()
elif conversion == C:
fahtocel()
except:
print "Please enter a numeric value"
但是我似乎在第5行得到了一個錯誤,我已經定義了celtofah函數。
我不認為縮進在這里是錯誤的,雖然我可能會錯過任何東西。
這是你的縮進,即使沒有看你的形象。 為了使它工作,你可以簡單地縮進所有def和if / elif。 但更好的是,如果你在try / except之前定義那些函數,轉換和if之后的else中的if / elif和除了ValueError之外的except更改。 您還應該使用函數的參數,並且您使用的F和C是未聲明的變量。
def celtofah(temp1):
temp2 = (9/5)*temp1+32
print temp1," C = ",temp2," F"
def fahtocel(temp1):
temp2 = (5/9)*(temp1-32)
print temp1," F = ",temp2," C"
try:
temperature=raw_input ("Enter temperature in numerals only")
temp1=float(temperature)
except ValueError:
print "Please enter a numeric value"
else:
conversion=raw_input ("Convert to (F)ahrenheit or (C)elsius?")
if conversion == 'F':
celtofah(temp1)
elif conversion == 'C':
fahtocel(temp1)
還有一些其他的東西你可以改進你的代碼,也許我錯過了,但這可以作為模板。
問題是try / except縮進,如果比較(C和F應該是字符串):
try:
temperature = raw_input("Enter temperature in numerals only")
temp1 = float(temperature)
conversion = raw_input("Convert to (F)ahrenheit or (C)elsius?")
def celtofah():
temp2 = (9 / 5) * temp1 + 32
print temp1, " C = ", temp2, " F"
def fahtocel():
temp2 = (5 / 9) * (temp1 - 32)
print temp1, " F = ", temp2, " C"
if conversion == "F":
celtofah()
elif conversion == "C":
fahtocel()
except:
print "Please enter a numeric value"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.