[英]How do I get my small python program to quit when the user enters 'q' or 'quit'?
我嘗試用sys.stdout.flush()刷新stdout但它仍然無法正常工作。 它工作正常,直到用戶只輸入破壞代碼的C或F. 后綴是第一個被調用的函數,因此我確保如果用戶只輸入一個字符,則返回錯誤。 但是一旦返回錯誤,用戶就不能再鍵入'quit'或'q'。
#!/usr/local/bin/python
#Converts between Celsius and Fahrenheit
import random, sys
def check_version():
"""
Make sure user is using Python 3k
"""
if(sys.version_info[0] != 3):
print("Stop peddling with your feet Fred!")
print("Only Py3k supported")
sys.exit()
else:
pass
def random_insult():
"""
Returns a list of random insults with the sole purpose of insulting the user
"""
insults = ["Kel", "stimpy", "knucklehead"]
return insults[random.randrange(3)]
def suffix(temp):
"""
Accepts the input temperature value which should be a string suffixed by C(c) or F(f)
Returns the last element of the input string(C or F)
"""
if(len(temp) >= 2):
return temp[len(temp)-1]
else:
temperature("Input String TOO Small")
def temp_value(temp):
"""
Accepts the input temperature value which should be a string suffixed by C(c) or F(f)
Returns the actual temperature value
"""
if(len(temp) >= 2):
return temp[0:len(temp)-1]
else:
temperature("Input String TOO Small")
def cel_to_far(temp):
"""
Accepts the input temperature value as Celsius and returns it in Fahrenheit
"""
try:
return ((temp * (9/5.0)) + 32)
except TypeError:
return "Has to be a number"
def far_to_cel(temp):
"""
Accepts the input temperature value as Fahrenheit and returns it in Celsius
"""
try:
return ((temp - 32) * (5/9.0))
except TypeError:
return "Has to be a number"
def temperature(error=None):
"""
Loops until the user enters quit or q. Allows the user to enter the temperature suffixed by either C(c) or F(f).
If suffixed with C then the temperature is taken as Celsius and converted to Fahrenheit.
If suffixed with F then the temperature is taken as Fahrenheit and converted to Celsius.
If the user enters anything else be sure to belittle him/her.
"""
prompt1 = "Enter value suffixed by C or F *\n"
prompt2 = "Type 'quit' or 'q' to quit *\n"
error1 = "What in the world are you doing "+ random_insult() + "?\n"
error2 = "Did you forget to add C or F to the end of the value?\n"
example = "Here's an example of input: 30F\n"
stars = ("*" * 32) + "\n"
temp = None
if(error != None):
print(error)
print(example)
temperature()
else:
while(True):
sys.stdout.flush()
try:
temp = input("\n"+ stars + prompt1 + prompt2 + stars + ">>")
if( (temp == 'quit') or (temp == 'q')):
return
elif( (suffix(temp) == 'C') or (suffix(temp) == 'c') ):
print("Celsius:", temp_value(temp))
print("Fahrenheit: {0:.1f}".format(cel_to_far(float(temp_value(temp)))))
elif( (suffix(temp) == 'F') or (suffix(temp) == 'f') ):
print("Fahrenheit:", temp_value(temp))
print("Celsius: {0:.1f}".format(far_to_cel(float(temp_value(temp)))))
else:
print(error1 + error2 + example)
except:
print("Something went wrong and I don't care to fix it.\n")
return
if(__name__ == '__main__'):
check_version()
temperature()
問題在於,當發生錯誤時, temperature
在不同的地方遞歸調用,並且從程序退出時,用戶必須在調用temperature
時多次輸入q
/ quit
。
為了解決這個問題,我建議刪除所有遞歸調用並以不同的方式處理錯誤。 例如,可以檢查temp
以確保它是來自用戶的正確輸入,如果不是這種情況,則打印錯誤消息並continue
無限循環直到輸入為q
或quit
時調用break
。
即使您沒有做任何遞歸操作,您的程序也是遞歸的。
例如,在溫度函數中,有這個位:
if(error != None):
print(error)
print(example)
temperature()
因此溫度函數調用溫度函數。 相反,你應該做一個
while temperature():
pass
在main函數中,當某人退出時,溫度函數返回false,並且永遠不會從其他任何地方調用temperature()函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.