Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
random library
This is my code:

[python=import random

Benvenuto al programma: 'Carta Forbice Sasso'

Creato da: Federico Oblatore

scelta = input('Cosa scegli? ')

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


if scelta == 'carta' or scelta == 'Carta':
if (random.choice(insieme)) == 'forbice':
print('Hai perso :(')
elif (random.choice(insieme)) == 'carta':
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':
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':
elif x == 'sasso':
    print('Hai vinto!!')

Possibly Related Threads…
Thread Author Replies Views Last Post
  PyInstaller, how to create library folder instead of file ? harun2525 2 2,731 May-06-2017, 11:29 AM
Last Post: harun2525

Forum Jump:

User Panel Messages

Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020