-1在多维数据集根计算器中返回错误

时间:2018-09-22 16:36:29

标签: python python-3.x

这是我的立方根计算器:

cube = int(input('Input an integer: '))
for guess in range(abs(cube + 1)):
    if guess ** 3 >= abs(cube):
        break
if guess ** 3 != abs(cube):
    print(str(cube) + ' is not a perfect cube.')
else:
    if cube < 0:
        guess = - guess
    print('Cube root of ' + str(cube) + ' is ' + str(guess))

在输入-1作为输入时返回以下错误:

Traceback (most recent call last):
  File "C:/Users/ABC.py", line 5, in <module>
    if guess ** 3 != abs(cube):
NameError: name 'guess' is not defined

它为所有期望-1的负整数打印期望答案,但我无法找到此现象的原因。它应该将-1打印为输出,并且当guess函数对其进行“定义”时,我看不出有任何理由定义range()

您看到我想念的东西吗?

3 个答案:

答案 0 :(得分:2)

将-1放入函数中时,for循环永远不会运行。 abs(-1+1)为0,因此它永远不会运行,因此永远不会初始化猜测。您可能有想法要做abs(-1) +1

答案 1 :(得分:1)

如果def func rc = function1 return rc unless rc.nil? function2 end ,则cube == -1abs(cube + 1) == 0为空。因此,不会发生迭代(因为没有要迭代的内容),并且永远不会创建名称range(abs(cube + 1))

此外,guess不是函数,而是class

答案 2 :(得分:1)

您必须正确缩进。 guess仅在for循环的范围内定义,它是for循环的索引。

cube = int(input('Input an integer: '))
for guess in range(abs(cube + 1)):
    if guess ** 3 >= abs(cube):
        break
if guess ** 3 != abs(cube): # this if is outside the for loop so guess is not defined
    print(str(cube) + ' is not a perfect cube.')
else: # this else-if is outside the foor loop so guess is not defined
    if cube < 0:
        guess = - guess
    print('Cube root of ' + str(cube) + ' is ' + str(guess))

我缩进了下面的那些行并运行了脚本,我没有得到您收到的错误,但是在运行程序时我也得到了8 is not a perfect cube.,如果我输入-1(或任何其他值,也不会得到任何输出)负数)。

cube = int(input('Input an integer: '))
for guess in range(abs(cube + 1)):
    if guess ** 3 >= abs(cube):
        break
    if guess ** 3 != abs(cube): # now it is inside the for loop
        print(str(cube) + ' is not a perfect cube.')
    else: # this is also now inside the for loop
        if cube < 0:
            guess = - guess
        print('Cube root of ' + str(cube) + ' is ' + str(guess))

关于您要执行的操作的最佳猜测如下。可能有更优雅的编写程序的方法,而且我知道break语句因使逻辑难以遵循而被皱眉。

cube = int(input('Input an integer: '))
for guess in range(abs(cube) + 1):
    # if a perfect cube is found we enter this if statement
    if guess ** 3 == abs(cube):
        # these if and else statements print the appropriate cube depending on if the input is negative or positive
        if cube < 0:
            print('Cube root of ' + str(cube) + ' is ' + str(guess * -1))
            break
        else:
            print('Cube root of ' + str(cube) + ' is ' + str(guess))
            break
    # else if the index cubed is greater than our input, we know it can't be a perfect cube and we should exit the loop.
    elif guess ** 3 > abs(cube):
        # tell the user the input is not a perfect cube
        print(str(cube) + " is not a perfect cube.")
        break