Reputation: 23
I am trying to create a program that asks user for a number and then generates a list of random numbers entered by the user and then uses a function to add these numbers together and return it back to the main function. I am so lost can someone please help me?
import random
def main():
rand = int(input('How many random intergers? (Max 20)'))
if rand <= 20:
for x in range(rand):
print (random.randint(1,9), end=' ')
total = randnums(x)
print('Integers total is ', total)
else:
print('Bad inpit. Maximum input is 20.')
Trying to get this sample output
How many random integers (max 20)? 12
5 9 7 7 9 8 8 2 5 5 8 7
Integers total is 80
Upvotes: 1
Views: 2113
Reputation: 96927
To sample i integers without replacement from a pool of integers from 1 to n, and then sum them:
$ n=12345
$ i=100
$ seq ${n} | shuf -n ${i} | awk '{s+=$0}END{print s}'
To sample with replacement and sum:
$ seq ${n} | shuf -r -n ${i} | awk '{s+=$0}END{print s}'
Upvotes: 0
Reputation: 1025
You have at least to store your random outputs and only then you can add them...
E.G.
total = 0
for x in range(rand):
rnum = random.randint(1,9)
print (rnum, end=' ')
total = total + rnum
print('Total: %s' %total)
Upvotes: 1
Reputation: 1782
import random
def f():
n= input("give n : ")
return sum([random.randint(0,10) for i in range(n)])
this will return the sum of 10 random number between 0 and 10
Upvotes: 2
Reputation: 199
Import random
print (sum ([random.random () for x in range (1,input ("choose a list size"))]))
Upvotes: 0