0

Why doesn't current_score update in the while loop? First time posting, couldn't find the answer online. I guess it's a scoping issue 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()
1
  • Where do you instruct it to update. Note that string formatting like ...%... is evaluated once... Commented Mar 23, 2017 at 19:40

2 Answers 2

1

Try this:

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

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

Here current_score is just a string containing the format specifiers. All the magic happens when you apply that format_string % (data) syntax to it. Then you get a new string that'll hold the formatted output.

Sign up to request clarification or add additional context in comments.

2 Comments

That's pretty smart. So does that mean that using '%' just stores current values in a string variable? And when i reuse that variable it just gives me the string not the "%s (%i : %i) %s" % (player_1, player_1_score, player_2_score, player_2)
@qutija, pretty much: the %s and %i themselves are merely format specifiers (i.e. just characters).
0

You have to reinitialize current score with the new values after the new values are set in the loop before printing out:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.