How to Modify Python Dice Rolling Game to Accept User Input for Number of Rolls?

In summary: If NRolls is not a number, then the user has not input a number, and the program should terminate. Next, you create a variable called "rolls" that will hold the number of rolls the user wants to make. Next, you create a for loop that will run as long as the user hasn't hit enter. The for loop will keep track of the number of rolls the user has made, and it will also keep track of the number of times the user has hit enter. Next, you use the rolls variable to control the flow of your code. You can see that you are checking to see if rolls is not a number,
  • #1
jdawg
367
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 randomrepeat = Truewhile 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

  • upload_2018-10-15_13-6-29.png
    upload_2018-10-15_13-6-29.png
    6.6 KB · Views: 8,017
Technology news on Phys.org
  • #2
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
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

  • upload_2018-10-15_18-53-37.png
    upload_2018-10-15_18-53-37.png
    13.3 KB · Views: 2,511
  • #4
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
Mark44 said:
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
jdawg said:
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
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
jdawg said:
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.

jdawg said:
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
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
Mark44 said:
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
wle said:
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
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
jdawg said:
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
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
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
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
jdawg said:
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
wle said:
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
 

1. What is the purpose of a Python Dice Rolling Game?

The purpose of a Python Dice Rolling Game is to simulate the experience of rolling dice in a traditional tabletop game. It allows users to play a game that involves chance and decision making, and can be used for entertainment or educational purposes.

2. How do I play a Python Dice Rolling Game?

To play a Python Dice Rolling Game, you simply need to run the program and follow the instructions. Typically, you will be asked to roll a certain number of dice and make a decision based on the outcome of the roll. The rules and gameplay can vary depending on the specific game being played.

3. Can I customize the Python Dice Rolling Game?

Yes, many Python Dice Rolling Games allow for customization. This can include changing the number of dice, the range of numbers on the dice, and the rules of the game. Some games may also allow for custom graphics or sound effects.

4. Is the outcome of a Python Dice Rolling Game truly random?

Yes, if the game is programmed correctly, the outcome of a Python Dice Rolling Game should be truly random. This is due to the use of built-in random number generators in the code. However, it is important to note that some games may have biases or patterns that are intentionally programmed in.

5. Can a Python Dice Rolling Game be used for educational purposes?

Yes, a Python Dice Rolling Game can be a useful tool for teaching concepts such as probability and decision making. It can also be used to demonstrate the use of random number generators in programming. However, the specific educational value will depend on the design and purpose of the game.

Similar threads

  • Programming and Computer Science
Replies
1
Views
3K
  • Programming and Computer Science
Replies
1
Views
3K
  • Programming and Computer Science
Replies
1
Views
4K
  • Programming and Computer Science
Replies
4
Views
392
  • Programming and Computer Science
Replies
18
Views
2K
  • Programming and Computer Science
Replies
3
Views
4K
  • Programming and Computer Science
Replies
7
Views
2K
  • Programming and Computer Science
Replies
1
Views
2K
  • Set Theory, Logic, Probability, Statistics
2
Replies
41
Views
3K
  • Set Theory, Logic, Probability, Statistics
Replies
6
Views
1K
Back
Top