python - 需要在用户输入列表中查找最小值、最大值、范围和平均值,但我无法使用内置函数来查找它们
问题描述
我需要找到用户输入列表的最小值、最大值、范围和平均值,但是我不能使用内置的 min()、max() 或 range、内置函数,而是必须使用迭代。我让普通人工作,但我无法让其他人工作。
def average():
number_of_stats = int(input('How many stats are being averaged?: '))
stat_sum = 0
for i in range(number_of_stats):
stat_score = int(input('Please enter the stats #%s: ' % (i+1)))
stat_sum += stat_score
stat_average = stat_sum / number_of_stats
while True:
conduct_average = input('Do you need to average some stats? ').lower()
if conduct_average == ('yes'):
average()
else:
break
解决方案
对于最小值和最大值,您可以遍历列表并将每个值与运行的最小值/最大值进行比较。例如:
min_value = None
max_value = None
for i in range(number_of_stats):
stat_score = int(input('Please enter the stats #%s: ' % (i+1)))
stat_sum += stat_score
if min_value is None or stat_score < min_value:
min_value = stat_score
if max_value is None or stat_score > max_value:
max_value = stat_score