我有一個計劃,計算完全平方高達上限的用戶輸入。我的代碼是:的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
函數以適應解決方案?