So i'm stuck with this problem, how can i add something within a function and print it from out of the function
import random
def dieRoll():
sum = 0
for i in range (die-1):
dieThrow = random.randrange( 1, sides+1)
sum += dieThrow
print(dieThrow)
print("That totals: ", sum)
return i
players = int(input("How many players are rolling dice? "))
die = int(input("How many dice does each player roll? "))
sides = int(input("How many sides does each die have? "))
for a in range(1, players+1):
print("Player",a, "rolled: ")
print(dieRoll())
it's supposed to look something like:
Player 1 rolled:
5
4
9
that totals: 18
but i'm getting something like:
Player 1 rolled:
5
4
that totals: 9
9
i feel like the answer is right in front of me but i just can't see it
it's because you print what the function return in the end, if you want such output you have two choices :
print(i)
return("That totals: ", sum)
or the other choice :
print(i)
print("That totals: ", sum)
#replace print(dieRoll())
dieRoll()
The problem is the line
for i in range (die-1):
Try this instead:
for i in range(0, die):
The thing is, the range function by default starts at 0 and "stops" when it gets to the last number (does not execute it), meaning you are not geting to do that last dice roll you expected.
Hope it helps.
Related
Im trying to make a loop where I start with 5 random dice rolls. the values 1,3,4, and 6 are added up for your score, while 2s and 5s are not counted and subtract the combined amount of dice rolled with 2s and 5s from the amount of dice rolled the next turn. I can't quite figure out how to get the sum of only the dice that rolled 1,3,4,6 and roll a lesser amount of dice the next turn based off ho many dice were 2 or 5
#Stuck in the Mud Dice Game
Exit = 0
Rolls = int(5)
score = 0
def RollDice():
totalsum = 0
for die in range(0, Rolls):
number = random.randint(1,6)
print("die", die + 1, ":", number)
totalsum += number
print("score: ", totalsum)
def Menu():
print("1. Roll Dice")
print("2. Exit Program")
print()
choice = int(input("Enter option here: "))
if(choice == 1):
RollDice()
if(choice == 2):
Exit()
Menu()
In the for-loop, use an if statement:
if number==2 or number==5:
Rolls -= 1
else:
totalsum += number
I suppose that you also need to start your function RollDice like this:
def RollDice():
global Rolls
...
otherwise, it might only locally (i.e., within the function) assign a new value to the variable.
Or do you mean the number of Rolls should be different when you re-start the program? This can only be done by writing the value to a file.
I need help condensing my Yahtzee code. I'm familiar with loops, but I can't seem to figure out how to do it without wiping my roll each turn. It's set up to roll 5 random dice and then you choose which you want to keep. It will then roll what's left for three total rolls. I thought of making a placeholder list, but I can't make it work that way either.
Dice = [‘⚀ ’,‘⚁ ‘,’ ⚂ ‘,’ ⚃ ‘,’ ⚄ ‘,’ ⚅ ‘]
turns = 3
#first roll
first_roll = []
for _ in range(5):
roll = random.choice(dice)
first_roll.append(roll)
print(first_roll)
turns -= 1
print(f'You have {turns} turns left.')
keep = input("Which dice would you like to keep? 1 - 5: ").split()
clear()
#second roll
second_roll = []
for i in keep:
x = int(i)
j = first_roll[x-1]
second_roll.append(j)
remainder = 5 - len(second_roll)
for _ in range(remainder):
roll = random.choice(dice)
second_roll.append(roll)
print(second_roll)
turns -= 1
print(f'This is your last turn.')
keep = input("Which dice would you like to keep? 1 - 5: ").split()
clear()
#third roll
third_roll = []
for i in keep:
x = int(i)
j = second_roll[x-1]
third_roll.append(j)
remainder = 5 - len(third_roll)
for _ in range(remainder):
roll = random.choice(dice)
third_roll.append(roll)
print(third_roll)
So I'm not sure if this is exactly what you're looking for, but I created a function that lets you continuously roll for X turns and the dice pool gets progressively smaller like your code shows. I thoroughly commented the code to hopefully give you a good explanation to what I'm doing.
import random
#Dice characters
dice = ['1','2','3','4','5','6']
#Number of turns player has
turns = 3
#This is the group of dice kept by the player
kept_dice = []
def roll():
#This is the group of dice randomly chosen
rolled_dice = []
#Generate up to 5 random dice based on how many have been kept so far
for _ in range(5 - len(kept_dice)):
#Append random dice value to rolled_dice array
rolled_dice.append(random.choice(dice))
#Print roll group
print(rolled_dice)
dice_to_keep = int(input("Which dice would you like to keep? 1 - 5: "))
kept_dice.append(rolled_dice[dice_to_keep-1])
while turns != 0:
#Let the user know how many turns they have left
print(f'You have {turns} turns left.')
#Roll dice
roll()
#Subtract 1 turn
turns -= 1
#After all turns, show the kept dice:
print("Kept dice:")
print(kept_dice)
I have been tasked to write at least one function to simulate the rolling of dice and call that function in a loop for each player, find the total sum of dice roll though find myself heavily suffering from analysis paralysis.
sample output
How many players are rolling dice? 2
How many dice does each player roll? 3
How many sides does each die have? 6
Player 1 rolled:
4
2
4
That totals: 10
Player 2 rolled:
1
3
5
That totals: 9
My code so far
import random
#User inputs
r = int(input("How many times do you want to roll the dice? "))
s = int(input("how many sides do you want "))
p = int(input("How many players are rolling dice?"))
#Function Declaration
def Rolldice(s,r):
for i in range(0,r):
die = random.randint(1, s)
print(die)
#For loop that iterates through function declaration
for num in range(1,p+1):
print(f"player {num} rolled")
Rolldice(s,r)
print(sum(Rolldice))
Though i am receiving error listed below
TypeError: 'function' object is not iterable
The error is caused by the last line print(sum(Rolldice)). Rolldice is a function, you cannot sum over function. I suppose this should solve your problem -
import random
#User inputs
r = int(input("How many times do you want to roll the dice? "))
s = int(input("how many sides do you want "))
p = int(input("How many players are rolling dice?"))
#Function Declaration
def Rolldice(s,r):
dies = []
for i in range(0,r):
die = random.randint(1, s)
print(die)
dies.append(die)
return dies
#For loop that iterates through function declaration
for num in range(1,p+1):
print(f"player {num} rolled")
dies = Rolldice(s,r)
print("That totals:", sum(dies))
The problem comes from your last line:
print(sum(Rolldice))
You are actually passing a function to the sum() function. But if you check the documentation for sum(), it actually requires an iterable to be passed as an argument.
You should actually try to sum the results of your dice direcly in the RollDice function, and return the result.
def Rolldice(s,r):
total = 0
for i in range(0,r):
die = random.randint(1, s)
print(die)
sum += die
return total
Now, you can finally print the total in your main function:
for num in range(1,p+1):
print(f"player {num} rolled")
total = Rolldice(s,r)
print(f"That totals: {total}")
You're cannot iterate over a function. However, you can iterate over it's results.
The first step to fix the code is to call the function and pass its results to sum instead of passing the function itself.
(You do call the function in the previous line but you don't use it's result in sum. This line could be removed.)
Replace print(sum(Rolldice)) with print(sum(Rolldice(s, r))).
Another problem is that you don't return value from the function. You just print it on the screen with print.
Normally returning a value is done via the keyword return but in this case you want to return multiple values. You could create an array of all the values and return it. It is nicely shown in the Vishwas Chepuri's answer.
However, in this case, you could use a generator. In simple words, it's a type of function that can be iterated over and return multiple values.
You can convert a normal function into a generator by returning value via yield keyword instead of return. In opposite to return, yield doesn't end the function.
Replace print(die) with yield die.
import random
#User inputs
r = int(input("How many times do you want to roll the dice? "))
s = int(input("how many sides do you want "))
p = int(input("How many players are rolling dice?"))
#Generator Declaration
def Rolldice(s,r):
for i in range(0,r):
die = random.randint(1, s)
yield die
#For loop that iterates through function declaration
for num in range(1,p+1):
print(f"player {num} rolled")
generator = Rolldice(s,r)
print(sum(generator))
BTW, you can write range(r), instead of range(0,r). It means the same.
import random
def Dice():
num_dice = raw_input("How many dice are you rolling? ")
user_dice = raw_input("How many sides do you want on your dice? ")
user_diceint = int(user_dice)
dice_rolling1 = random.randint(0, user_diceint)
print dice_rolling, "was your dice roll."
if user_dice > 0 and user_dice.isdigit():
print "This is correct."
if len(num_dice) <= 0:
num_dice = 2
print num_dice, "is the number of dice you rolled"
print num_dice * user_dice, "is your total roll"
else:
print "Number of Dice has an error"
else:
print "This is not a number."
So I am new to coding/programming and I thought I would try my hand at doing a Dice roll generator. So in the code I have num_dice which is the number of dice("duh"). But I was wondering how would I do a different randint for each of the dice. So say someone enters '5' dice. How would I get my code to generate 5 different randomints to simulate 5 actual dice being rolled? Would some kind of loop work for this? Please excuse the bad code, I am new and it's still being worked on! Thank you.
You can put a for loop in your Dice function to handle that
def Dice():
num_dice = int(raw_input("How many dice are you rolling? "))
user_dice = int(raw_input("How many sides do you want on your dice? "))
for roll in range(1, num_dice+1):
dice_roll = random.randint(1, user_dice)
print "Roll number", roll, "was: ", dice_roll
Example
num_dice = 5 # 5 rolls
user_dice = 8 # 8 sided dice
Output
Roll number 1 was: 2
Roll number 2 was: 1
Roll number 3 was: 8
Roll number 4 was: 4
Roll number 5 was: 6
You can do that by creating a list of rolling dice num_dice times:
list_of_values = [random.randint(0, user_diceint) for _ in range(num_dice)]
Your Code
def Dice():
num_dice = raw_input("How many dice are you rolling? ")
user_dice = raw_input("How many sides do you want on your dice? ")
user_diceint = int(user_dice)
list_of_values = [random.randint(0, user_diceint) for _ in range(num_dice)]
print list_of_values, "were your dice rolls."
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.