Home > Back-end >  Getting Sum from a randint loop
Getting Sum from a randint loop

Time:10-29

I would like to get the sum of the random numbers produced by my loop This is my loop

for i in range(1, rolls   1):
    random1 = str([random.randint(1, 6)])
    print(f'Roll {i}:'   random1)
The output looks like this 
Roll 1:[2]
Roll 2:[5]
Roll 3:[1]
Roll 4:[1]
Roll 5:[2]
Roll 6:[4]
Roll 7:[2]
Roll 8:[5]
Roll 9:[1]
Roll 10:[6]

How do i get the sum from the [brackets]?

CodePudding user response:

Using a variable to keep track of the sum:

total = 0
for i in range(1, rolls   1):
    n = random.randint(1, 6)
    total  = n
    print(f'Roll {i}: [{n}]')

print(f"Total: {total}")

Using sum:

nums = [random.randint(1, 6) for i in range(1, rolls   1)]

for i, n in enumerate(nums):
     print(f'Roll {i}: [{n}]')

print(f"Total: {sum(nums)}")

CodePudding user response:

Alternatively, here's a slightly shorter approach using the := operator in 3.8 :

total = 0

for i in range(1, rolls   1):
    total  = (n := random.randint(1, 6))
    print(f'Roll {i}: [{n}]')

print(f"Total: {total}")

CodePudding user response:

sum = 0
for i in range(1, rolls   1):
    rand = random.randint(1, 6)
    sum  = rand
    random1 = str(rand)
    print(f'Roll {i}:'   random1)
print(sum)

CodePudding user response:

You can define a variable that adds up all the random numbers

sum_number = 0
for i in range(1, rolls   1):
    random_number = random.randint(1, 6)
    random1 = str([random_number])
    print(f'Roll {i}:'   random1)
    sum_number  = random_number
print(sum_number)

Or you could rewrite it

random_number_list = [random.randint(1, 6) for _ in range(rolls)]
sum_number = sum(random_number_list)
# print random number
for i,random_number in enumerate(random_number_list):
    print(f'Roll {i 1}:'   random1)
print(sum_number)

If you don't need to see the print, you just need the first two lines of code

  • Related