簡體   English   中英

如何在python中定義輸入限制

[英]How do I define limits for my inputs in python

我正在嘗試為python中的輸入定義限制:

hp_cur=int(input("Enter the current number of HP (1-75): "))
hp_max= int(input("Enter the maximum number of HP (1-75): "))
hp_dif=(hp_max-hp_cur)

我想將hp-cur的輸入限制為1-75,並同時限制hp-max的輸入,並確保輸入大於hp-cur的輸入。

您可以檢查輸入,如果不在限制范圍內,則可以要求用戶再次輸入。

您將通過while循環意識到這一點。

while True:    
    try:
        hp_cur=int(input("Enter the current number of HP (1-75): "))
    except ValueError: # used to check whether the input is an int
        print("please insert a int type number!")
    else: # is accessed if the input is a int
        if hp_cur < 1 or hp_cur > 75:
            print("please insert a number in the given limit")
        else: # if number is in limit, break the loop
            break     

您可以對第二個所需的輸入執行相同的操作,然后再進行比較。 如果它是負數,則可以通過將兩個“有效性檢查”放在較大的while循環中來要求用戶再次輸入數字,當返回的數字為正數時,您會break該循環。

while True:
    answer = input('Enter the current number of HP (1-75): ')

    try:
        # try to convert the answer to an integer
        hp_cur = int(answer)

    except ValueError:
        # if the input was not a number, print an error message and loop again
        print ('Please enter a number.')
        continue

    # if the number is in the correct range, stop looping
    if 1 <= hp_cur <= 75:
        break

    # otherwise print an error message, and we will loop around again
    print ('Please enter a number in the range 1 to 75.')

暫無
暫無

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

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