So I have been putting together a small text based game and I was wondering if this was the best way to execute a die roller:
import random
def roll_die(die_type, roll_times, print_op):
total_roll = 0
for roll_times:
roll_result = random.randint(1, die_type)
roll_result += total_roll
if print_op == True:
print(roll_result)
print(total_roll)
I haven't done to much in python so if this is horrible beyond comprehension I understand.
This is a good time to get to grips with splitting things into small, self-contained functions and passing arguments around. As I see it, you have two tasks here:
So this should be two functions:
import random
def roll_die(die_type, print_op=False):
roll_result = random.randint(1, die_type)
if print_op:
print("Roll: {0}.".format(roll_result))
return roll_result
def roll_dice(die_type, roll_times, print_op=False):
total_roll = 0
for _ in range(roll_times):
total_roll += roll_die(die_type, print_op)
if print_op:
print("Running total: {0}.".format(total_roll))
return total_roll
In use:
>>> print("Output: {0}.".format(roll_dice(6, 3, True)))
Roll: 5.
Running total: 5.
Roll: 1.
Running total: 6.
Roll: 5.
Running total: 11.
Output: 11.
Here's what I would do if I were you, adapting your code to something that works and seems to do what you want:
import random
def roll_die(die_type, roll_times, print_op=False):
total_roll = 0 # you need to use an iterable to iterate over
for _ in range(roll_times): # range is made for this
roll_result = random.randint(1, die_type)
total_roll += roll_result # you mixed these up
if print_op:
print(roll_result)
if print_op:
print(total_roll)
return total_roll # don't forget to return your result
And demo of usage:
>>> print('returning:', roll_die(6, 3, True))
1
6
5
12
('returning:', 12)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.