1

这是我当前的代码:

while True:
        try:
            mylist = [0] * 7
            for x in range(7):
                    sales = float(input("Sales for day:"))
                    mylist[x] = sales
                    if  sales < 0:
                        print ("Sorry,invalid. Try again.")
        except:
            print ("Sorry, invalid. Try again.")
        else:
            break

print (mylist)

best = max(sales)
worst = min(sales)

print ("Your best day had", best, "in sales.")
print ("Your worst day had", worst, "in sales.")

当我运行它时,我得到了这个:

Sales for day:-5
Sorry,invalid. Try again.
Sales for day:-6
Sorry,invalid. Try again.
Sales for day:-7
Sorry,invalid. Try again.
Sales for day:-8
Sorry,invalid. Try again.
Sales for day:-9
Sorry,invalid. Try again.
Sales for day:-2
Sorry,invalid. Try again.
Sales for day:-5
Sorry,invalid. Try again.
[-5.0, -6.0, -7.0, -8.0, -9.0, -2.0, -5.0]
Traceback (most recent call last):
  File "C:/Users/Si Hong/Desktop/HuangSiHong_assign9_part.py", line 45, in <module>
    best = max(sales)
TypeError: 'float' object is not iterable

我不太确定如何对其进行编码,以便列表不接受负值,因为我只想要 0 或更大的值。

我不确定如何解决 TypeError 问题,以便在我的代码中打印最小值和最大值

我的最后一个问题是,如果我想找到用户输入的七个输入的平均值,我应该如何将这些值从列表中提取出来

非常感谢

4

3 回答 3

3

你最好的选择是将数据检查放入一个while循环中。这将继续循环这个值,直到满足您的条件(>0

此外,这可能会让用户混淆他们在哪一天输入结果。另外,您需要使用列表来获取最大值/最小值,而不是单个值。将它们放在一起,并进行以下更改:

        for x in range(7):
            sales=-1
            while (sales<0):
                sales = float(input("Sales for day {0}".format(x)))
                mylist[x] = sales
                if  sales < 0:
                    print ("Sorry,invalid. Try again.")

稍后进行此更改:

best = max(my_list)
worst = min(my_list)
于 2012-12-09T23:03:16.487 回答
3

你的意思是说:

best = max(my_list)
worst = min(my_list)

至于有效性检查,问题在于如果输入无效,您仍然会转到下一个值x

于 2012-12-09T23:03:42.227 回答
-1

也许(未经测试):

mylist = []
while len(mylist) < 7:
    sales = float(input("Sales for day %s:" % str(len(mylist)+1)))
    if  sales >= 0:
        mylist.append(sales)
    else:
        print ("Sorry,invalid. Try again.")

print (mylist)

best = max(mylist)
worst = min(mylist)

print ("Your best day had", best, "in sales.")
print ("Your worst day had", worst, "in sales.")
于 2012-12-11T01:04:44.030 回答