简体   繁体   中英

Getting Sum from a randint loop

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]?

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)}")

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}")
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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM