Python Dice Roller - How can I total all dice? - python

I want to get the total amount of the dice results:
import random
min = 1
max = 6
numDices = 0
roll_again = "yes"
sum = 0
while roll_again == "yes" or roll_again == "y":
numDices = int(raw_input("how many dices "))
for i in range(numDices):
dicesArray = list(range(numDices))
dicesArray[i] = random.randint(min, max)
print(dicesArray[i])
sum += dicesArray[i]
print("sum ", sum)
roll_again = raw_input("Roll the dices again? ")
but I get this when I run the code:
how many dices 3
4
('sum ', 4)
2
('sum ', 6)
6
('sum ', 12)
Roll the dices again?
Also, how can I limit the user to roll 1 to 5 dice max?
Thank you so much Python experts!

You should change the indentation of the print("sum") statement so you only print the final sum. Also add a check for the dice number like below.
import random
min = 1
max = 6
numDices = 0
roll_again = "yes"
# Greeting here
print("Welcome to the dice rolling program!")
raw_input("Press any key to continue...")
while roll_again == "yes" or roll_again == "y":
sum = 0 # sum should be inside while loop
numDices = int(raw_input("How many dice? "))
if (numDices < 1 or numDices > 5):
print("Allowed number of dice is 1 - 5. Please choose again.")
continue
for i in range(numDices):
dicesArray = list(range(numDices))
dicesArray[i] = random.randint(min, max)
print(dicesArray[i])
sum += dicesArray[i]
print("sum: " + str(sum))
roll_again = raw_input("Roll the dice again? ")

You need to check and make sure that numDices stays between 1 and 6. You can do that by adding an if condition before entering the for loop.
import random
min = 1
max = 6
numDices = 0
roll_again = "yes"
sum = 0
while roll_again == "yes" or roll_again == "y":
numDices = int(raw_input("how many dices "))
if numDices < 1 or numDices > 6:
print ("Invalid range. You can roll only between 1 and 5 times.")
continue
for i in range(numDices):
dicesArray = list(range(numDices))
dicesArray[i] = random.randint(min, max)
print(dicesArray[i])
sum += dicesArray[i]
print("sum ", sum)
roll_again = raw_input("Roll the dices again? ")

Related

print statement only when the condition is CONSECUTIVELY met 3 times in a row

I'm currently making a guessing game where user can get a congrats statement if they guess correctly 3 times in a row or a hint statement if they guesses incorrectly 3 times in a row. If user makes two correct guesses and one incorrect guess the count will reset and vice versa for incorrect guesses. the goal is for the right/wrong guess to be 3 times in a row for the statement to print
Here is what I have
count = 0
rightGuess = 0
wrongGuess = 0
die1 = random.randint(1,6)
guess = int(input('Enter guess: '))
if guess == die1:
rightGuess += 1
print('Good job')
if rightGuess == 3:
print('You guessed three times in a row!')
if guess != die1:
wrongGuess += 1
print('Uh oh wrong answer')
if wrongGuess == 3:
print("Hint: issa number :)")
This works but it displays the text whenever the user reaches 3 wrong or right guesses even if it's not in a row. Please help
You can reset the rightGuess variable using rightGuess = 0 when you add 1 to the wrongGuess variable.
You just have to reset the opposite variable to 0 when incrementing either of them.
count = 0
consecutiveRightGuess = 0
consecutiveWrongGuess = 0
die1 = random.randint(1, 6)
guess = int(input('Enter guess: '))
if guess == die1:
consecutiveWrongGuess = 0
consecutiveRightGuess += 1
print('Good job')
if consecutiveRightGuess == 3:
print('You guessed three times in a row!')
if guess != die1:
consecutiveRightGuess = 0
consecutiveWrongGuess += 1
print('Uh oh wrong answer')
if consecutiveWrongGuess == 3:
print("Hint: issa number :)")
You could also do it like this only using one variable for counting guesses:
import random
count = 0
while True:
die1 = random.randint(1,6)
guess = int(input("Enter guess: "))
if guess == die1:
count = count + 1 if count >= 0 else 1
print('Good job')
if guess != die1:
print('Uh oh wrong answer')
count = count - 1 if count <= 0 else -1
if count == 3:
print('You guessed three times in a row!')
break
if count == -3:
print("Hint: issa number :)")
break

Can someone help me loop this script (Python)?

I have this Python assigment to complete where I need to write a program that reads in X whole numbers and outputs (1) the sum of all positive numbers, (2) the sum of all negative numbers, and (3) the sum of all positive and negative numbers. The user can enter the X numbers in any different order every time, and can repeat the program if desired. This is what I've got so far:
x = int(input('How many numbers would you like to enter?: '))
sumAll = 0
sumNeg = 0
sumPos = 0
for k in range (0,x,1):
num = int(input("please enter number %i :" %(k+1)))
sumAll = sumAll + num
if num < 0:
sumNeg += num
if num > 0:
sumPos += num
if k == 0:
smallest = num
largest = num
else:
if num < smallest:
smallest = num
if num > largest:
largest = num
print("The sum of negative numbers is: " , sumNeg)
print("The sum of positive numbers is: " , sumPos)
print("The sum of all numbers is: " , sumAll)
count = 0
repeat = input('Would you like to repeat? y/n: ')
repeat = 'y'
while y == 'y':
I'm just a little stuck after this point. Any ideas on what I should do?
A simple while loop would suffice.
run = True
while run is True:
x = int(input('How many numbers would you like to enter?: '))
sumAll = 0
sumNeg = 0
sumPos = 0
for k in range (0,x,1):
num = int(input("please enter number %i :" %(k+1)))
sumAll = sumAll + num
if num < 0:
sumNeg += num
if num > 0:
sumPos += num
if k == 0:
smallest = num
largest = num
else:
if num < smallest:
smallest = num
if num > largest:
largest = num
print("The sum of negative numbers is: " , sumNeg)
print("The sum of positive numbers is: " , sumPos)
print("The sum of all numbers is: " , sumAll)
repeat = input('Would you like to repeat? y/n: ')
if repeat != 'y':
run = False
Example of the output:
How many numbers would you like to enter?: 4
please enter number 1 : 3
please enter number 2 : 2
please enter number 3 : 4
please enter number 4 : 5
The sum of negative numbers is: 0
The sum of positive numbers is: 14
The sum of all numbers is: 14
Would you like to repeat? y/n: y
How many numbers would you like to enter?: 3
please enter number 1 : 2
please enter number 2 : 4
please enter number 3 : 3
The sum of negative numbers is: 0
The sum of positive numbers is: 9
The sum of all numbers is: 9
Would you like to repeat? y/n: n
You just need to place your code inside an outer loop, that might start it all over again if the user wants to repeat.
while True:
# all your current code until the prints
repeat = input('Would you like to repeat? y/n: ')
if repeat is not 'y':
break

dice roll simulation in python

I am writing a program that is to repeatedly roll two dice until the user input target value is reached. I can not figure out how to make the dice roll happen repeatedly. Please, help...
from random import randrange
print ("This program rolls two 6-sided dice until their sum is a given target value.")
input = int (input("Enter the target sum to roll for:"))
#def main():
dice1 = randrange (1,7)
dice2 = randrange (1,7)
sumofRoll = dice1 + dice2
output = "Roll: {} and {}, sum is {}".format (dice1,dice2,sumofRoll)
print (output)
if sumofRoll == input:
print ("All done!!")
if sumofRoll != input:
#how do I make this repeatedly run until input number is reached?!
Here is a complete working code which takes care of invalid sum entered as input as well. The sum of two dice rolls cannot be either less than 2 or more than 13. So a check for this condition makes your code slightly more robust. You need to initialize sumofRoll = 0 before entering the while loop as this would be needed to first enter the while loop. The value of 0 is a safe value because we excluded the value of 0 entered by user to be a valid sum.
from random import randrange
print ("This program rolls two 6-sided dice until their sum is a given target value.")
input_sum = int(input("Enter the target sum to roll for:"))
def main():
sumofRoll = 0
if input_sum < 2 or input_sum > 13:
print ("Enter a valid sum of dices")
return
while sumofRoll != input_sum:
dice1 = randrange (1,7)
dice2 = randrange (1,7)
sumofRoll = dice1 + dice2
output = "Roll: {} and {}, sum is {}".format (dice1,dice2,sumofRoll)
print (output)
if sumofRoll == input_sum:
print ("All done!!")
main()
This program rolls two 6-sided dice until their sum is a given target value.
Enter the target sum to roll for:10
Roll: 3 and 5, sum is 8
Roll: 6 and 6, sum is 12
Roll: 5 and 1, sum is 6
Roll: 2 and 5, sum is 7
Roll: 6 and 6, sum is 12
Roll: 3 and 5, sum is 8
Roll: 1 and 2, sum is 3
Roll: 6 and 4, sum is 10
All done!!
I took your game and added some elements for you to peek through. One is you could use random.choice and select from a die list instead of generating new random ints repeatedly. Second you can use a try/except block to only accept an int and one that is within the range of (2, 13). Next we can add a roll_count to track the amount of rolls to hit our target. Our while loop will continue until target == roll_sum and then we can print our results.
from random import choice
die = [1, 2, 3, 4, 5, 6]
print('This program rolls two 6-sided dice until their sum is a given target.')
target = 0
while target not in range(2, 13):
try:
target = int(input('Enter the target sum to roll (2- 12): '))
except ValueError:
print('Please enter a target between 2 and 12')
roll_sum = 0
roll_count = 0
while target != roll_sum:
die_1 = choice(die)
die_2 = choice(die)
roll_sum = die_1 + die_2
roll_count += 1
print('You rolled a total of {}'.format(roll_sum))
print('You hit your target {} in {} rolls'.format(target, roll_count))
...
You rolled a total of 4
You rolled a total of 12
You hit your target 12 in 29 rolls
This is a simple while loop:
sumofRoll = -1; #a starting value!
while sumofRoll != input:
#Put the code that updates the sumofRoll variable here
count = 0
while(sumOfRoll != input):
dice1 = randrange(1,7)
dice2 = rangrange(1,7)
count = count + 1
sumOfRoll = dice1 + dice2
print("sum = %s, took %s tries" % (sumOfRoll, count))
Use a do while statement
do:
dice1=randrange(1,7)
...
while(sumofroll != input)
print("all done")

Calculating an average of multiple random numbers Python

I am fairly new to Python and have run into a roadblock with trying to calculate an average of a bunch of random numbers.The general overview of the program is that it is a die rolling program which prompts the user to enter a certain amount of sides and it then rolls until the program outputs snake eyes. It also keeps track of the amount of doubles rolled and how long it took to get snake eyes. Then create an average of the numbers that were rolled for each die throughout the program. This is where I am lost.
EDIT: I deleted my original code and worked in Vasilis's answer:
import random
while True:
#prompts user for valid number
user_s = int (input ("How many sides on your dice? "))
if user_s < 3:
print("That is not a valid size value, please enter a positive number")
if user_s >= 3:
break
print()
print("Thanks! Here we go...")
print()
double_count = 0
roll_count = 0
sum1 = 0 # Used to calculate sum of die_1
sum2 = 0 # Used to calculate sum of die_2
while True:
roll_count += 1
die_1 = random.randint(1,user_s)
die_2 = random.randint (1,user_s)
print(roll_count,".", " Die number 1 is ", die_1 , " and die number 2 is ", die_2, ".", sep ="")
if die_1 == die_2:
double_count += 1
if die_1 == 1 and die_2 == 1:
break
# Making sum
sum1 = sum1 + die_1
sum2 = sum2 + die_2
print("You finally got snake eyes on try number", roll_count)
print("Along the way you rolled a double", double_count,"times")
print(die_1)
print(die_2)
# Integer divisions
avg_roll1 = sum1 // roll_count
avg_roll2 = sum2 // roll_count
print("The average roll for die 1 was", format(avg_roll1,".2f"))
print("The average roll for die 2 was", avg_roll2)
However like he pointed out it doesn't take all of the numbers that is recorded through all the rolls, rather the last number.
Any help to accomplish that would be appreciated.
Thanks!
I made a few changes in your code if you like to take a look. I assumed that you wanted the average to be calculated as an integer although you can change that. You use die_1 and die_2 as simple integer variables and thus they hold only the last value generated by random.randint(1,user_s):
import random
'''Skipped input part'''
print()
print("Thanks! Here we go...")
print()
double_count = 0
roll_count = 0
sum1 = 0 # Used to calculate sum of die_1
sum2 = 0 # Used to calculate sum of die_2
while True:
roll_count += 1
die_1 = random.randint(1,user_s)
die_2 = random.randint (1,user_s)
print("DIE_1: ", die_1)
print("DIE_2: ", die_2)
print(roll_count,".", " Die number 1 is ", die_1 , " and die number 2 is ", die_2, ".", sep ="")
if die_1 == die_2:
double_count += 1
if die_1 == 1 and die_2 == 1:
break
# Making sum
sum1 = sum1 + die_1
sum2 = sum2 + die_2
print("You finally got snake eyes on try number", roll_count)
print("Along the way you rolled a double", double_count,"times")
print(die_1)
print(die_2)
# Integer divisions
avg_roll1 = sum1 // roll_count
avg_roll2 = sum2 // roll_count
print("The average roll for die 1 was", avg_roll1)
print("The average roll for die 2 was", avg_roll2)
Got it myself.
Set the accumulator variable = to the die rolls. In this case sum1 and sum2 are the variables.
# make all of the functions in the "random" module available to this program
import random
while True:
#prompts user for valid number
user_s = int (input ("How many sides on your dice? "))
if user_s < 3:
print("That is not a valid size value, please enter a positive number")
if user_s >= 3:
break
print()
print("Thanks! Here we go...")
print()
double_count = 0
roll_count = 0
sum1 = 0 # Used to calculate sum of die_1
sum2 = 0 # Used to calculate sum of die_2
#while statement for die rolls
while True:
roll_count += 1
die_1 = random.randint(1,user_s)
sum1 += die_1
die_2 = random.randint (1,user_s)
sum2 += die_2
print(roll_count,".", " Die number 1 is ", die_1 , " and die number 2 is ", die_2, ".", sep ="")
if die_1 == die_2:
double_count += 1
if die_1 == 1 and die_2 == 1:
break
print("You finally got snake eyes on try number", roll_count)
print("Along the way you rolled a double", double_count,"times")
# Integer divisions
avg_roll1 = sum1 / roll_count
avg_roll2 = sum2 / roll_count
print("The average roll for die 1 was", format(avg_roll1,".2f"))
print("The average roll for die 2 was", format(avg_roll2,".2f"))

How to find the sum of two separate items of data in python, separately?

How can I restart the program?
I am trying to find the sum of the first set of data in the first loop and then the sum of the data in the second loop alone, but the sum in the last loop calculates the sum of the data in that loop and the one before. What mistake did I make?
import random, time
#Variables
die1 = 0
die2 = 0
goal = 0
tries1 = 0
tries2 = 0
sum = 0
#Asking for the player's names
player1 = input("What is your name, player1?")
player2 = input("What is your name, player2?")
#The "goal"
goal = random.randrange(5) + 1
print("The goal is:", goal)
while die1 != goal:
die1 = random.randrange(5) + 1
print(player1, "Your roll is:", die1)
tries1 = tries1 + 1
sum = sum + die1
print(sum)
while die2 != goal:
die2 = random.randrange(5) + 1
print(player2, "Your roll is:", die2)
tries2 = tries2 + 1
sum = sum + die2
print(sum)
You are missing re-initializing sum to 0 after the first loop.

Categories