How to accumulate within a loop python

946 views Asked by At

I am new to programming and I am having difficulty accumulating within a loop

    wrong_guesses=0
    formSoFar=''
    game_over=False
    while (game_over==False and wrong_guesses<max_guesses):
        guess1= raw_input("Please enter an operation symbol or digit: ")
        if (guess1 in formula):
            print "Your guess is correct!"
            for i in range (len(formula)):
                if (randomFormula[i] == guess1):
                    formSoFar += formula[i]
                else:
                    formSoFar+= "-"
            print "The formula you have guessed so far is: ",formSoFar

Supposed the equation the user is trying to guess is 1+2+3 and their first guess is 2 the formSoFar is --2-- but the second time they guess it should show the first guess as well so if they guess 1 it should be 1-2-- but this code is printing--2--1-2-- please help :(

1

There are 1 answers

0
Barry On BEST ANSWER

In each loop, you are appending characters to formSoFar. What you want to do instead is have it start with some value and edit it as you go:

formSoFar = ['-'] * len(formula)

while not game_over and wrong_guesses < max_guesses:
    guess = raw_input(...)
    if guess in formula:
        for i, c in enumerate(formula):
            if c == guess:
                formSoFar[i] = c

        print 'The formula you have guessed so far is:', ''.join(formSoFar)

Also note that you don't need ()s in an if statement. That's a C/C++/Java thing.