首页 > 解决方案 > Python 3.7 代码不会循环并返回名称错误

问题描述

首先,我对编程很陌生,所以请耐心等待。我当前的代码存在以下问题,我无法弄清楚。我无法根据用户输入结束循环。现在代码返回名称错误。有谁知道我该如何解决这个问题?感谢您的时间。

def gcd(a,b):    

    start_over = "true" 
    while start_over == "true":



        while True:
            a = int(input("Enter your first positive whole number: "))
            if a < 1 :
                print(a ,"IS NOT A POSITIVE WHOLE NUMBER")
                print("")
                continue

            else:
                break
        while True:
            b = int(input("Enter your second positive whole number: "))
            if b < 1 :
                print(b ,"IS NOT A POSITIVE WHOLE NUMBER")
                print("")
                continue

            else:
                break

        if (b==0):
                return a
        else:
            return gcd(b,a % b)

        gcf = gcd(a,b)


        print("the GCD of", a,"and", b,"is: ", gcf)

        redo_program = input("To perform another computation type Y/Yes or to quit type N/No: ").lower()

        if redo_program == "y" or "yes":
            start_over = "true"


        else:
            start_over ="null"
            print("GOODBYE")



gcd(a,b)     

标签: nameerror

解决方案


您的代码混淆并交织了两个部分。大概你想

  • 向用户询问两个号码
  • 递归计算它们的最大公约数

但是该gcd函数既需要两个数字作为参数,也要求用户输入数字(从而忽略参数),并且还递归调用自身。

名称错误来自最后一行,gcd(a, b)您试图获取的 GCDab- 但a尚未b输入(因为您只在函数内部执行此操作)。

即使该位有效,您的函数也会计算出,为了计算两个较大数字的 GCD,它需要事先计算两个较小数字的 GCD。到目前为止,一切都很好 - 除了您从未实际计算较小数字的 GCD,而是要求用户提供新的、不相关的数字对来计算 GCD,而忘记计算前一对数字。

另请注意,您的if b == 0条件return在两个分支中都有,因此不会gcd到达函数中低于它的代码。

所以要做你想做的事,试着改变你的代码以适应这个伪代码:

function gcd(a, b)
    calculate GCD without asking user anything

presume user wants to continue
loop while user wants to continue
    ask for two numbers
    calculate GCD
    print result
    ask the user if they want to continue

此外,你还有一些奇怪的字符串。这并不是一个真正的错误,除非我错过了一些让字符串"true"指示真值或"null"无值的字符串,但它是非常非常糟糕的形式 - 在 Python 中有特殊值TrueNone这些角色(你甚至True正确使用中while True)。


推荐阅读