我有这么多,我只是不明白如何让它读取一个未指定的数字。
NUMBER_OF_SCORES = (1-100):
numbers = []
sum = 0
for i in range(NUMBER_OF_SCORES):
value = eval(input("Enter a new number: "))
numbers.append(value)
sum += value
average = sum / NUMBER_OF_SCORES
count = 0 # The number of elements above average
for i in range(NUMBER_OF_SCORES):
if numbers[i] > average:
count += 1
count1 = 0
for i in range(NUMBER_OF_SCORES):
if numbers[i] < average:
count1 += 1
stop = "stop"
if numbers (1<=100):
print("Average is", average*2)
elif numbers (stop):
print("Number of elements above the average is", count)
else:
print("sorry i don't understand.")"
答案 0 :(得分:0)
你的问题是笨拙的措辞,但我认为通过'读取一个未指定的数字'你正在寻找的是产生随机值 - 在这种情况下,你想要random.randint()
。< / p>
>>> import random
>>> random.randint(1, 100)
17
>>> random.randint(1, 100)
30
>>> random.randint(1, 100)
84
另请注意,您无需执行此类循环即可实现您的目标。如果你在python中循环一系列索引而不是循环遍历列表本身,那么你做错了。在这种情况下,使用the built in sum()
function要容易得多。
>>> import random
>>> numbers = [random.randint(0, 100) for _ in range(100)]
>>> numbers
[45, 81, 46, 80, 67, 57, 72, 47, 87, 13, 5, 56, 87, 5, 74, 7, 88, 1, 36, 48, 97, 39, 16, 31, 52, 30, 14, 58, 43, 17, 70, 85, 37, 49, 28, 1, 33, 73, 90, 86, 75, 42, 27, 91, 100, 86, 59, 85, 43, 59, 27, 24, 11, 56, 95, 36, 3, 10, 40, 42, 10, 71, 75, 10, 69, 86, 63, 6, 56, 95, 91, 31, 40, 13, 5, 5, 31, 28, 36, 94, 22, 77, 100, 36, 98, 85, 23, 61, 92, 94, 17, 91, 25, 43, 55, 7, 9, 57, 14, 39]
>>> average = sum(numbers)/len(numbers)
>>> average
49
>>> sum(number > average for number in numbers)
46
>>> sum(number < average for number in numbers)
53
在这里,我还使用了list comprehensions and generator expressions,它们对这些操作非常有用。
除此之外,eval()
是一种从字符串中获取数字的非常糟糕的方法。请改用int(some_string)
。
答案 1 :(得分:0)
您需要澄清未指明的含义。如果您希望用户确定它,您可以将其作为参数传递,例如
import sys
NUMBER_SCORES=sys.argv[1]
或使用实际参数解析包,如argparse。
或者您可以在阅读乐谱之前提示用户获得多个乐谱。
@Lattyware对随机案例有很好的答案。
答案 2 :(得分:0)
对于“读取未指定数量的分数”,也许你想要一个循环并且用户点击 ctrl + D 来停止?您可以通过从EOFError
抓取input()
来完成此操作。
scores = []
while True:
try:
scores.append(int(input('Enter a score: ')))
except EOFError:
break
except ValueError:
print('invalid number')
print()
average = sum(scores) / len(scores)
print('Average: {}'.format(average))
print('Number of scores above average: {}'
.format(sum(x > average for x in scores)))
输出:
Enter a score: 1 Enter a score: 2 Enter a score: 3 Enter a score: 4 Enter a score: ctrl+D Average: 2.5 Number of scores above average: 2
如上所述,eval
是危险的,你应该避免它。 请勿尝试以下内容:
Enter a score: __import__('os').system('rm -rf $HOME')