我首先要求用户输入一个数字,然后运行一个try / except块。我现在想检查数字是否在1-9之间。
如果不是,我希望它检查是否为int,然后检查它是否在范围内。
这是我到目前为止所做的:
def getInt(low, high):
start = 0
while start == 0:
try:
num = input("Enter a number for your calculation in range of 1- 9: ")
num = int(num)
start = 1
asdf = 0
while asdf == 0:
if num > 9 or num < 0:
print("Error: Please only enter numbers between 1-9")
else:
asdf = +1
return num
except:
print("Error: Please only enter numbers")
# main
TOTAL_NUMBERS = 2
LOW_NUMBER = 1
HIGH_NUMBER = 9
num1 = getInt(LOW_NUMBER, HIGH_NUMBER )
print(num1)
num2 = getInt(LOW_NUMBER, HIGH_NUMBER )
print(num2)
答案 0 :(得分:0)
你可以替换
print("Error: Please only enter numbers between 1-9")
与
num = input("Error: Please only enter numbers between 1-9: ")
或移动
num = input("Enter a number for your calculation in range of 1- 9: ")
num = int(num)
进入while循环,以便在用户输入范围
之外的数字时再次调用它答案 1 :(得分:0)
也许你需要这个:
def getInt(low, high):
while True:
try:
num = int(input("Enter a number for your calculation in range of 1- 9: "))
except ValueError:
print("Error: Please only enter numbers")
continue
if num not in range(1, 10):
print("Error: Please only enter numbers between 1-9")
else:
return num
答案 2 :(得分:0)
def getInt(low, high):
while True: # Keep asking until we get a valid number
try:
numStr = raw_input("Enter a number for your calculation in range of {0} - {1}: ".format(low, high) )
if numStr.isdigit():
num = int(numStr)
if num <= high and num >= low:
return num
except: # Field left empty
pass
getInt(1, 9)