嗨,我正在尝试制作一个函数,将所有从1到number
的数字平方(在代码末尾提供给函数)。我也这样做了,所以我有一个if语句,以便它检查数字是否<1并显示“错误”,但是当我输入0作为输入时,它什么都不做?
def print_squares_to_number(number):
"""takes number and prints a table of all integers and their squares from one to number"""
for numbers in range(1, number + 1):
if numbers < 1:
print("ERROR: number must be at least 1")
else:
print(numbers, "*", numbers, "=", numbers*numbers)
print_squares_to_number(0)
print_squares_to_number(5)
print_squares_to_number(3)
答案 0 :(得分:1)
您的循环部分从1
到input_integer+1
进行迭代。因此,如果您给出0或任何负整数,range(1, number+1)
会变成一个空的可迭代对象,因此它不会打印任何内容。
尝试一下:
def print_squares_to_number(number):
"""takes number and prints a table of all integers and their squares from one to number"""
if number < 1:
print("ERROR: number must be at least 1")
else:
for numbers in range(1, number + 1):
print(numbers, "*", numbers, "=", numbers*numbers)
print_squares_to_number(0)
print_squares_to_number(5)
print_squares_to_number(-1)
输出:
ERROR: number must be at least 1
1 * 1 = 1
2 * 2 = 4
3 * 3 = 9
4 * 4 = 16
5 * 5 = 25
ERROR: number must be at least 1