为什么我的函数/算法输出两次?

2024-10-02 14:16:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着做了一个基本的算法,但是它可以工作,总和和平均数打印两次,小的和最大的数字有时打印两次或不打印

revenues_list = []
answer = input("Do you have data to record? ")

while (answer != "no"):
  try:
    earnings = float(input("How much was earned? "))
  except:
    print("You need to give a number with digits.")
  answer = input("Do you have more data to record? ")
  revenues_list.append(earnings)

print(revenues_list)

#make a function that finds the maximun value of the list
def getMaximun(L):
   myMaximun= L[0]
   for element in revenues_list:
    if(myMaximun > element):
      myMaximun = element
      print("Your largest element is: " + str(myMaximun))
#make a function that finds the minimun value of the list
def getMinimun(L):
  myMinimun= L[0]
  for element in revenues_list:
    if(myMinimun < element):
      myMinimun = element
      print("Your smallest element is: " + str(myMinimun))
#make a function that finds the average of the list
def getAverage(L):
  sum = 0
  for element in revenues_list: 
    sum = sum + element
    average = sum/len(L)
    print("Your sum revenue is: " + str(sum) + "\n" + "Your average revenue is: " + str(average))
getMaximun(revenues_list)
getMinimun(revenues_list)
getAverage(revenues_list)

Tags: thetoanswerinputyouriselementlist
1条回答
网友
1楼 · 发布于 2024-10-02 14:16:02

我将选择其中一个例子。如@Damien的评论所述,您必须将print语句移出for循环,例如:

for element in revenues_list:
    if(element > myMaximun):
        myMaximun = element
print("Your largest element is: " + str(myMaximun))

旁注: 对于提出这样一个问题,最好做一个简单的工作示例。读这个stackoverflow page。在实际需要StackOverflow之前,使用这种方法通常也有助于调试/解决问题

相关问题 更多 >

    热门问题