• Support PF! Buy your school textbooks, materials and every day products Here!

Python Dice Rolling Game

  • Comp Sci
  • Thread starter jdawg
  • Start date
  • #1
365
2

Homework Statement



I want to prompt the user to input how many times they want to roll a die, then generate a random number between 1 and 6. I then need to print what their number is and if it is even or odd.

The code I posted below is what I came up with for a single die roll that allows the user to roll every time they press enter, prints their number, and prints even or odd depending on their roll.

I have been trying to modify my single die roll code to allow for the user to input how many times they want to roll the die instead of hitting enter each time, but nothing I try seems to work. I've seen some people write functions for their dice games, maybe that would be a better route?

I just started teaching myself Python a few days ago, so over explanations are more than appreciated. Thanks for any help!


Homework Equations




The Attempt at a Solution


[/B]
upload_2018-10-15_13-6-29.png



# Single Dice Roll

import random


repeat = True


while repeat:

Die = str(random.randint(1,6))

print("Your roll was a " + Die)



if Die == "1" or Die == "3" or Die == "5":

print("You rolled an odd number")

elif Die == "2" or Die == "4" or Die == "6":

print("You rolled an even number")



print("Roll again?")



repeat = "Yes" in input()
 

Attachments

Answers and Replies

  • #2
StoneTemplePython
Science Advisor
Gold Member
2019 Award
1,146
550
have you tried

Python:
number_of_rolls = input()
then, supposing the user inputs a valid number, you can take

int(number_of_rolls)

as the number of rolls desired... note: I think you are using Python 3.x. In Python 2.x. it was raw_input().
 
  • #3
365
2
Thanks for the idea! Yes I am using version 3.
Here is what I did, I think something is still wrong, maybe I didn't close the loop? It just keeps rolling the die over and over again.
upload_2018-10-15_18-53-37.png
 

Attachments

  • #4
33,314
5,006
That's because your while loop essentially runs forever. Your while statement
Python:
while Number_of_Rolls:
has a condition (a string) that is always true unless it's an empty string.

The statement at the end of your loop,
Python:
int(Number_of_Rolls)
isn't doing anything useful. The numeric digit in the string is converted to an integer, but it isn't saved to a variable, so this conversion isn't useful.

A better strategy would be this:
  • Take input from the user on how many rolls of the die.
  • Convert that input value to a number. E.g., rolls = int(Number_of_Rolls)
  • Use that number to control a for loop, not a while loop. (A while loop can be used, but if you know how many times a loop should be executed, the better choice is a for loop.)
Your input statement in the 2nd line returns a string that contains a number digit. Your while condition is testing whether the string the user entered is considered true -- that's not what you want.
 
Last edited:
  • #5
365
2
That's because your while loop essentially runs forever. Your while statement
Python:
while Number_of_Rolls:
has a condition (a string) that is always true unless it's an empty string.

The statement at the end of your loop,
Python:
int(Number_of_Rolls)
isn't doing anything useful. The numeric digit in the string is converted to an integer, but it isn't saved to a variable, so this conversion isn't useful.

A better strategy would be this:
  • Take input from the user on how many rolls of the die.
  • Convert that input value to a number. E.g., rolls = int(Number_of_Rolls)
  • Use that number to control a for loop, not a while loop. (A while loop can be used, but if you know how many times a loop should be executed, the better choice is a for loop.)
Your input statement in the 2nd line returns a string that contains a number digit. Your while condition is testing whether the string the user entered is considered true -- that's not what you want.
Oh ok, using a for loop makes sense! And it makes sense why you're converting the number of rolls into an integer. I've been searching for for loop examples that use the user specified number to control the loop, but I can only seem to find very basic examples that don't quite explain what I need. Is there an example you could give me that could show me what you're trying to tell me to do? Thanks.
 
  • #6
33,314
5,006
Oh ok, using a for loop makes sense! And it makes sense why you're converting the number of rolls into an integer. I've been searching for for loop examples that use the user specified number to control the loop, but I can only seem to find very basic examples that don't quite explain what I need. Is there an example you could give me that could show me what you're trying to tell me to do? Thanks.
Here's the idea:
Python:
NRolls = input("Enter number of rolls...")
N = int(NRolls)

for i in range(N):
    # add the code to generate the number for a roll of the die
    print ("i: ", i)
Here's the output from this code:

Code:
C:\Users\Mark\Documents\Python3.4.2>python test3.py
Enter number of rolls...5
i:  0
i:  1
i:  2
i:  3
i:  4
Also, when you post code, don't post a screen shot (the one you posted is barely readable, with faint letters on a black background). The code is just text, so it's better to just post the text. Use BBCode code tags, like so
[code=python]
# Your code goes here
[/code]
People seeing your post won't see the opening and closing code tags -- the browser consumes them when it formats the code.
 
  • Like
Likes jdawg
  • #7
365
2
Thanks, that was definitely a step in the right direction! Also thanks for the code posting tip, I didn't know how to do that.

Python:
# Multiple Dice Rolls

import random

NRolls = input("Enter number of rolls...")
N = int(NRolls)                                

for Die in range(N):
    Die = str(random.randint(1,6))
    print("Your roll was a " + Die)
  
    if Die == "1" or Die == "3" or Die == "5":
        print("You rolled an odd number")
    elif Die == "2" or Die == "4" or Die == "6":
        print("You rolled an even number")
      
    print ("Die: ", Die)
The result is almost what I wanted, it still came out a little funky though:

Code:
Enter number of rolls...
Your roll was a 3
You rolled an odd number
Die:  3
Your roll was a 1
You rolled an odd number
Die:  1
Your roll was a 1
You rolled an odd number
Die:  1

So from my understanding, you store the user's input in the variable NRolls, then convert NRolls into an integer which is stored in the variable N. Then this N variable gets put into the range function, which will iterate your for loop N times.

What exactly does this part of the code do?:

Python:
print ("Die: ", Die)
 
  • #8
33,314
5,006
So from my understanding, you store the user's input in the variable NRolls, then convert NRolls into an integer which is stored in the variable N. Then this N variable gets put into the range function, which will iterate your for loop N times.
Yes.

What exactly does this part of the code do?:
Python:
print ("Die: ", Die)
It prints the string "Die: " and the current value of your loop control variable, Die.

Your code has a bug.
Python:
# Multiple Dice Rolls

import random

NRolls = input("Enter number of rolls...")
N = int(NRolls)
for Die in range(N):
    Die = str(random.randint(1,6))
    print("Your roll was a " + Die)
  
    if Die == "1" or Die == "3" or Die == "5":
        print("You rolled an odd number")
    elif Die == "2" or Die == "4" or Die == "6":
        print("You rolled an even number")
      
    print ("Die: ", Die)
You are using Die for two different purposes, which is not good. If N gets set to 5, say, then Die will be set in turn to 0, 1, 2, 3, 4, and 5 in the six iterations of your loop. In the first line in the body of your for loop, you are reusing Die for the number of "pips" on the upper face of the die.

You need a different variable for this. I suggest changing your loop control variable (now Die) to RollNo.
 
  • Like
Likes jdawg
  • #9
wle
307
136
A lot of people use the variable name _ (underscore) for variables that are required by the language but aren't actually going to be used, e.g.
Python:
for _ in range(n):
    # ...
when you just want to repeat something ##n## times and don't care about the loop counter.

The normal way to test if a number is even or odd is with the modulo operator: n % 2 == 0.

If an integer is not odd then it is definitely even. There is no need to test it a second time.

You can avoid typing print("You rolled an ... number") twice by storing one of the strings 'even' or 'odd' in a variable and printing the variable. You might find the String format method and if expression useful.
 
  • Like
Likes jdawg
  • #10
365
2
Yes.

It prints the string "Die: " and the current value of your loop control variable, Die.

Your code has a bug.
Python:
# Multiple Dice Rolls

import random

NRolls = input("Enter number of rolls...")
N = int(NRolls)
for Die in range(N):
    Die = str(random.randint(1,6))
    print("Your roll was a " + Die)
 
    if Die == "1" or Die == "3" or Die == "5":
        print("You rolled an odd number")
    elif Die == "2" or Die == "4" or Die == "6":
        print("You rolled an even number")
     
    print ("Die: ", Die)
You are using Die for two different purposes, which is not good. If N gets set to 5, say, then Die will be set in turn to 0, 1, 2, 3, 4, and 5 in the six iterations of your loop. In the first line in the body of your for loop, you are reusing Die for the number of "pips" on the upper face of the die.

You need a different variable for this. I suggest changing your loop control variable (now Die) to RollNo.

It's working now!! I really appreciate the quick replies, thanks so much for all your help!
 
  • #11
365
2
A lot of people use the variable name _ (underscore) for variables that are required by the language but aren't actually going to be used, e.g.
Python:
for _ in range(n):
    # ...
when you just want to repeat something ##n## times and don't care about the loop counter.

The normal way to test if a number is even or odd is with the modulo operator: n % 2 == 0.

If an integer is not odd then it is definitely even. There is no need to test it a second time.

You can avoid typing print("You rolled an ... number") twice by storing one of the strings 'even' or 'odd' in a variable and printing the variable. You might find the String format method and if expression useful.
Thanks for the tip, I'll try it out that way as well!
 
  • #12
365
2
So I have another question related to this, I hope it's alright that I post it in this thread instead of making a new one. What if I not only wanted to have the user specify how many times they would like to roll a die, but also prompt the user to specify the number of dice they want to roll? At this point I'm not sure if this would be some sort of nested for loop, or maybe it would be better to actually create some functions to carry this out? Here is my very rough (obviously wrong) first attempt with the nested for loop approach:

Python:
# Multiple Dice with Multiple Rolls

import random

NDice = input("Enter number of dice...")
D = int(NDice)

NRolls = input("Enter number of rolls...")
N = int(NRolls)  

for DiceNo in range(D):
    for RollNo in range(N):
        Die = str(random.randint(1,6))
        print("Your roll was a " + Die)
      
        if Die == "1" or Die == "3" or Die == "5":
            print("You rolled an odd number")
        elif Die == "2" or Die == "4" or Die == "6":
            print("You rolled an even number")
Code:
Enter number of dice...
Enter number of rolls...
Traceback (most recent call last):
  File "jdoodle.py", line 8, in <module>
    NRolls = input("Enter number of rolls...")
EOFError: EOF when reading a line
Command exited with non-zero status 1
 
  • #13
33,314
5,006
So I have another question related to this, I hope it's alright that I post it in this thread instead of making a new one. What if I not only wanted to have the user specify how many times they would like to roll a die, but also prompt the user to specify the number of dice they want to roll? At this point I'm not sure if this would be some sort of nested for loop, or maybe it would be better to actually create some functions to carry this out? Here is my very rough (obviously wrong) first attempt with the nested for loop approach:

Python:
# Multiple Dice with Multiple Rolls

import random

NDice = input("Enter number of dice...")
D = int(NDice)

NRolls = input("Enter number of rolls...")
N = int(NRolls) 

for DiceNo in range(D):
    for RollNo in range(N):
        Die = str(random.randint(1,6))
        print("Your roll was a " + Die)
     
        if Die == "1" or Die == "3" or Die == "5":
            print("You rolled an odd number")
        elif Die == "2" or Die == "4" or Die == "6":
            print("You rolled an even number")
Code:
Enter number of dice...
Enter number of rolls...
Traceback (most recent call last):
  File "jdoodle.py", line 8, in <module>
    NRolls = input("Enter number of rolls...")
EOFError: EOF when reading a line
Command exited with non-zero status 1
I ran your code, but didn't get the EOF error that you show.

I wouldn't advise writing a function to do this, at least until you can get your algorithm straight. You do need nested loops, but yours are in the wrong order. If the user wants to have five rolls of the dice, using two dice on each roll, you need an outer loop that tracks the roll number, and an inner loop that generates a number for each die. With my example numbers it would be
Python:
for RollNo in Range(N):
   for DiceNo in range(D):
      # generate a number for a die
Also, why are you converting your random number to a string? If Die is an integer value, you can use the modulus operator that @wle suggested in post #9, and you can simplify the if ... elif part.
Die % 2 will be 0 if Die is an even integer, and will be 1 if Die is an odd integer

For example:
Python:
EvenOdd = Die % 2
if EvenOdd:
    print("You rolled an odd number")
else
    print ("You rolled an even number")
EvenOdd can be only 0 or 1. If it's 0, that's considered false, and 1 (or any other value) is considered true.
 
  • #14
365
2
I'm using an online python editor (https://www.jdoodle.com/python3-programming-online), I don't know if maybe it's a little buggy and throws out weird errors? So I changed the order of the for loops, left my Die variable as an integer, and tried using the EvenOdd code you gave me and this is what I have now:

Python:
import random

NRolls = input("Enter number of rolls...")
N = int(NRolls)

NDice = input("Enter number of dice...")
D = int(NDice)

for RollNo in range(N):
    for DiceNo in range(D):
        Die = random.randint(1,6)
        print("Your roll was a " + str(Die))
       
        EvenOdd = Die % 2
        if EvenOdd:
            print("You rolled an odd number")
        else:
            print("You rolled an even number")
Code:
Enter number of rolls...Enter number of dice...
Traceback (most recent call last):
  File "jdoodle.py", line 7, in <module>
    D = int(NDice)
ValueError: invalid literal for int() with base 10: ''
Command exited with non-zero status 1
I don't understand what that error means.
 
  • #15
33,314
5,006
I don't either. I ran the exact code you posted, and it worked as I expected. Here's the output I got:
Code:
C:\Users\Mark\Documents\Python3.4.2>python jdawg.py
Enter number of rolls...5
Enter number of dice...2
Your roll was a 3
You rolled an odd number
Your roll was a 1
You rolled an odd number
Your roll was a 3
You rolled an odd number
Your roll was a 5
You rolled an odd number
Your roll was a 1
You rolled an odd number
Your roll was a 5
You rolled an odd number
Your roll was a 5
You rolled an odd number
Your roll was a 2
You rolled an even number
Your roll was a 4
You rolled an even number
Your roll was a 2
You rolled an even number
I'm running Python 3.4.2 from the command line.

Maybe you should consider downloading the interpreter, and bailing out of the online editor thingy. You can download the Python system from http://python.org

Their current version is 3.7.0.
 
  • Like
Likes jdawg
  • #16
365
2
I have Python downloaded on my personal laptop, but unfortunately I can't download it at work. Thanks for all your help, I feel like I've learned some good stuff! I'll give this code a try when I get home.
 
  • #17
wle
307
136
What if I not only wanted to have the user specify how many times they would like to roll a die, but also prompt the user to specify the number of dice they want to roll?
What's the difference? E.g., your code basically ends up doing the same thing if you say you want to roll ##N## dice once as it does if you say you want to roll one die ##N## times.
 
  • #18
33,314
5,006
What's the difference? E.g., your code basically ends up doing the same thing if you say you want to roll ##N## dice once as it does if you say you want to roll one die ##N## times.
But you could report what happened on each roll, which would be important if you were shooting craps. For example, if there are 5 rolls of two dice, the output could look something like this:
On roll 1, the dice showed 2 and 5, for a total of 7.
On roll 2, the dice showed 1 and 1, for a total of 2 "snake eyes".
On roll 3, the dice showed 6 and 6, for a total of 12 "box cars".
etc. for the remaining 2 rolls
 

Related Threads on Python Dice Rolling Game

  • Last Post
Replies
1
Views
5K
Replies
7
Views
6K
  • Last Post
Replies
5
Views
2K
  • Last Post
Replies
2
Views
826
  • Last Post
Replies
3
Views
1K
  • Last Post
Replies
1
Views
983
  • Last Post
Replies
2
Views
2K
Replies
3
Views
1K
Replies
2
Views
986
Replies
8
Views
563
Top