简体   繁体   中英

How do I calculate the total and average of all dice rolls?

I am 100% new to coding. This is my first semester in IT and Python is making 0% sense to me at all. This is the assignment I have been given:

Code this program as a while statement, then create it a second time as a for statement

Ask the user how many times she will roll the 2 dice. Simulate the dice roll that many times by generating 2 random numbers between 1 and 6 Immediately after each roll display the total of the roll After all of the rolls calculate and display: -the total of all of the rolls -the average of all of the rolls

Use meaningful variable names Comment the main sections of your code and any lines that aren't self-explanatory

Your program output should look like this:

How many times will you roll the dice? 2 You rolled a 1 and a 5 You rolled a 3 and a 6 Your total for all of the rolls is 15 You average for all of the rolls is 7.5

This is what I have so far, but I have spent hours reading our text-book chapters and watching recordings of the lecture and I can not figure out the rest. Please help.

from random import randint

numRolls= int(input("How many times will you roll the dice? "))

for diceRolls in range(numRolls):
    d1 = randint(1,6)
    d2 = randint(1,6)
    print("You rolled a", d1, "and a",d2)
    
print("Your total for all of the rolls is", )

print("Your average for all of the rolls is", )

Without using lists and additional memory:

from random import randint


numRolls = int(input("How many times will you roll the dice? "))
s = 0

for roll in range(numRolls):
    d1 = randint(1, 6)
    d2 = randint(1, 6)
    s += d1 + d2
    print("You rolled a", d1, "and a", d2)
    
print("Your total for all of the rolls is", s)
print("Your average for all of the rolls is", s / numRolls)

You can use a list to store the data. You can also use the sum function to get the sum of all the values in the list, and use sum(allDiceRolls)/len(allDiceRolls) to get the average

Code:

from random import randint

numRolls = int(input("How many times will you roll the dice? "))

allDiceRolls = []

for diceRolls in range(numRolls):
    d1 = randint(1,6)
    d2 = randint(1,6)
    allDiceRolls.append(d1)
    allDiceRolls.append(d2)
    print("You rolled a", d1, "and a",d2)
    
print("Your total for all of the rolls is", sum(allDiceRolls))

print("Your average for all of the rolls is", sum(allDiceRolls)/len(allDiceRolls))

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