Lets say I want to find all the numbers a fair die can roll sample_size
of times.
I first create a empty list
die_list= []
def die_number(sample_size):
for i in range(sample_size) #i want to iterate what ever the sample_size is
die_list.append(random.randint(0,7))
is this thought process correct?
CodePudding user response:
Based on the sample code provided,you can try this out using list comprehension
import random
def die_number(sample_size):
return [random.randint(0, 100) for x in range(sample_size)]
die_number(5)
[29, 0, 2, 100, 51]
CodePudding user response:
The thought process is basically correct, and your code can be made to work once the syntax and indentation errors are ironed out:
import random
die_list= []
def die_number(sample_size):
for i in range(sample_size): # I want to iterate whatever the sample_size is
die_list.append(random.randint(1,6))
die_number(10)
print(die_list)
However, the code still feels a little weird. That's because it is more idiomatic (“pythonic”) to have the die_number
function create the list, populate it and ultimately return it to the caller. Like this:
import random
def die_number(sample_size):
die_list = []
for i in range(sample_size): # I want to iterate whatever the sample_size is
die_list.append(random.randint(1,6))
return die_list
dies = die_number(10)
print(dies)