猿问

如何在 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 输入。


慕无忌1623718
浏览 133回答 2
2回答

拉丁的传说

while True:&nbsp; &nbsp; answer = input('Enter the current number of HP (1-75): ')&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; # try to convert the answer to an integer&nbsp; &nbsp; &nbsp; &nbsp; hp_cur = int(answer)&nbsp; &nbsp; except ValueError:&nbsp; &nbsp; &nbsp; &nbsp; # if the input was not a number, print an error message and loop again&nbsp; &nbsp; &nbsp; &nbsp; print ('Please enter a number.')&nbsp; &nbsp; &nbsp; &nbsp; continue&nbsp; &nbsp; # if the number is in the correct range, stop looping&nbsp; &nbsp; if 1 <= hp_cur <= 75:&nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; # otherwise print an error message, and we will loop around again&nbsp; &nbsp; print ('Please enter a number in the range 1 to 75.')

精慕HU

您可以检查输入,如果它不在限制内,您可以要求用户再次输入。你会用一个while循环来实现这一点。while True:&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; hp_cur=int(input("Enter the current number of HP (1-75): "))&nbsp; &nbsp; except ValueError: # used to check whether the input is an int&nbsp; &nbsp; &nbsp; &nbsp; print("please insert a int type number!")&nbsp; &nbsp; else: # is accessed if the input is a int&nbsp; &nbsp; &nbsp; &nbsp; if hp_cur < 1 or hp_cur > 75:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("please insert a number in the given limit")&nbsp; &nbsp; &nbsp; &nbsp; else: # if number is in limit, break the loop&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp;您可以对第二个所需的输入执行相同的操作,然后再进行比较。如果它是一个负数,您可以通过将两个“有效性检查”放在一个更大的while循环中来要求用户再次输入数字,break当返回的数字为正时。
随时随地看视频慕课网APP

相关分类

Python
我要回答