[Tutor] Running a loop

Steven D'Aprano steve at pearwood.info
Sun Oct 16 06:01:20 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.

Alan has already explained that you are comparing UPPERCASE strings to 
lowercase strings, and they are not equal.

A few other comments below:


> 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']

Rather than duplicating values each time, it is better to do this:

images = tuple('''ZOMBIE WITCH CAT GHOST CANDY PUMPKIN PUMPKIN
                   CANDY GHOST CANDY'''.split())

wheel1 = list(images)
wheel2 = list(images)
wheel3 = list(images)

(Note: I call list(images) instead of just images to ensure that each of 
the wheels has its own independent list of images, rather than all 
sharing the same one.)

Checking for winning sets also can be simplified a lot:


def checkwin (wheel1index, wheel2index, wheel3index):
     combo = [wheel1index, wheel2index, wheel3index]
     if combo.count('ZOMBIE') == 3:
         print('wins zombies')
     elif combo.count('WITCH') == 3:
         print('wins witchs')
     elif combo.count('CAT') == 3:
         print('wins cats')
     elif combo.count('PUMPKIN') == 3:
         print('wins pumpkins')
     elif combo.count('GHOST') == 3:
         print('wins ghosts')
     elif combo.count('CANDY') == 3:
         print('wins candies')
     elif combo.count('WITCH') == 2 and combo.count('CAT') == 1:
         print('wins witches and cat')
     elif combo.count('PUMPKIN') == 2 and combo.count('GHOST') == 1:
         print('wins pumpkins and ghost')
     # check for single combo winner
     elif set(combo) = set(['CANDY', 'PUMPKIN', 'GHOST']):
         print('wins pumpkin, ghost and candy')
     else:
         print('loses')





-- 
Steven


More information about the Tutor mailing list