亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 python 中為我的輸入定義限制

如何在 python 中為我的輸入定義限制

慕無忌1623718 2021-06-08 12:52:14
我正在嘗試為我在 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 輸入。
查看完整描述

2 回答

?
拉丁的傳說

TA貢獻1789條經驗 獲得超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.')


查看完整回答
反對 回復 2021-06-09
?
精慕HU

TA貢獻1845條經驗 獲得超8個贊

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


你會用一個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當返回的數字為正時。


查看完整回答
反對 回復 2021-06-09
  • 2 回答
  • 0 關注
  • 163 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號