-1

I am learning python and trying make my code in function.

## set total sticks number
stick_left = 20
## Given hints, this for statement shows sticks
for _ in range(5): print('|  '*stick_left)
## this condition lasts until stick = 0
while stick_left>0:
    ## first player
    first_player=input('Player1: please pick sticks up to 3 ')
    if first_player>3 or first_player<0:
        print('Please pick between 1-3 stick(s)')
    else:
        stick_left-=first_player
        if stick_left<=0:
            print ('Player1 lost')
            break
        else:
            print('There is %d stick(s) left' %stick_left) ## print how many sticks left
            for _ in range(5): print('|  ' * stick_left)
    ## second player
    second_player = input('Player2: Please pick sticks up to 3 ')
    if second_player > 3 or second_player < 0:
        print('Please pick between 1-3 stick(s)')
    else:
        stick_left -= second_player
        if stick_left <= 0:
            print ('Player2 lost')
            break
        else:
            print('There is %d stick(s) left' % stick_left)
            for _ in range(5): print('|  ' * stick_left)

and this is my code includes function

player =0
def player():
    for i in 2:
        player%d %i= input('Player %d:  Please pick sticks up to 3' %i)
        if player >3 or player <0:
            print('Please pick between 1-3 stick(s)')

On line 4, I want to make it print player1 player2, but I just notice that I cannot assign operator like that. I tried player_%d %i but no luck. Can anybody give me advice please? Thanks!

jayko03
  • 2,329
  • 7
  • 28
  • 51

2 Answers2

4

You can't define variable names on the fly like this. Use a dictionary.

players = {}
def player():
    for i in range(2):
        players[i] = input("Player %d: Please pick sticks up to 3" % (i,))
        # etc
vaultah
  • 44,105
  • 12
  • 114
  • 143
chepner
  • 497,756
  • 71
  • 530
  • 681
-1

exec() function will work for you. Please refer below code.

player =0
def player():
    for i in range(1,3):
        exec("player%d = input('Player%d =  Please pick sticks up to 3 ')" %(i,i))
player()

Following is the o/p.

Player1 = Please pick sticks up to 3 1

Player2 = Please pick sticks up to 3 2

Community
  • 1
  • 1
PShiwotia
  • 15
  • 3
  • While this would work, please *please* do not recommend exec to a new programmer. There is a ridiculous amount of foot-shooting possible here. – Kirk Strauser Apr 15 '16 at 18:46
  • And this *won't* actually work in Python 3 (although it would have in Python 2). If you add `print(player1)` after the loop, it'll work in Py2 and give you a NameError in Py3. – DSM Apr 15 '16 at 18:53
  • 1
    @PShiw: as I said, try adding `print(player1)` after the loop. That will fail in Python 3.4 with `NameError: name 'player1' is not defined` even though it will succeed in Python 2.7, because of changes in how `exec` behaves. – DSM Apr 15 '16 at 19:00