我试图找到用户输入数字的平均值。循环应该重复自己,直到用户输入-9999(sentinel值)这是我到目前为止所做的并且它在空闲时工作但程序没有结束给我平均当我输入-9999。我是python的新手,可以使用一点指导谢谢。
import random
numbers = [int(input("Please, enter number {}(-9999 to end")
if input("-9999"):
# will display prompt like "Please, enter number 1:"
print ("numbers entered:", numbers) # this will print the entered number
positives = [num for num in numbers if num > 0]
negatives = [num for num in numbers if num < 0]
# loop ends here
print ("Average negative number is :", sum(negatives)*1.0/len(negatives))
print ("Average positive number is :", sum(positives)*1.0/len(positives))
print ("Average of all numbers is:",sum(numbers)/len(numbers))
答案 0 :(得分:0)
ns = []
while not ns or ns[-1] != -9999:
ns.append(int(input("Please, enter number {}(-9999 to end"))))
答案 1 :(得分:0)
ns = list(iter(lambda:int(input("Enter Number:")),-9999))
是一种很酷的方式
如果你使用第一个参数的函数,iter可以将一个sentinal值等待作为第二个参数
作为你的正面和负面的旁边....它似乎会忽略零(这可能是有意的)......
答案 2 :(得分:0)
此代码将在您向列表中添加数字时循环,并在您输入-9999时停止。然后它会抛出-9999,这样你就可以继续你的平均值了。它不紧凑,但它很有效,而且很简单。
numbers = []
while True:
numbers.append(input("Enter a number: ")) #append user input to 'numbers'
if numbers[-1] == -9999: #check to see if the last number entered was -9999
numbers = numbers[:-1] #if it was, modify numbers to exclude it
break # and break the loop