我写了一个简单的程序,可以计算出给定数量的完美平方。我的代码是:提取函数
"""Print all the perfect squares from zero up to a given maximum."""
def main():
"""Even the main function needs a docstring to keep pylint happy"""
upper_bound = None
while upper_bound is None:
line = input("Enter the upper bound: ")
if line.isnumeric():
upper_bound = int(line)
else:
print("You must enter a positive number.")
squares = []
for num in range(2, upper_bound + 1):
for candidate in range(1, num):
if candidate * candidate == num:
squares.append(num)
print("The perfect squares up to {} are: ".format(upper_bound))
for square in squares:
print(square, end=' ')
print()
我想我的代码块提取成几个功能,我想出了我认为是一个可能的解决方案,但不幸的是我无法得到它的运行,因为它给了我一个错误unsupported operand type(s) for +: 'NoneType' and 'int'
。我似乎无法找到这个问题的根源,我想知道我的解决方案是不是很糟糕,如果是的话,那么更好的解决方案是什么?
我尝试
"""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"""
line = input("Enter the upper bound: ")
if line.isnumeric() and int(line) >= 0:
upper_bound = int(line)
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()
暗示:你错过了原来代码中的while循环'而UPPER_BOUND是无:' – balki
我本来是包括在内,但拿出来,看它是否固定的我得到的错误,但可悲的是,这不是问题所以现在我正在寻找另一种解决方案 –