Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
random library
#1
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
Reply
#2
interesting thread
Reply
#3
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!!')
Reply
#4
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!!')
Reply


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

Forum Jump:

User Panel Messages

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