簡體   English   中英

我想對int()進行輸入驗證,但驗證str()

[英]I want to do an input validation on an int(), but validate for str()

當用戶的輸入<= 0且輸入=“停止”時,我希望代碼“中斷”。 這就是我到目前為止所擁有的。

while True:

    try:
        x = input("how many times do you want to flip the coin?: ")
        if int(x) <= 0 or x.lower() == "stop": 
            break
        x = int(x)
        coinFlip(x)


     except ValueError:
        print ()
        print ("Please read the instructions carefully and try one more time! :)")
        print ()

我收到錯誤:

    if int(x) <= 0 or str(x).lower() == "stop":
ValueError: invalid literal for int() with base 10: 'stop'

你得到異常是因為第一個被評估的條件是int(x) <= 0而x此時並不是真正的整數。

你可以改變條件的順序:

if x.lower() == 'stop' or int(x) <=0

這樣你首先檢查'stop' ,並且不評估int(x) (因為or條件已經計算為True )。 任何非整數而不是'stop'字符串都會導致您正在處理的ValueError異常。

您得到一個ValueError因為您無法將字符串'stop'轉換為整數。

解決此問題的一種方法是使用正確捕獲ValueError的輔助方法,然后檢查字符串是否stop

def should_stop(value):
    try:
        return int(value) <= 0
    except ValueError:
        return value.lower() == "stop"

while True:
    x = input("how many times do you want to flip the coin?: ")
    if should_stop(x): 
        break

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM