我正在学习python并尝试使用我的代码。
## 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)
这是我的代码包含函数
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)')
在第4行,我想让它打印播放器1 player2,但我只是注意到我不能像这样分配运算符。
我试过player_%d %i
但没有运气。请问有人给我建议吗?
谢谢!
答案 0 :(得分:4)
您无法像这样定义变量名称。使用字典。
players = {}
def player():
for i in range(2):
players[i] = input("Player %d: Please pick sticks up to 3" % (i,))
# etc
答案 1 :(得分:-1)
exec()函数适合你。请参考以下代码。
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()
以下是o / p。
球员1 =请选择最多3 1的球棒
Player2 =请选择最多3 2的支撑