簡體   English   中英

變量不會在while循環中更新

[英]Variable does not update in while loop

為什么current_score在while循環中不更新? 首次發布時,無法在線找到答案。 我想這是一個范圍界定問題

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()

嘗試這個:

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)語法時,所有的魔術都會發生。 然后,您將獲得一個新字符串,其中包含格式化輸出。

在打印出來之前,您必須在循環中設置新值之后,用新值重新初始化當前分數。

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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM