所以我搜索了幾乎每個字串「python」,「驗證」,「用戶輸入」等字樣的排列,但我還沒有碰到一個爲我工作的解決方案。驗證用戶輸入字符串在Python中
我的目標是提示用戶是否要使用字符串「yes」和「no」開始另一個事務,並且我認爲字符串比較在Python中是一個相當簡單的過程,但只是一些工作不正常。據我所知,我使用的是Python 3.X,因此輸入時應該使用字符串而不使用原始輸入。
即使輸入'yes'或'no',程序也會回覆無效輸入,但真正奇怪的是每次輸入長度大於4個字符的字符串或int值時,都會檢查它作爲有效的正向輸入並重新啓動程序。我還沒有找到一種方法來獲得有效的負面投入。
endProgram = 0;
while endProgram != 1:
#Prompt for a new transaction
userInput = input("Would you like to start a new transaction?: ");
userInput = userInput.lower();
#Validate input
while userInput in ['yes', 'no']:
print ("Invalid input. Please try again.")
userInput = input("Would you like to start a new transaction?: ")
userInput = userInput.lower()
if userInput == 'yes':
endProgram = 0
if userInput == 'no':
endProgram = 1
我也曾嘗試
while userInput != 'yes' or userInput != 'no':
我將不勝感激,不僅與我的問題有所幫助,但如果任何人有關於Python如何處理字符串,將是巨大的任何其他信息。
對不起,如果其他人已經問過這樣的問題,但我盡我所能搜索。
謝謝大家!
〜戴夫
哇。這樣一個簡單的錯誤。感謝您的及時回覆。我想有時你只需要第二雙眼睛來發現事物。 – user2398870
作爲一個方面說明,你能幫我學習爲什麼我的原始方法雖然userInput!='yes'或userInput!='no':不起作用嗎? – user2398870
@ user2398870:如果'userInput'設置爲''yes'',那麼'!='no''爲真。這不是你想要測試的。 :-)更改'或'爲'和'會使該版本正常工作。 –