当结果不是我们期望的时候,我们可以模拟您的代码中发生的情况。
我们注意到,如果我们插入一个负数,程序就会停止。
所以让我们假设 num1 = -4 和 num2 = 2
def computeHCF(x,y): # x = -4, y = 2
if x>y: # we don't meet this condition
smaller = y
else: # we meet this condition
smaller = x # smaller value is -4
for i in range(1, smaller+1): # there is nothing in range(1, -3)!!
# we do not enter here
if((x % i == 0) and (y % i == 0)):
hcf = i
return hcf # hcf value has never been retrived, so an error will be raised here
您可以通过多种方式解决此问题,其中两种是:
给hfc设置一个基值,这样如果for循环中的条件不满足,就会返回基值:
def computeHCF(x,y):
hcf = None
此代码将返回:
('The H.C.F. of', -4, 'and', 2, 'is', None)
或者通过 x 和 y 的绝对值:
def computeHCF(x,y):
x = abs(x)
y = abs(y)
此代码将返回:
('The H.C.F. of', -4, 'and', 2, 'is', 2)
我们还看到,如果我们插入一个字符串或不能被解释为 int 的东西,则会引发另一个错误。
这一次,当您读取输入时发生错误:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
在这两行中,您将用户输入的任何内容都转换为 int,但将字符串转换为“Hello World!”不能转换成int。
解决此问题的众多方法之一是使用 try/except:您尝试将输入读取为 int,但如果发生错误,则执行其他操作。
try:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
print("The H.C.F. of", num1,"and", num2,"is", computeHCF(num1, num2))
continue
except:
print("You write something that doesn't have any sense!")
continue
使用此代码,输入“Hello”和“World!”的结果将是:
"You write something that doesn't have any sense!"
当 x = 0 或 y = 0 时,您还会发现函数 computeHCF(x,y) 生成的错误。
最后,您可以使用“else”语句擦除最后两行。只有当 while 循环的条件为 False 时才会执行 else,但 True 始终为 True!
最后,你的代码可能是这样的:
def computeHCF(x,y):
x = abs(x)
y = abs(y)
# or hcf = None
if any([type(x)!=int,type(y)!=int]):
return hcf
if x>y:
smaller = y
else:
smaller = x
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
hcf = i
return hcf
while True:
try:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
print("The H.C.F. of", num1,"and", num2,"is", computeHCF(num1, num2))
except:
print("You write something that doesn't have any sense!")
continue