import random
#Making sure all values are = to 0
one = 0
two = 0
three = 0
four = 0
five = 0
six = 0
#Loop for rolling the die 100 times
for r in range(0, 100):
roll = random.randint(1, 6)
if roll == 1:
one += 1
elif roll == 2:
two += 1
elif roll == 3:
three += 1
elif roll == 4:
four += 1
elif roll == 5:
five += 1
elif roll == 6:
six += 1
#print how many times each number was rolled
print(one)
print(two)
print(three)
print(four)
print(five)
print(six)
#How many times the 3 was rolled
print("The 3 was rolled", three, "times!")
#Average roll between all of them
print("The average roll was", (one * 1 + two * 2 + three * 3 + 4 * four + 5 * five + 6 * six)/100)
I am trying to make it so it prints out
"number is the most common roll." for whichever the roll is.
Just trying to do this is the most simple way, and I'm confused on how to do it. I tried to do like if one > two > three etc etc. but that did not work.
Choosing an appropriate data structure to gain maximum leverage of a language’s core features is one of the most valuable skills a programmer can develop.
For this particular use case, it’s best to use an iterable data type that facilitates operations (e.g. sort, obtain the maximum) on the collection of numbers. As we want to associate a number (1-6) with the number of times that number was rolled, a dictionary seems like the simplest data structure to choose.
I’ve re-written the program to show how its existing functionality could be re-implemented using a dictionary as its data structure. With the comments, the code should be fairly self-explanatory.
The tricky part is what this question is actually asking: determining the number rolled most often. Instead of manually implementing a sorting algorithm, we can use the Python built-in max function. It can accept an optional key argument which specifies the function that should be applied to each item in the iterable object before carrying out the comparison. In this case, I chose the dict.get() method which returns the value corresponding to a key. This is how the dictionary of roll results is compared by the number of rolls for each result for determining the number rolled most often. Note that max() only returns one item so in the case of a tie, only one of the results will be printed (see Which maximum does Python pick in the case of a tie?).
See also: How do I sort a dictionary by value?
import random
NUM_ROLLS = 100
DIE_SIDES = 6
# Create the dictionary to store the results of each roll of the die.
rolls = {}
#Loop for rolling the die NUM_ROLLS times
for r in range(NUM_ROLLS):
roll_result = random.randint(1, DIE_SIDES)
if roll_result in rolls:
# Add to the count for this number.
rolls[roll_result] += 1
else:
# Record the first roll result for this number.
rolls[roll_result] = 1
# Print how many times each number was rolled
for roll_result in range(1, 7):
print("The number", str(roll_result), "was rolled", str(rolls[roll_result]), "times.")
#How many times the 3 was rolled
print("The number three was rolled", str(rolls[3]), "times.")
#Average roll between all of them
sum = 0
for roll_result in rolls:
sum += roll_result * rolls[roll_result]
print("The average roll result was", str(sum/NUM_ROLLS))
# The number rolled most often.
print(str(max(rolls, key=rolls.get)), "is the most common roll result.")
Related
import random
money=int(0) # money starts at 0 always
bet=int(input("enter a bet.")) # user inputs a bet.
winningnumber=(random.randint(0,30)) # chooses random integer from 0 - 30, stores it as variable winningnumber
number = int(input("Pick a number 0-30"))
if number % 2 == 0: #checks if number is divisible by 2
print("The number was even, you get 2x your money.") #prints the users winnings
money = float(bet) * float(2) # multiplies the bet by 2
else:
money = bet+0 # doesnt add anyuthing to the bet
if number % 10 ==0: #checks if number is divisible by 10
print("The number was a multiple of 10, you get 3x your money.") #prints the users winnings
money = bet*3 # multiplies the bet by 3
else:
money = bet+0 # doesnt add anyuthing to the bet
primenum = ["3","5","7","11","13","17","19","23","29"] #list of prime numbers
if number == primenum ==0: #if number chosen by user = one of the numbers on the list, the user wins.
print("The number was a prime number, you get 5x your money.") #prints the users winnings
money = bet*5 # multiplies the bet by 5
else:
money=bet+0 # doesnt add anything to the bet
print("the winning number was",winningnumber) #shows the player the winning number
print("Your money for the end of the round is",money) #prints money at end of round
Why doesn't this code work? I have tried multiple different ways yet the bet doesn't seem to multiply.
I was expecting the code number to be multiplied at the end.
You have three different if-else blocks. All three do different things to money if their respective conditions evaluate to True. However, if the last if-else block evaluates False, then regardless of what happened in the previous if-else blocks, the code in the final else block will run. That code sets money back to the original bet.
You can see this happening if you introduce print (money) after each if-else block and re-run your code.
Also - it's not clear to me how number == primenum == 0 would ever evaluate to True. primenum is a list of strings. number is an int. Therefore, this condition will never evaluate to True.
If what you're trying to do is check whether number is prime, then I would (first), define primenum as a list of integers, like so:
primenum = [3,5,7,11,13,17,19,23,29] #list of prime numbers
and then, change the criterion in your last if-else block to:
if number in primenum:
One way to make your if-else blocks work would be to use if-elif-else, like so:
import random
money=int(0) # money starts at 0 always
bet=int(input("enter a bet.")) # user inputs a bet.
winningnumber=(random.randint(0,30)) # chooses random integer from 0 - 30, stores it as variable winningnumber
primenum = [3,5,7,11,13,17,19,23,29] #list of prime numbers
number = int(input("Pick a number 0-30"))
if number % 10 == 0:
print("The number was a multiple of 10, you get 3x your money.") #prints the users winnings
money = float(bet) * float(2)
elif number % 2 == 0:
print("The number was even, you get 2x your money.") #prints the users winnings
money = bet*3
if number in primenum: #if number chosen by user = one of the numbers on the list, the user wins.
print("The number was a prime number, you get 5x your money.") #prints the users winnings
money = bet*5 # multiplies the bet by 5
else:
money=bet+0 # doesnt add anything to the bet
print("the winning number was",winningnumber) #shows the player the winning number
print("Your money for the end of the round is",money) #prints money at end of round
Bear in mind that "winningnumber" hasn't played a role in the program at all - except to be generated at the start, and printed to screen at the end. The above may not reflect your original intent, it's just ONE way in which the control-flow could be made to work so you reliably modify money when any of the three conditions evaluates to True.
The problem with your code relates to the multiple if-else blocks.
You have a problem with your prime number section, which will always equate to False, and as such you will set money=bet+0 - which will override any other successful changes made to money.
Your winning number does not seem to have any impact on the flow of code, so as long as you choose an even number or a number divisible by 10, it should multiply. But then when you get to the section to test if it is a prime number, it will ALWAYS equate to FALSE, and as mentioned before will set money=bet+0 - and undo anything done prior.
You need to make sure that you set money = money + (bet + 0)
This way your cumulative effects are maintained. You have to do this for the other money calculations as well.
And you need to fix the prime number section:
primenum = [3,5,7,11,13,17,19,23,29]
if number in primenum:
...
Here is the complete code based on what I think you were trying to do:
import random
money=0 # money starts at 0 always
bet=int(input("enter a bet.")) # user inputs a bet.
winningnumber=(random.randint(0,30)) # chooses random integer from 0 - 30, stores it as variable winningnumber
number = int(input("Pick a number 0-30"))
primenum = [3,5,7,11,13,17,19,23,29] #list of prime numbers
if winningnumber == number:
if number % 2 == 0: #checks if number is divisible by 2
print("The number was even, you get 2x your money.") #prints the users winnings
money = money + (bet * 2) # multiplies the bet by 2
else:
money = money + (bet + 0) # doesn't add anything to the bet
if number % 10 == 0: #checks if number is divisible by 10
print("The number was a multiple of 10, you get 3x your money.") #prints the users winnings
money = money + (bet * 3) # multiplies the bet by 3
else:
money = money + (bet + 0) # doesn't add anything to the bet
if number in primenum: #if number chosen by user = one of the numbers on the list, the user wins.
print("The number was a prime number, you get 5x your money.") #prints the users winnings
money = money + (bet * 5) # multiplies the bet by 5
else:
money = money + (bet + 0) # doesn't add anything to the bet
print("the winning number was",winningnumber) #shows the player the winning number
print("Your money for the end of the round is",money) #prints money at end of round
This is what the instructions are telling me to do...
main – This function is the main routine. It should do the following:
Ask the user how many dice they want to roll. If the user enters a number less than 1 or greater than 10, the program should continue to ask the user for a valid number between 1 and 10. Remember you can use a while loop to do input validation.
Once the program has a valid number from the user, it should use that number as an argument when calling the roll_dice function.
roll_dice – This function has one parameter, num_dice, which is the number of dice to roll.
Since the program will be displaying the total of the dice, start by initializing a variable to 0 which will keep a running total.
Use a for loop to roll each die the number of times specified.
Use the randint function from the random module to get a random digit between 1 and 6 inclusive.
Print the number of the loop iteration and the die value as indicated in the Sample Output.
Make sure to update the running total INSIDE the for loop.
After the for loop is complete, print the total value of all the dice that were rolled.
And this is the code I have so far:
import random
def main():
num_dice = int(input('How many dice do you want to roll?'))
while num_dice < 1 or num_dice > 10:
print('Enter a number between 1 and 10.')
num_dice = (input('How many dice do you want to roll?'))
roll_dice(num_dice)
def roll_dice(num_dice):
rolls = 0
for i in range(num_dice):
print(f'Roll #', rolls, random.randint(1, 6))
rolls+=1
main()
There's a few improvements:
you typically don't want to repeat code, so it would be better to only have the input statement in there once (that would have also avoided the mistake you made on the second one);
you are asked to return a sum total of rolls, but also to print each roll; you can either compute it before printing, or print the assigned value directly (with a walrus operator :=)
once you have the total, you'll need to do something with it, like print it.
Something like:
import random
def main():
# you can loop 'forever' and then break out under the right condition
while True:
# you'd forgotten one of the int()
num_dice = int(input('How many dice do you want to roll?'))
if num_dice < 1 or num_dice > 10:
print('Enter a number between 1 and 10.')
else:
break
result = roll_dice(num_dice)
print(f'The total for {num_dice} rolls was {result}.')
def roll_dice(num_dice):
rolls = 0
for i in range(1, num_dice + 1):
# you printed rolls, but you want i, starting at 1
# roll := something, causes roll to be assigned, but also returns the value
print(f'Roll #{i} = {(roll := random.randint(1, 6))}')
rolls += roll
return rolls
main()
(Edit: I noticed that you were already using an f-string in roll_dice, so you may as well make actual use of it)
I like #Blckknght's suggestion for another nice use of the walrus operator in a shorter version of main():
def main():
# you can loop 'forever' and then break out under the right condition
while (n := int(input('How many dice do you want to roll?'))) < 1 or n > 10:
print('Enter a number between 1 and 10.')
result = roll_dice(n)
print(f'The total for {n} rolls was {result}.')
Beware though: if someone asks you to explain your code, you better know what's going on here:
due to short-circuit evaluation, the first part of the or in the while is executed first, and the second part is only executed if the first part is False; that's why you can use the := in the first part and know that num_dice will have been updated for the second part;
the walrus operator assigns the righthand value, but also returns it, so it can be compared to 1
def main():
num_dice = int(input('How many dice do you want to roll?'))
while num_dice < 1 or num_dice > 10:
print('Enter a number between 1 and 10.')
num_dice = (input('How many dice do you want to roll?'))
roll_dice(num_dice)
def roll_dice(num_dice):
rolls = 0
for i in range(num_dice):
print(f'Roll #', rolls, random.randint(1, 6))
out_ran_num = random.randint(1, 6)
rolls+=out_ran_num
return rolls
main()
Please check indentation
First, we want to keep asking the user how many dice they want to roll until they give a valid input, we can do that with a while loop like so:
valid_integer = False
# While the user hasn't given a valid integer
while valid_integer == False:
# Note: this will crash if the user does not input a number
num_dice = int(input('How many dice do you want to roll?'))
# Checking if the input is valid
if num_dice < 1 or num_dice > 10:
print("Please enter a number between 1 and 10")
# Because we did not change the variable valid_integer, it will loop again
else:
valid_integer = True
print(roll_dice(num_dice))
Now we need to create the roll_dice function, it needs to take one parameter (the number of dice to roll) and return a integer (the total of the dice rolls)
import random
# num_dice: int is known as type hinting, it is used to indicate the type of a value
def roll_dice(num_dice: int):
total = 0
for i in range(num_dice):
roll = random.randint(1, 6)
total += roll
return total
Now we can put the code together! We need to put the loop in a function main() and call it. Don't forget your imports!
import random
def main():
valid_integer = False
# While the user hasn't given a valid integer
while valid_integer == False:
# Note: this will crash if the user does not input a number
num_dice = int(input('How many dice do you want to roll?'))
# Checking if the input is valid
if num_dice < 1 or num_dice > 10:
print("Please enter a number between 1 and 10")
# Because we did not change the variable valid_integer, it will loop again
else:
valid_integer = True
print(roll_dice(num_dice))
# num_dice: int is known as type hinting, it is used to indicate the type of a value
def roll_dice(num_dice: int):
total = 0
for i in range(num_dice):
roll = random.randint(1, 6)
total += roll
return total
if __name__ == "__main__":
main()
more info on if __name__ == "__main__" What does if __name__ == "__main__": do?
In main function in while loop there should int for taking input and should use roll_dice function outside while loop. there should be return word to get total as shown in figure
In roll_dies function there should should be rolls+=random.randint(1,6) and also
return rolls outside for loop
So I'm a beginner programmer and I'm trying to calculate the number of rolls it would take for two dice to add up to the sum of 11. This is the code I tried, but every time I run this, it gives me the output 'None'. What am I doing wrong here?
from random import randint
def die_roll1():
return(randint(1, 6))
def die_roll2():
return(randint(1,6))
def roll_sum():
sum = die_roll1() + die_roll2()
count = 2
if sum == 11:
return(count)
else:
count +=2
roll_sum()
print("The number of rolls are: ", roll_sum())
You are not returning the result of roll_sum() in the else block. However, consider using a while loop instead, as recursion for simpler cases is generally unpythonic:
import random
tries = 1
while True:
a, b = random.randint(1, 6), random.randint(1, 6)
if a + b == 11:
winning = [a, b]
break
tries += 1
Output:
22
[5, 6]
Technically, you simply need to return the count after the else portion. If you roll two non-11s, then the result is never passed recursively through all function calls, so it gets lost in limbo and returns None.
However, your code would never produce a number other than 4 in this case because you reset the count variable to 2 every time you roll an 11.
This can be fixed by making your count variable global (outside the function), and then incrementing it inside the function. This can also be fixed by declaring the variable outside of a while loop.
Iterative programs are nearly always more readable than recursive ones, and your program for this problem should definitely be iterative. The other answers give you an iterative solution.
But as nobody has shown you exactly how to correct your own (recursive) program, I'll do that. I think there are a few things you can learn which will help you (and other beginners) in the long run.
Here's the corrected code.
from random import randint
def die_roll():
return(randint(1, 6))
def roll_sum(count):
sum = die_roll() + die_roll()
if sum == 11:
return(count)
else:
count += 2
return roll_sum(count)
# Call roll_sum with 2 as your initial count
roll_sum(2)
Explanation
When your if statement block has a return statement, your else block should ALWAYS have a return statement too (and so should any elif blocks). If Python doesn't find an explicit return statement (this is what happens in your original program), it returns a special object called None.
So you need to make sure that every possible flow through your function leads to a return statement. Preceding your recursive call in your else block fixes this problem.
Initializing count = 2 inside your roll_sum function results in 2 being assigned to count every single time that the function is (recursively) called. This is obviously not what you want. Instead, you can add a function argument called count, which will solve this problem.
In your initial call of roll_sum, you will have to pass the initial value of count.
There is no need of having 2 functions which do exactly the same thing -- die_roll1 and die_roll2. A function is only supposed to encapsulate a functionality. You can instead just call the same function twice. If you want to make it explicit that you have 2 separate dice rolls, you can just add 2 variables.
roll1 = die_roll()
roll2 = die_roll()
sum = roll1 + roll2
All the best!
Here are several simple solutions to calculate the number of times each sum occurs in the rolling of two dice. To answer your specific problem, you would simply need to use the 'Specific Solution' in place of the 'General Solution' below.
dice1 = [1,2,3,4,5,6]
dice2 = [1,2,3,4,5,6]
totals = []
for num in dice1:
for roll in dice2:
sumz = str(num+roll)
if [sumz, 0] not in totals:
temp = [sumz, 0]
totals.append(temp)
for item in totals:
for num in dice1:
for roll in dice2:
# General Solution - sum of all roles
sumz2 = str(num+roll)
if sumz2 == item[0]:
item[1] += 1
# Specific Solution - only count number of 11's rolled
if sumz2 == '11':
if item[0] == '11':
item[1] += 1
print(totals)
# Using a dictionary to count
totals = {}
for num in dice1:
for roll in dice2:
sumz = str(num+roll)
if sumz not in totals:
totals[sumz] = 1
else:
totals[sumz] += 1
print(totals)
# using collections
from collections import Counter
# temp list to hold all sumz, including multiple entries of same value
temp = []
for num in dice1:
for roll in dice2:
temp.append(num+roll)
# unsorted dictionary of key value pairs
d = Counter(temp)
list_sorted_by_key = []
for i in sorted (d):
temp2 = (i, d[i])
list_sorted_by_key.append(temp2)
print(list_sorted_by_key)
rounds = input()
for i in range(int(rounds)):
score = input(int())[0:3]
a = score[0]
d = score[2]
antonia = 100
david = 100
for scores in score:
if a < d:
antonia -= int(a)
if a > d:
david -= int(d)
elif a == d:
pass
print(antonia)
print(david)
Input Expectation:
The first line of input contains the integer n (1 ≤ n ≤ 15), which is the number of rounds that
will be played. On each of the next n lines, will be two integers: the roll of Antonia for that round,
followed by a space, followed by the roll of David for that round. Each roll will be an integer
between 1 and 6 (inclusive).
Output Expectation: The output will consist of two lines. On the first line, output the number of points that Antonia has
after all rounds have been played. On the second line, output the number of points that David has
after all rounds have been played.
Input:
4
5 6
6 6
4 3
5 2
Output:
100 <--(WHY???)
94
Why is the bottom value(david) changed as it should correctly, but the top is not?? What am I doing different for antonia thats making it not output the same function as david?
Within your first loop, you continuously update a and d. So, at the end of the loop, a and d simply have the values corresponding to the last set of input.
Additionally, within your second loop, you are not iterating over all the scores, but rather the very last set of input. Before going any further, I would suggest you go back and understand what exactly your code is doing and trace how values change.
In any case, one way to solve your problem is:
rounds = input("Number of rounds: ")
scores = []
for i in range(int(rounds)):
score = input("Scores separated by a space: ").split()
scores.append((int(score[0]), int(score[1]))) #Append pairs of scores to a list
antonia = 100
david = 100
for score in scores:
a,d = score # Split the pair into a and d
if a < d:
antonia -= int(a)
if a > d:
david -= int(d)
elif a == d:
pass
print(antonia)
print(david)
This is my homework question:
Write a program that simulates rolling a set of six-sided dice multiple times. The program should use a dictionary to record the results and then display the results.
Input: The program should prompt for the number of dice to roll and the number of times to roll the dice.
Output:
The program is to display how many times each possible value was rolled. The format of the output must be as shown below:
The first column is the number shown on the dice when they are rolled. The brackets are only as wide as needed and the number inside the brackets is right justified. Note the minimum and maximum values in the sample runs below.
The second column is the number of times that value was rolled. This column is right justified.
The last column is the percent of times that the number was rolled. The percentages are displayed with an accuracy of one decimal place.
This is the code I have so far:
import random
from math import floor, ceil
one = 0
two = 0
three = 0
four = 0
five = 0
six = 0
rand = float(0)
rolltotal = int(input("How many times do you want to roll? "))
q = 0
while q < rolltotal:
q = q + 1
rand = ceil(6*(random.random()))
if rand == 1:
one = one + 1
elif rand == 2:
two = two + 1
elif rand == 3:
three = three + 1
elif rand == 4:
four = four + 1
elif rand == 5:
five = five + 1
else:
six = six + 1
total = one + two + three + four + five + six
print("[1]", one, " ",round(100*one/total, 1),"%")
print("[2]", two, " ",round(100*two/total, 1),"%")
print("[3]", three, " ",round(100*three/total, 1),"%")
print("[4]", four, " ",round(100*four/total, 1),"%")
print("[5]", five, " ",round(100*five/total, 1),"%")
print("[6]", six, " ",round(100*six/total, 1),"%")
My question is: I just know how to roll one dice. how can i get more than one .
from collections import defaultdict
import random
dice = int(input("How many dice do you want to roll? "))
rolls = int(input("How many times do you want to roll them? "))
irange = xrange
sides = [1,2,3,4,5,6]
d = defaultdict(int)
for r in irange(rolls):
d[sum( random.choice(sides) for d in irange(dice) )] += 1
total = float(rolls)
for k in sorted(d.keys()):
print "[%d] %d %.1f%%" % (k, d[k], 100.0*d[k]/total)
You would rather do the following:-
loop=True
import random #This allows python to import built in "random" function.
while loop is True:
dice=input("Which sided dice would you like to roll? (You can only choose 4,6 or 12) \n") # "\n" allows python to add a new line.
if dice=="4":
print("You have chosen to roll dice 4\nYour score is... \n", random.randint(1,4)) #This allows python to generate a random number from 1 to 4.
elif dice=="6":
print("You have chosen to roll dice 6\nYour score is...\n", random.randint(1,6)) #This allows python to generate a random number from 1 to 6.
elif dice=="12":
print("You have chosen to roll dice 12\nYour score is...\n", random.randint(1,12)) #This allows python to generate a random number from 1 to 12.
else: print("Invalid option! Please try again!")
loop2=input("Do you want to roll again? (Yes or No) \n")
if loop2=="yes" or loop2=="Yes": # "or" funtion allows python to accept any of the two answers input by the user.
loop=True
else: break # This function allows program to close.