问题描述
这是我的立方根计算器:
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
打印为输出,并且当range()
函数对其进行“定义”时,我看不出有任何理由来定义guess
。
看到我想念的东西了吗?
1楼
当您将-1放入函数中时,for循环永远不会运行。
abs(-1+1)
为0,因此它永远不会运行,因此永远不会初始化猜测。
您可能需要做abs(-1) +1
2楼
如果cube == -1
,则abs(cube + 1) == 0
,而range(abs(cube + 1))
为空。
因此,不会发生任何迭代(因为没有要迭代的内容),并且永远不会创建名称guess
。
另外, range
不是函数,而是一个 。
3楼
您必须正确缩进。
仅在for循环的范围内定义guess
,它是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