I am trying to use a while loop instead of a for loop while rolling dice. I do not think elif is right, but I cannot figure out how to use the while loop within this. This is what I have so far:
import random
def rolldiewhileloop():
number = 10
one = 0
two = 0
three = 0
four = 0
five = 0
six = 0
while number > 0:
flip = int(random.random() * 6)
if(flip == 1):
one = one + 1
elif flip == 2:
two = two + 1
elif flip == 3:
three = three + 1
elif flip == 4:
four = four + 1
elif flip == 5:
five = five + 1
elif flip == 6:
six = six + 1
return [one, two, three, four, five, six]
In your current while loop you aren't changing the value of number, so this will be an infinite loop. Since you are starting at 10 and looping until number is less than or equal to zero, you should probably be decrementing by one on each iteration:
number = 10
while number > 0:
number -= 1
# the rest of the loop
Note that number -= 1 is equivalent to number = number - 1.
As a side note, instead of multiplying the result of random.random() it would be better to use random.randint(1, 6). Also, since you are returning an array already it would be more Pythonic to create a list of the results and modify that, rather than creating a separate variable for each possibility. For example:
def rolldiewhileloop():
results = [0] * 6
number = 10
while number > 0:
number -= 1
flip = random.randint(1, 6)
results[flip-1] += 1
return results
You need to decrement number on each pass of the while loop. Put number -= 1 as the last line in the while loop.
Related
import random
my_stats = []
stat = 0
while len(my_stats) < 3:
for i in range(1,4): # generates a num (d6) but no 1's
number = (random.randint(1, 6))
while number == 1:
number = (random.randint(1, 6))
else:
stat += number # sums the 3 rolls into stat
my_stats.append(stat)
print(my_stats)
I am not sure how to get 3 distinct entries in my list, just keeps adding up.
Your code currently rolls a die 3 times, adding the results if the roll is not 1, otherwise rerolling the die pointlessly (as the value is never used). The summed value is then appended to a list and you repeat the process, but without resetting the sum to 0 first. So it contains at least 2 errors (as ignoring the 1 and not using the reroll doesn't appear to be what you want)
I think this is what you were after:
import random
my_stats = []
stat = 0
while len(my_stats) < 3:
# you'd want to restart the count every time
stat = 0
# you'll need to keep track of the number of good rolls, can roll any number of 1's
good_rolls = 0
while good_rolls < 3:
number = (random.randint(1, 6))
if number != 1:
stat += number # sums the 3 rolls into stat
good_rolls += 1
my_stats.append(stat)
print(my_stats)
You never reset stat.
Try moving its initialization into the loop, e.g.
while len(my_stats) < 3:
stat = 0
for i in range(1,4):
# ...
This is my code:
def helper_number_of_ones(n:int, counter:int)->int:
if n == 1:
counter += 1
return counter
else:
if n % 10 == 1:
counter += 1
if n // 10 == 1:
counter += 1
return helper_number_of_ones(n-1,counter)
def number_of_ones(n: int) -> int:
count = 0
return helper_number_of_ones(n,count)
My code basically checks for the number of digit one occurrences, throughout all numbers between n and 1, for example n=13 will output 6 for 6 ones occurrences, the only problem it doesn’t work
properly for numbers bigger than 100? Thanks in advance
Your code takes into consideration two possibilities:
The ones digit is 1 (if n % 10 == 1)
The tens digit is 1 (if n // 10 == 1)
This is enough for numbers up to 99, but fails for higher numbers.
I would suggest to break your function into two separate functions: one that counts the number of occurences of 1 in a single number, and another that does that for a range of numbers (using the first one of course).
It is because of how you calculate counter
...
if n % 10 == 1:
counter += 1
if n // 10 == 1:
counter += 1
...
For example, if n = 100, it will fail both ifs. You can make a function that calculates the number of 1 in a number recursively.
def num_of_one(number):
if number == 0:
return 0
else:
return ((number % 10) == 1) + num_of_one(number // 10)
Then make another function to calculate it over the range.
def range_num_of_one(max_num):
if max_num == 1:
return 1
else:
return num_of_one(max_num) + range_num_of_one(max_num - 1)
I'm currently beginning to learn Python specifically the while and for loops.
I expected the below code to go into an infinite loop, but it does not. Can anyone explain?
N = int(input("Enter N: "))
number = 1
count = 0
while count < N:
x = 0
for i in range(1, number+1):
if number % i == 0:
x = x + 1
if x == 2:
print(i)
count = count + 1
number = number + 1
For this code to not infinitely loop, count needs to be >= N.
For count to increase, x needs to be equal to 2.
For x to be equal to 2 the inner for loop needs to run twice:
for i in range(1, number+1):
if number % i == 0:
x = x + 1
For the inner for loop to run twice number must not have factors besides 1 and the number itself. This leaves only prime numbers.
The inner loop will always set x == 2 when number is a prime number. As there are an infinite amount of prime numbers, count >= N will eventually be satisfied.
Try to change N to number:
while count < N:
while count < number:
Ok let's dissect your code.
N = int(input("Enter N: "))
number = 1
count = 0
Here you are taking user input and setting N to some number,
for the sake of brevity let's say 4. It gets casted as an int so it's now
an integer. You also initialize a count to 0 for looping and a number variable holding value 1.
while count < N:
x = 0
for i in range(1, number+1):
if number % i == 0:
x = x + 1
if x == 2:
print(i)
count = count + 1
number = number + 1
Here you say while count is less than N keep doing the chunk of code indented.
So in our N input case (4) we loop through until count is equal to 4 which breaks the logic of the while loop. Your first iteration there's an x = 0 this means everytime you start again from the top x becomes 0. Next you enter a for loop going from 1 up to but not including your number (1) + 1 more to make 2. you then check if the number is divisible by whatever i equals in the for loop and whenever that happens you add 1 to x. After iteration happens you then check if x is 2, which is true and so you enter the if block after the for loop. Everytime you hit that second if block you update count by adding one to it. now keep in mind it'll keep updating so long as that if x == 2 is met and it will be met throughout each iteration so eventually your while loop will break because of that. Hence why it doesn't go forever.
This question already has answers here:
Python dice rolling simulation
(4 answers)
Closed 9 years ago.
I have a homework problem that states use the random.choice function to simulate the
roll of the die. . It will still simulate rolling a six-sided die 1000 times. Do i have to type out the list like 0, 1000? Or is there an easier way of doing it.
import random
def rolldie3():
#6 variables set to 0 as the counter
one = 0
two = 0
three = 0
four = 0
five = 0
six = 0
#use for loop for 1000 times to run
for i in range(1000):
scores = range(0,1000)
#get a random number out of the list
roll = random.choice(scores)
if roll == 1:
one = one + 1
elif roll == 2:
two = two + 1
elif roll == 3:
three = three + 1
elif roll == 4:
four = four + 1
elif roll == 5:
five = five + 1
elif roll == 6:
six = six + 1
#return the variables as a list
return [one,two,three,four,five,six]
I think you want something like this:
roll = random.choice([1,2,3,4,5,6])
As is, you're choosing a random dice roll, but only doing anything if it's 1 through 6.
Check out the random.choice description: http://docs.python.org/2/library/random.html#random.choice
random.choice(seq)
Return a random element from the non-empty sequence seq. If seq is empty, raises IndexError.
So you need to call this function by passing it a sequence to pick from, which you're trying to do with your scores variable. But that goes from 0 to 999, when you want it to go from 1 to 6. So define your range better:
scores = range(1,7)
for i in range(1000):
#get a random number out of the list
roll = random.choice(scores)
...
range(x,y) counts from x (inclusive) to y (exclusive), which is why 7 gives what you want.
I'm having trouble with a code where I need to roll a six-sided die 1000 times and then return a list of how many times each number on the die was rolled.
The code runs just fine and I can get a list at the end, but my list keeps having 0 in place of four so it appears that my function is not keeping tabs on the number 4 being rolled or it's not being rolled at all.
I'm kind of stumped and I thought maybe someone here could help. Any and all help is appreciated.
Here's my code.
def rollDie(number):
one = 0
two = 0
three = 0
four = 0
five = 0
six = 0
for i in range(0, number):
roll=int(random.randint(1,6))
if roll == 1:
one = one+1
elif roll == 2:
two = two+1
elif roll == 3:
three = three+1
elif roll == 4:
four == four+1
elif roll == 5:
five = five+1
elif roll == 6:
six = six+1
return [one,two,three,four,five,six]
You have a small typo; you are testing for equality, not assigning:
four == four+1
should be:
four = four+1
However, you already have a number between 1 and 6, why not make that into an index into the results list? That way you don't have to use so many if statements. Keep your data out of your variable names:
def rollDie(number):
counts = [0] * 6
for i in range(number):
roll = random.randint(1,6)
counts[roll - 1] += 1
return counts
I can't improve on Martijn Pieters's answer. :-) But this problem can be more conveniently solved using a list.
import random
def rollDie(number):
# create a list with 7 values; we will only use the top six
rolls = [0, 0, 0, 0, 0, 0, 0]
for i in range(0, number):
roll=int(random.randint(1,6))
rolls[roll] += 1
return rolls
if __name__ == "__main__":
result = rollDie(1000)
print(result[1:]) # print only the indices from 1 to 6
And, this is a little bit tricky, but here is a better way to create a list of 7 entries all set to zero:
rolls = [0] * 7
Why count the zeros yourself? It's easier to just make Python do the work for you. :-)
EDIT: The list is length 7 because we want to use indices 1 through 6. There is also a position 0 in the list, but we don't use it.
Another way to do it is to map the dice rolls onto indices. It's a pretty simple mapping: just subtract 1. So, a die roll of 1 would go into index 0 of the list, a die roll of 2 would go into index 1, and so on. Now we will use every position in the list.
Here's that version:
import random
def rollDie(number):
rolls = [0] * 6
for i in range(0, number):
roll=int(random.randint(1,6))
rolls[roll - 1] += 1
return rolls
if __name__ == "__main__":
result = rollDie(1000)
print(result)
You should do random.randint(1, 7), otherwise you will never get a 6.
...
roll = random.randint(1, 7)
import random
def dice():
print random.randint(1,6)
dice()