我是编程新手,我在循环中累积有困难
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
假设用户试图猜测的等式是1 + 2 + 3并且他们的第一次猜测是2,formSoFar是--2--但他们第二次猜测它应该显示第一个猜测,所以如果他们猜测1它应该是1-2--但是这个代码是打印 - 2--1-2-- 请帮忙:(
答案 0 :(得分:2)
在每个循环中,您将字符附加到formSoFar
。你要做的是让它从一些值开始并在你去的时候进行编辑:
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)
另请注意,您在()
声明中不需要if
。那是一个C / C ++ / Java的东西。