我有一个计划,计算完全平方高达上限的用户输入。我的代码是:的Python - 扩大和简化程序
"""Print all the perfect squares from zero up to a given maximum."""
import math
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"""
root = math.sqrt(num)
return int(root) - root == 0
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()
我想扩大这个计划稍微还包括一个下限,因此程序计算和两个界限lower_bound
和upper_bound
之间打印完美的正方形。虽然这样做,我也想概括read_bound()
功能,使得它适用于双方的上限和下限,同时还打印成原来的程序做了适当提示提示字符串。我想出了一个途径,以一个可能的解决方案,通过传递所需的提示字符串到read_bound()
功能,使主要功能变成这样的:
def main():
"""Every home should have one"""
lower_bound = read_bound("Enter the lower bound: ")
upper_bound = read_bound("Enter the upper bound: ")
squares = []
for num in range(lower_bound, upper_bound + 1):
if is_perfect_square(num):
squares.append(num)
print_squares(lower_bound, upper_bound, squares)
这是一个有效的途径就是要解决增加一个下界到我的程序,同时也推广它?如果是这样,我如何调整我的read_bound()
和print_squares
函数以适应解决方案?