I am just learning python (first language ever) and am implementing what I find in ways that I find fun. I built a pseudo slot machine odds calculator. However, it stops at one Grand prize win. Is there a way to make it run over and over to give an average number of attempts for n amount of games to get the grand prize?
Here’s my code
#!/usr/bin/env python
import random
a = 1
while a >0 :
l1 = random.randrange(36)
l2 = random.randrange(36)
l3 = random.randrange(36)
print l1, l2, l3
if l1 == l2 == l3 == 7:
print 'grand prize winner!!!'
break
elif l1 == l2 == l3:
print 'you won! congratulations'
print 'it took', a, 'attempts to win'
else:
a += 1
print 'sorry... try again'
print 'attempt', a
Also, is there a way to tell me how many normal wins there were during the course of winning that grand prize
The
breakstatement in the grand prizeifblock exits the outerwhileloop. If you want it to keep going, remove thebreak. Also, as a style point,while True:orwhile 1:is a bit clearer of a way to create an infinite loop. As far as the second part of your question, you have theacounter, but you may want to capture more data, like so:I also snuck a control
till_jackpot_countin at the top that will make the loop end after that number of jackpots. The function also returns the test results if you want to analyze them further outside of the function itself, but the result just gets dropped here because it is not assigned to anything.For your own study, this code uses lists (
[]), dicts ({}), tuples (()), old style string formatting ('%d' % var), new style string formatting ('{} {} {}'.format(*iterable)), list comprehensions ([a for a in b]), slicing (list[:]), and a few builtins (sum,len) in addition to therandomlibrary andwhileloop you’re already familiar with. I also swapped out yourrandom.randrange()for a somewhat simpler, probably more efficient,random.sample()of a pre-builtxrange().