Can I please get help with this python code?

JRigle

Distinguished
Sep 15, 2013
37
0
18,540
I'm learning python on zybooks and I have to change dice rolling code to repeatedly ask for the user to enter the number of rolls until the user enters a number less than 1. Can someone look at my code and tell me what I'm doing wrong. I tried to figure it out myself and not ask for help but just can't seem to get it.

import random

num_sixes = 0
num_sevens = 0
num_rolls = int(input('Enter number of rolls:\n'))
while num_rolls >= 1:
num_rolls = num_rolls -1

for i in range(num_rolls):
die1 = random.randint(1,6)
die2 = random.randint(1,6)
roll_total = die1 + die2

#Count number of sixes and sevens
if roll_total == 6:
num_sixes = num_sixes + 1
if roll_total == 7:
num_sevens = num_sevens + 1
print('Roll %d is %d (%d + %d)' % (i, roll_total, die1, die2))

print('\nDice roll statistics:')
print('6s:', num_sixes)
print('7s:', num_sevens)

 
Solution
Rather than introducing further variables, the most elegant way of doing this in Python is something like:

Python:
while True:
        num_rolls = int(input('Enter number of rolls:\n'))
        if num_rolls < 1:
                break
        ... code to print results here ...
You should really use boolean true/false statements in the while loop (while TRUE do stuff). Inside the while loop ask for user input then use an if-else statement to test if number rolls >=1, (then do more stuff). the else statement should set whatever to false and it will escape the loop.
 

McHenryB

Admirable
Rather than introducing further variables, the most elegant way of doing this in Python is something like:

Python:
while True:
        num_rolls = int(input('Enter number of rolls:\n'))
        if num_rolls < 1:
                break
        ... code to print results here ...
 
Solution