[英]Why does my Python code keep returning “Invalid mode.” with proper input?
因此,我正在編寫一個簡單的計時器程序,以提高Python的性能,因為我以前從未真正嘗試過。 由於我對語言的了解有限,所以我不具備自己診斷該問題的資格。 我嘗試將“ if mode ==”語句周圍的雙引號更改為單引號,但這並沒有任何改變。 我不斷收到“無效模式”。這是我的錯誤消息,指出它沒有啟動或關閉。
這是我的代碼:
import time
seconds = 0
mode = "down"
def main():
print("Timer v1.0 by Alexis Knox")
time.sleep(1)
seconds = int(input("Seconds to count: "))
mode = str(input("Timer mode [up/down]: "))
if mode != 'up':
print("Invalid mode.")
exit(0)
if mode != 'down':
print("Invalid mode.")
exit(0)
if seconds < 1:
print("Invalid time.")
exit(0)
if mode == 'up':
for x in range(seconds):
x += 1
print(str(x))
time.sleep(1)
if mode == 'down':
y = seconds
for y in range(seconds):
y -= 1
print(str(y))
time.sleep(1)
# Ensure that we execute main
if __name__ == "__main__":
main()
如果您看一下我對您的代碼所做的操作,這應該可以解決問題
if seconds < 1:
print("Invalid time.")
exit(0)
elif mode == 'up':
for x in range(seconds):
x += 1
print(str(x))
time.sleep(1)
elif mode == 'down':
y = seconds
for y in range(seconds):
y -= 1
print(str(y))
time.sleep(1)
else:
print("Invalid mode.")
exit(0)
如果您像以前一樣運行連續的if語句,則最好使用elif語句(如果它們彼此相關),如我的代碼所示。 else會更高效,因為它將完全執行您之前代碼的第一部分所做的工作,除了它將首先運行if和elif測試。 else將基本上捕獲elif和if測試中未說明的任何內容。 但是您的輸出可能不是您想要的,但這不是問題
如果輸入“ up”,則第二個if
將為true,因為該模式不是“ down”。 如果輸入“ down”,則第一個if
將為true,因為該模式不是“ up”。 其他任何事情,第一個if
都會消失,因為其他任何事情都不會“升級”。 也就是說,無論如何,前兩個之一將在您到達實際可處理的代碼之前就消失了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.