我正在尝试编写一个简单的程序,计算并打印完美的正方形数字直到输入上限。我的代码是:
"""Print all the perfect squares from zero up to a given maximum."""
def read_bound():
"""Reads the upper bound from the standard input (keyboard).
If the user enters something that is not a positive integer
the function issues an error message and retries
repeatedly"""
upper_bound = None
while upper_bound is None:
line = input("Enter the upper bound: ")
if line.isnumeric() and int(line) >= 0:
upper_bound = int(line)
return upper_bound
else:
print("You must enter a positive number.")
def is_perfect_square(num):
"""Return true if and only if num is a perfect square"""
for num in range(2, upper_bound + 1):
for candidate in range(1, num):
if candidate * candidate == num:
return True
def print_squares(upper_bound, squares):
"""Print a given list of all the squares up to a given upper bound"""
print("The perfect squares up to {} are: ". format(upper_bound))
for square in squares:
print(square, end=' ')
def main():
"""Calling the functions"""
upper_bound = read_bound()
squares = []
for num in range(2, upper_bound + 1):
if is_perfect_square(num):
squares.append(num)
print_squares(upper_bound, squares)
main()
但是,当我运行程序并输入任何有效数字时,我在builtins.NameError: name 'upper_bound' is not defined
的行上收到错误,指出for num in range(2, upper_bound + 1):
。是什么导致了这个问题,我该如何解决?
答案 0 :(得分:0)
您的程序遇到问题" is_perfect_square"功能。你不需要" upper_bound" for循环,因为你已经在" main"功能。你的" is_perfect_square"功能应如下所示:
def is_perfect_square(num):
"""Return true if and only if num is a perfect square"""
for candidate in range(1, num):
if candidate * candidate == num:
return True