[Tutor] Running a loop
Peter Otten
__peter__ at web.de
Sun Oct 16 11:11:26 CEST 2011
Jason Barry wrote:
> I am using Windows 7 and python 3.1. This is a block from a slot machine
> code. It takes the random generated words and indicates if it wins or
> loses. I can't figure out why it wants to print the last print statement
> 'Loser' no matter if the elif statements are true.
>
> import random
>
> wheel1=['ZOMBIE', 'WITCH', 'CAT', 'GHOST',
> 'CANDY','PUMPKIN','PUMPKIN','CANDY', 'GHOST','CANDY']
>
> wheel2=['ZOMBIE', 'WITCH', 'CAT', 'GHOST',
> 'CANDY','PUMPKIN','PUMPKIN','CANDY', 'GHOST','CANDY']
>
> wheel3=['ZOMBIE', 'WITCH', 'CAT', 'GHOST',
> 'CANDY','PUMPKIN','PUMPKIN','CANDY', 'GHOST','CANDY']
The wheels are all the same and you don't plan to modify them; therefore you
can use a single wheel variable for all wheels in the slot machine
> wheel1index=''
No need to initialise the variable with a dummy value when you proceed to
see the real value immediately afterwards.
> wheel1index=wheel1[random.randint(0, len(wheel1) - 1)]
> wheel2index=wheel2[random.randint(0, len(wheel2) - 1)]
> wheel3index=wheel3[random.randint(0, len(wheel3) - 1)]
Have a look at random.choice() which has the same effect. Also, consider
putting the results into a list as in
chosen = [random.choice(wheel) for dummy in range(3)]
> winning=0
Unused variable.
> def checkwin (wheel1index, wheel2index, wheel3index):
You can shorten this function considerably with the help of sets and dicts.
A complete example script:
import random
from collections import Counter
wheel = ['zombie', 'witch', 'cat', 'ghost',
'candy','pumpkin','pumpkin','candy', 'ghost','candy']
_plurals = {
"witch": "witches",
"candy": "candies"}
def plural(word):
return _plurals.get(word, word + "s")
def checkwin (chosen):
chosen_dict = Counter(chosen)
if len(chosen_dict) == 1:
print("wins {}.".format(plural(chosen[0])))
elif chosen_dict == {"witch": 2, "cat": 1}:
print("wins witches and cat")
elif chosen_dict == {"pumpkin": 2, "ghost": 1}:
print("wins pumpkins and ghost")
elif chosen_dict.keys() == {"candy", "pumpkin", "ghost"}:
print("wins pumpkin, ghost, and candy.")
else:
print("Loser")
for i in range(1000):
chosen = [random.choice(wheel) for wheel_index in range(3)]
print(" ".join(chosen).ljust(25), end=" --> ")
checkwin(chosen)
More information about the Tutor
mailing list