2 回答

TA貢獻1789條經(jīng)驗 獲得超8個贊
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.')

TA貢獻1845條經(jīng)驗 獲得超8個贊
您可以檢查輸入,如果它不在限制內(nèi),您可以要求用戶再次輸入。
你會用一個while循環(huán)來實現(xiàn)這一點。
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
您可以對第二個所需的輸入執(zhí)行相同的操作,然后再進行比較。如果它是一個負數(shù),您可以通過將兩個“有效性檢查”放在一個更大的while循環(huán)中來要求用戶再次輸入數(shù)字,break當(dāng)返回的數(shù)字為正時。
添加回答
舉報