Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

Python Dictionaries In range loop

I have this code:

from random import randint
#1o Skelos:
numplayers=eval(input('Number of players (between 2 and 6): '))
while numplayers>6 or numplayers<2 or numplayers!=int(numplayers):
    print('I expected between 2 and 6 players')
    print('I am setting the number of players to 3')
    numplayers=3
numcoins=eval(input('Number of coins per player (between 5 and 100): '))
while numcoins>100 or numcoins<5 or numcoins!=int(numcoins):
    print('I expected between 5 and 100 coins per player')
    print('I am setting the number of coins to 10')
    numcoins=10
print('Game begins with',numplayers,'players.')
print('Each players has',numcoins,'coins.')
banker=randint(1,numplayers)
print('Player',banker,'is randomly chosen as banker') 
print()


#2o Skelos:
bet={}
print('Current balance: ')
for i in range(1,numplayers+1):
    print('Player',i,'has',numcoins,'coins')
print()
for x in range(1,numplayers+1):
    if x==1:
        print('Player',banker,': You are the banker!',end=' ')
        bank_amount=int(input('Please enter a valid bank amount: '))
        while bank_amount<1 or bank_amount>numcoins:
            print('Player',banker,': You are the banker!',end=' ')
            bank_amount=int(input('Please enter a valid bank amount: '))
    if x!=banker:
        print('Player',x,':',end=' ')
        player_bet=int(input('Please enter a valid bet: '))
        while player_bet<1 or player_bet>bank_amount:
            print('Player',x,':',end=' ')
            player_bet=int(input('Please enter a valid bet: '))
        bet['bet_of_player {0} '.format(x)] = player_bet
        while sum(bet.values())>bank_amount:
            bet.popitem()
            print('Player',x,':',end=' ')
            player_bet=int(input('Please enter a valid bet: '))
            bet['bet_of_player {0} '.format(x)] = player_bet
            break
        if sum(bet.values())>=bank_amount:
            break

In the #2o Skelos, I am creating a dictionary called bet. I want for every player to print the value(his bet) from the above dictionary for example, (bet_of_player 2 is 4).

I have tried this but it won't work:

for k in range(1,numplayers+1):
    print('bet of player',k,'is',bet['bet_of_player {k} '])

I keep getting "KeyError": Any suggestions?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...