[英]Creating function in python - while loop won't end
所以這是我的代碼:
def userInputInt(LL,UL):
"""Asks for user input for an integer value within a certain limit"""
need_input = True
while need_input == True:
print("Please enter an integer between ",LL," and ",UL, ": ", sep='')
user = input()
if user >= 'LL' and user <= 'UL':
need_input == False
return int(user)
我希望能夠接受輸入中的任何內容,並且仍然可以正常工作。 但是我的while循環不管輸入什么,都會繼續進行,即使它在參數中也是如此。
有什么建議么?
感謝您的所有幫助!
我想將它們作為字符串進行比較,以便用戶可以輸入字母而不會使其崩潰。 但是我忘了把''變成變量文字。
我的解決方案:
while need_input == True:
print("Please enter an integer between ",LL," and ",UL, ": ", sep='')
user = input()
if user >= str(LL) and user <= str(UL):
need_input = False
其次@Wondercricket說的。 用戶實際上不是一個字符串,它是一個等於字符串或整數(無論您是哪種情況)的變量。 當在LL和UL周圍加上引號時,您將它們視為文字字符串“ LL”和“ UL”,而不是它們等於的值。 您需要將它們視為變量LL和UL,以便可以將LL和UL的值與用戶變量的值進行比較。
編輯該地址以解決用戶輸入非整數的問題。 除了嘗試將輸入轉換為整數外,還包括嘗試。 如果由於用戶未輸入整數而無法執行此操作,請通過將exception關鍵字放在except子句中再次請求輸入。 輸入可以轉換為整數的輸入后,代碼將移至檢查int是否在LL和UL之間的行:
LL = 10
UL = 20
need_input = True
while need_input == True:
print("Please enter an integer between ",LL," and ",UL, ": ", sep='')
try:
user = int(input())
except:
continue
if user >= LL and user <= UL:
need_input = False
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.