Python Forum

Full Version: random library
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
This is my code:

[python=import random

print('''
Benvenuto al programma: 'Carta Forbice Sasso'

Creato da: Federico Oblatore
''')

scelta = input('Cosa scegli? ')

insieme = ['carta', 'forbice', 'sasso']

str(scelta)

if scelta == 'carta' or scelta == 'Carta':
print(random.choice(insieme))
if (random.choice(insieme)) == 'forbice':
print('Hai perso :(')
elif (random.choice(insieme)) == 'carta':
print('Pareggio')
elif (random.choice(insieme)) == 'sasso':
print('Hai vinto!!')][/python]


but in the idle it write the random element but the 'elifs' dont work
interesting thread
Please fix the opening tag. Should just be python in brackets. Click the python icon button to insert them automatically.

Each time you call random.choice(insieme), you're making a new choice. Often rather than rechoosing, you want to make one choice, remember it, then do your comparisons against that choice. Otherwise you might pick the second one on the first check (so it doesn't print), then on the second check it picks the first choice. You might never match any of them. By remembering the choice, you know you should match one of them.

Something like:
mychoice = random.choice(insieme)
if (mychoice) == 'forbice':
    print('Hai perso :(')
elif (mychoice) == 'carta':
    print('Pareggio')
elif (mychoice) == 'sasso':
    print('Hai vinto!!')
Well, by calling random.Choice() on every line, the interpreter is selecting a different element each time. In essence, you have approximately a 3.5% chance of the code ever working. Instead, store the result of random.Choice() in a variable and then check that variable in your if...elif statement.

x = random.choice(insieme)
if x == 'forbice':
    print('Hai perso :(')
elif x == 'carta':
    print('Pareggio')
elif x == 'sasso':
    print('Hai vinto!!')