vendredi 4 mai 2018

Python: player input using for loops?

I am trying to make a guessing game in python 3 using jupyter notebook whereby two people take turns to guess a number between 1 and 10. What I don't want is that the answer is immediately given like this:

from random import randint
rand_num = randint(1,10)

players = ['player_1', 'player_2']

for player in players:
    player_input = int(input('What is your guess {}? '.format(player)))
    if player_input == rand_num:
        print('You won!')
    else:
        print('You lost!')

print('The random number was: {}'.format(rand_num))

Instead I want everyone to guess and then the answer is given so that everyone has a fair chance at guessing the number. I tried the following here but this doesn't seem to work because I think the player_input doesn't account for every single player. So when one player got the number right, python prints that every player got the number right.

from random import randint
rand_num = randint(1,10)

players = ['player_1', 'player_2']

for player in players:
    player_input = int(input('What is your guess {}? '.format(player)))

for player in players:
    if player_input == rand_num:
        print('You won {}!'.format(player))
    else:
        print('You lost {}!'.format(player))

print('The random number was: {}'.format(rand_num))

How can I make this work using lists and for loops?




Aucun commentaire:

Enregistrer un commentaire