我想设置一个列表,其范围为5插入您自己的数字,然后找到这些数字的总和。我被困在如何做范围。
import math
list(range(1, 5))
n = input("Enter a number: ")
range(1, 5)
#number.append(n)
print(n)
#print(len(number))
while(True):
n = (input("Enter a number: "))
#number.append
if(n == -1):
break;
for i in range(1, 5):
print(i)
#average = (len(number))
#average += (len(number))
print("Your average is: ")
答案 0 :(得分:2)
在range(5)
中循环追加用户输入的每个数字,然后求和:
nums = []
for _ in range(5): # ask user to enter a num 5 times
n = int(input("Enter a number")) # get and cast input to int
nums.append(n) # append each num
print(sum(n)) # call sum on the list of 5 numbers
我随机假设您指的是用户可以输入的5个数字。
答案 1 :(得分:0)
您可以使用列表理解:
randomNumbers = [int(input("enter a number")) for n in range(5)]
total = sum(randomNumbers)
average = sum(randomNumbers)/5
这将提示用户输入5次号码,每个号码都会被添加到列表中
如果您只想生成标题建议的随机数列表:
>>>import random
>>>random.sample(range(1, 100), 5)
[96, 87, 3, 70, 46]
答案 2 :(得分:0)
您可以让计算机生成如下随机数:
import random #Put this at the top of the file for clarity
nums = []
[nums.append(random.randint(1, 5)) for x in range(0, 5)] #Replace list(range(0, 5)) with this.
像这样的循环的一行基本上是写for x in range(0, 5): #Do stuff
之类的简单方法。
或者,您可以为用户输入执行此操作。
#DO NOT IMPORT RANDOM HERE. THIS IS NOT A CODE I ACTUALLY MEAN IT DO NOT PUT IMPORT RANDOM FOR THIS CODE BECAUSE IT WILL BE POINTLESS
#Replace the list(0, 5) again
nums = []
[nums.append(int(input("Please enter a number")) for x in range(0, 5)]
然后,总和,将每个元素加起来
total = sum(nums)
最后,对于平均值。
print(total/len(nums)) #len(nums) is basically the length of the numbers array which is how many numbers you are adding
如果您想让人们大吃一惊,我们会提供三线解决方案。
def avg(arr):
return sum(arr)/len(arr)
print(avg([int(input("Enter a number") for x in range(0, 5))]))