3 回答
TA贡献1765条经验 获得超5个赞
为 num 添加关键字 arg 并将其默认为None:
def five_numbers(num=None):
my_list = []
if num is None:
for i in range(1, 6):
user_nr = check_if_number_is_1_to_25(input("Number " + str(i) + ": "))
my_list.append(user_nr)
else:
# do other stuff with num (4) here...
return my_list
def check_if_number_is_1_to_25(number):
if number.isalpha():
print("Enter a number between 1 and 25.")
five_numbers(4)
TA贡献1934条经验 获得超2个赞
不要使用 for 循环,使用以列表长度为条件的 while 循环。使检查函数返回一个布尔值并使用它来决定是否附加到列表中。
def five_numbers():
my_list = []
while len(my_list) < 5:
user_nr = input("Number {}: ".format(len(my_list)+1))
if check_if_number_is_1_to_25(user_nr):
my_list.append(user_nr)
else:
print("Enter a number between 1 and 25.")
return my_list
def check_if_number_is_1_to_25(number):
return number.isdigit() and (1 <= float(number) <= 25)
TA贡献1798条经验 获得超7个赞
您可以使用while循环不断向用户询问有效输入,直到用户输入。您还应该让 check 函数引发异常,以便调用者可以捕获异常并重试输入:
def five_numbers():
my_list = []
for i in range(1, 6):
while True:
user_nr = input("Number " + str(i) + ": ")
try:
check_if_number_is_1_to_25(user_nr)
break
except ValueError as e:
print(str(e))
my_list.append(user_nr)
return my_list
def check_if_number_is_1_to_25(number):
if number.isalpha():
raise ValueError('Enter a number between 1 and 25.')
添加回答
举报