如何更改我的代码

时间:2017-12-13 14:40:26

标签: python function optimization

如果我给出负数,这段代码就不再起作用了,如果我把一个字符串或者某些东西没有意义,我就不知道如何阻止它。请帮帮我!!

def computeHCF(x,y):

        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:
        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;
    else:
        print("You write something that doesn't have any sense!")

2 个答案:

答案 0 :(得分:0)

你必须先让python检查输入中的字符串。 然后检查负数, 如果这两个错误都不存在,那么继续运行您的代码 但如果他们在发出错误之前让它退出 像这样:

def computeHCF(x,y):

    if type(x) is str or type(y) is str:
        print("You wrote something that doesn't have any sense!")
        exit()
    elif x < 0 or y < 0 :
        print("You wrote something that doesn't have any sense!")
        exit()
    elif x>y:
        smaller = y
    elif y<x:
        smaller = x
    for i in range(1, smaller+1):
        if((x % i == 0) and (y % i == 0)):
            hcf = i
    return hcf

while True:
    num1 = (input("Enter the first number: "))
    num2 = (input("Enter the second number: "))
    print("The H.C.F. of", num1,"and", num2,"is", computeHCF(num1, num2))
    continue;

答案 1 :(得分:0)

当结果不符合我们的预期时,我们可以模拟代码中发生的情况。 我们注意到如果我们插入一个负数,程序就会停止。 所以我们假设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