如何关闭我的' while'循环所以程序没有无限循环?
def letter_guess(guess):
if guess in word:
return True
else:
return False
def correct_letter(guess):
guess = guess
if letter_guess(guess) == True:
print ('Correct: ' + guess)
else:
wrong_letter(guess)
def wrong_letter(guess):
guess = guess
if letter_guess(guess) == False:
print('Wrong: ' + guess)
else:
correct_letter(guess)
#Program starts here
word = 'samsung'
guess = raw_input('Guess a letter: ')
while guess !='':
letter_guess(guess)
correct_letter(guess)
wrong_letter(guess)
程序应该接收原始输入并确定输入是否在对象中。'然后它应该继续提出相同的问题,而不是无限循环。
答案 0 :(得分:1)
您需要在循环内移动输入。当您了解它时,您可能还希望简化逻辑的其余部分:
while True:
guess = raw_input('Guess a letter or press Enter to stop: ')
if guess == '':
break
if guess in word:
print('Correct')
else:
print('Incorrect')
答案 1 :(得分:0)
在无限循环内询问raw_input,如果不满足条件则中断
while True:
# your algorithm
# ...
if not satisfied:
break
答案 2 :(得分:0)
为什么不在全局设置一个由正确猜测修改的标志变量?这是你的脚本的头部,声明flag = false
,然后检查标志作为你的while循环中的条件,如
while guess !='' && flag == false:
在correct_letter()
:
def correct_letter(guess):
guess = guess
if letter_guess(guess) == True:
print ('Correct: ' + guess)
flag = true
else:
wrong_letter(guess)