Python Forum
Sum of numbers from for loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sum of numbers from for loop
#1
Hello everyone,

I am trying to create a dice roll game where 2 players can roll 2 dice each for 5 rounds and then their points are added up. I am trying to use a for loop, but can't seem to find a way to add up the numbers from those 5 rounds. This is what I have so far:

for i in range(5):
  die1 = random.randint(1,6)
  die2 = random.randint(1,6)
  diesum = die1 + die2
  print("Your score for this round is",diesum)
How can I calculate the sum of all five 'diesum's ?
Reply
#2
something like
import random
diesum = 0
for i in range(5):
    die1 = random.randint(1,6)
    die2 = random.randint(1,6)
    diesum += die1 + die2
print("Your score for this round is {}".format(diesum))
if you don't need the numbers from individual dies
import random
diesum = sum([random.randint(1,6) for _ in range(10)])
print("Your score for this round is {}".format(diesum))
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
Hello buran, I already know how to add up the scores in one round, I'm trying to add up the scores of all 5 rounds...
Reply
#4
that's exactly what my code snippets do.
Here is code snippet with extra print at each iteration of the loop
import random
diesum = 0
for i in range(5):
    die1 = random.randint(1,6)
    die2 = random.randint(1,6)
    diesum += die1 + die2
    print('die1: {}, die2: {}, current diesum: {}'.format(die1, die2, diesum))
print("Your score for this round is {}".format(diesum))
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
I'm sorry if I didn't explain my issue well enough, but this is not quite what I need. I want the user to see the score for each individual round AND the total score for all 5 rounds. The two solutions that you have given me do only one of those things, but I need them to do both.
Reply
#6
I have added a code snippet to my previous post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Print Numbers starting at 1 vertically with separator for output numbers Pleiades 3 3,763 May-09-2019, 12:19 PM
Last Post: Pleiades

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020