ArmyKirouac
ArmyKirouac

Reputation: 11

How do I close out my 'while' loop so the program doesn't loop infinitely?

How do I close out my 'while' loop so the program doesn't loop infinitely?

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)

The program is supposed to receive raw input and determine whether or not the input is in the object 'word.' It should then continue to ask the same question instead of loop infinitely.

Upvotes: 0

Views: 88

Answers (3)

T.Woody
T.Woody

Reputation: 1218

Why not set a flag variable globally that is modified by correct guess? That is at the head of your script, declare flag = false, then check flag as the condition in your while loop such as

while guess !='' && flag == false:

And in correct_letter():

def correct_letter(guess):
    guess = guess
    if letter_guess(guess) == True:
        print ('Correct: ' + guess)
        flag = true
    else:
        wrong_letter(guess)

Upvotes: 0

NPE
NPE

Reputation: 500167

You need to move the input inside the loop. While you're at it, you might want to also simplify the rest of the logic:

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

Upvotes: 1

Ask raw_input inside infinite loop and break if your conditions are not satisfied

while True:
    # your algorithm
    # ...
    if not satisfied:
        break

Upvotes: 0

Related Questions