【问题标题】:How to change my code如何更改我的代码
【发布时间】:2018-05-27 11:58:19
【问题描述】:

如果我给出负数,则此代码不再起作用,并且如果我输入例如字符串或没有意义的东西,我不知道如何停止它。请帮帮我!!

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!")

【问题讨论】:

  • 为什么不把输入的绝对值作为第一步呢?另外——为什么不直接使用small = min(x,y) 而不是if ... else 构造呢?此外 - 你的缩进没有意义。我怀疑你在函数定义的底部是否真的有 while 循环。最后,math.gcd() 会更有效地计算您尝试计算的内容。
  • 只为num1和num2写一个if条件
  • 定义“这不再起作用”

标签: python function optimization


【解决方案1】:

你必须让 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;

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2020-09-16
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      相关资源
      最近更新 更多