2 回答
TA贡献1906条经验 获得超3个赞
使用try/except ValueError块是对的,但用错了地方。try 块需要在变量被转换为整数的地方。例如。
def main():
firstVal = input("Enter First Number: ")
secondVal = input("Enter Second Number: ")
try:
firstVal = int(firstVal)
secondVal = int(secondVal)
except ValueError:
# print the error message and return early
print("Please provide only Integers...")
return
divideNums (firstVal, secondVal)
TA贡献1810条经验 获得超5个赞
您可以使用 isdigit 函数来检查输入值是否为整数
def main():
firstVal = input("Enter First Number: ")
secondVal = input("Enter Second Number: ")
if firstVal.isdigit() and secondVal.isdigit():
divideNums (int(firstVal), int(secondVal))
else:
print ("Please provide only Integers...")
添加回答
举报