循环

时间:2017-03-23 19:39:14

标签: python while-loop

为什么current_score不会在while循环中更新?第一次发帖,在网上找不到答案。我想这是一个范围问题halp

def main():
    player_1 = input("Player one: ")
    player_1_score = 0
    player_2 = input("Player two: ")
    player_2_score = 0
    num_sets = int(input("Points for a win: "))
    current_score = "%s (%i : %i) %s" % (player_1, player_1_score, player_2_score, player_2)

    while player_1_score < num_sets > player_2_score:
        round = int(input("Who won this round? (type 1 for player one; type 2 for player two"))
        if round == 1:
            player_1_score += 1
        else:
            player_2_score += 1

    print(current_score)
pass

if __name__ == '__main__':
    main()

2 个答案:

答案 0 :(得分:1)

试试这个:

current_score = "%s (%i : %i) %s"

while something:
    # do the update
    print(current_score % (player_1, player_1_score, player_2_score, player_2))

这里current_score只是一个包含格式说明符的字符串。当您将format_string % (data)语法应用于它时,所有的魔法都会发生。然后你得到一个新的字符串,它将保存格式化的输出。

答案 1 :(得分:0)

在打印输出之前在循环中设置新值后,您必须使用新值重新初始化当前得分:

def main():
player_1 = input("Player one: ")
player_1_score = 0
player_2 = input("Player two: ")
player_2_score = 0
num_sets = int(input("Points for a win: "))
current_score = "%s (%i : %i) %s" % (player_1, player_1_score, player_2_score, player_2)

while player_1_score < num_sets > player_2_score:
    round = int(input("Who won this round? (type 1 for player one; type 2 for player two"))
    if round == 1:
        player_1_score += 1
    else:
        player_2_score += 1

    current_score = "%s (%i : %i) %s" % (player_1, player_1_score, player_2_score, player_2)
    print(current_score)
pass

if __name__ == '__main__':
    main()