如果输入数字0,如何结束while循环并遵循其他说明

2024-04-19 07:22:01 发布

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

我的代码将所有用户输入的项目放入一个列表中 我希望它在输入0时停止,并遵循其他命令,例如排序列表、删除最高值和最低值,然后找到它们的平均值 以下是迄今为止的代码:

i = 0
sizes = []
while i == 0:
    size = int(input("Enter the weight of your parcel in grams, enter 0 when done: "))
    sizes.append(size)
    if size < 1:
        break
sortedsizes = sorted(sizes)
largest = max(sizes)
smallest = min(sizes)
sizes.remove(largest)
sizes.remove(smallest)
print(sizes)

Tags: 项目代码用户命令列表size排序remove
2条回答

您不需要i,也不希望包的重量小于0。你可能想考虑用float代替int——在我住的地方,我们测量kg的包裹或g的字母——两者都将包括分数(1.235kg或5.28g)。你知道吗

如果有人输入"22kg",任何数字转换都会崩溃-您应该注意:

sizes = []
while True:
    try:
        size = int(input("Enter the weight of your parcel in grams, enter 0 when done: "))
        if size > 0:  
            sizes.append(size)
        elif size == 0:
            break
        else:
            raise ValueError()  # negative weight
    except ValueError:
        print("Only positive numbers or 0 to quit. Do not input text or kg/g/mg.")

sortedsizes = sorted(sizes) # you do nothing with this - why sort at all?
largest = max(sizes)
smallest = min(sizes)
sizes.remove(largest)
sizes.remove(smallest)
print(sizes)  # this prints the unsorted list that got min/max removed...

输出:

Enter the weight of your parcel in grams, enter 0 when done: 4 
Enter the weight of your parcel in grams, enter 0 when done: 3 
Enter the weight of your parcel in grams, enter 0 when done: 5 
Enter the weight of your parcel in grams, enter 0 when done: 6 
Enter the weight of your parcel in grams, enter 0 when done: -1 
Only positive numbers or 0 to quit. Do not input text or kg/g/mg.
Enter the weight of your parcel in grams, enter 0 when done: DONE 
Only positive numbers or 0 to quit. Do not input text or kg/g/mg. 
Enter the weight of your parcel in grams, enter 0 when done: 2 
Enter the weight of your parcel in grams, enter 0 when done: 0

[4, 3, 5]  # this is the unsorted list that got min/max removed...

如果您只想从排序列表中删除1个最大值和1个最小值,您可以简单地执行以下操作:

sortedsizes = sorted(sizes)  
maxval = sortedsizes.pop()    # remove last one from sortedsizes  (== max)
minval = sortedsizes.pop(0)   # remove first one from sortedsizes (== min)
print(sortedsizes)            # print the sorted values

独行:

如果希望代码在输入0时停止(将大小附加到列表中,并在重复过程后继续执行命令),则必须执行相反的操作。你知道吗

while True:
    size = int(input("Enter the weight of your parcel in grams, enter 0 when done: "))
    sizes.append(size)
    if size < 1:
        break

当语句为false时,代码从sortedsizes = sorted(sizes)命令继续。你知道吗

相关问题 更多 >