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.')
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当返回的数字为正时。
添加回答
举报