我有任務,我們需要將攝氏度轉換為華氏度,反之亦然。我必須回圈程式,但我不知道如何。
我的代碼正在運行,但它仍然是錯誤的。
定義主():
print("a. Celsius to Fahrenheit")
print("b. Fahrenheit to Celsius")
choice = str(input("Enter Choice:"))
if choice == "a":
def c_to_f(C):
return((9/5)*C) 32
temp =float(input("Enter Temp: "))
print(temp,"Celsius is",c_to_f(temp),"Fahrenheit")
if choice =="b":
def f_to_c(F):
return (5/9)*(F-32)
temp =float(input("Enter Temp: "))
print(temp,"Fahrenheit is",f_to_c(temp),"Celsius")
repeat = input("Do you want to convert again? (Yes/No): ")
for _ in range(10):
if repeat == "yes":
main()
else:
exit()
主要的()
uj5u.com熱心網友回復:
嗨,這是因為變數具有可以讀取其修改的范圍,repeat修改在main()其范圍之外是不可見的:這里是main函式。
可以在任何地方“檢查”的變數稱為全域變數,您應該在函式外部檔案的開頭宣告它們。
你有很多解決問題的方法,如果你想遠離你的實際代碼,這里有一個:
from sys import exit
def main():
print("a. Celsius to Fahrenheit")
print("b. Fahrenheit to Celsius")
choice = str(input("Enter Choice:"))
if choice == "a":
def c_to_f(C):
return((9/5)*C) 32
temp =float(input("Enter Temp: "))
print(temp,"Celsius is",c_to_f(temp),"Fahrenheit")
if choice =="b":
def f_to_c(F):
return (5/9)*(F-32)
temp =float(input("Enter Temp: "))
print(temp,"Fahrenheit is",f_to_c(temp),"Celsius")
return input("Do you want to convert again? (Yes/No): ")
for _ in range(10):
repeat = main()
if repeat.lower() == 'no':
exit()
uj5u.com熱心網友回復:
您的代碼的問題是您main()在完成最后一行代碼后運行
這對你很有用:
def main():
for _ in range(10):
print("a. Celsius to Fahrenheit")
print("b. Fahrenheit to Celsius")
choice = str(input("Enter Choice:"))
if choice == "a":
def c_to_f(C):
return ((9 / 5) * C) 32
temp = float(input("Enter Temp: "))
print(temp, "Celsius is", c_to_f(temp), "Fahrenheit")
if choice == "b":
def f_to_c(F):
return (5 / 9) * (F - 32)
temp = float(input("Enter Temp: "))
print(temp, "Fahrenheit is", f_to_c(temp), "Celsius")
repeat = input("Do you want to convert again? (Yes/No): ")
if repeat == "yes":
main()
else:
exit()
if __name__ == '__main__':
main()
uj5u.com熱心網友回復:
您的代碼的問題是您最后的用戶輸入。
這對你很有用:
def main():
print("a. Celsius to Fahrenheit")
print("b. Fahrenheit to Celsius")
choice = str(input("Enter Choice:"))
if choice == "a":
def c_to_f(C):
return((9/5)*C) 32
temp =float(input("Enter Temp: "))
print(temp,"Celsius is",c_to_f(temp),"Fahrenheit")
if choice =="b":
def f_to_c(F):
return (5/9)*(F-32)
temp =float(input("Enter Temp: "))
print(temp,"Fahrenheit is",f_to_c(temp),"Celsius")
repeat = str(input("Do you want to convert again? (Yes/No): "))
for _ in range(10):
if repeat == "yes" or repeat == "Yes":
main()
else:
exit()
if __name__ == '__main__':
main()
玩得開心 CODE :)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/429165.html
