Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

When to use a while loop in a function?

Nothing wrong with the code here - I just have a general question and using the program as an example.

I'm a little unsure as to when a while loop is used in a function. I understand what a while loop is which is that it is used to have some code iterate continuously as long as the condition in it is true. In this particular program, there are times when there is a while loop in a function and times when there is not one. When there is a while loop, it doesn't seem like it's really needed because it appears the code would run just fine without it (in reality it doesn't but I'm not sure why).

import os
import random
import sys

words = [
    'apple',
    'banana',
    'orange',
    'strawberry',
    'lime',
    'grapefruit',
    'lemon',
    'kumquat',
    'blueberry',
    'melon'
]

def clear():
    if os.name == 'nt':
        os.system('cls')
    else:
        os.system('clear')

def draw(bad_guesses, good_guesses, secret_word):
    clear()

    print('Strikes: {}/7'.format(len(bad_guesses)))
    print('')

    for letter in bad_guesses:
        print(letter, end='')
    print('\n\n')

    for letter in secret_word:
        if letter in good_guesses:
            print(letter, end='')
        else:
            print('_', end='')

    print('')

def get_guess(bad_guesses, good_guesses):
    while True:
        guess = input("Guess a letter: ").lower()

        if len(guess) != 1:
            print("You can only guess a single letter!")
        elif guess in bad_guesses or guess in good_guesses:
            print("You've already guessed that letter!")
        elif not guess.isalpha():
            print("You can only guess letters!")
        else:
            return guess

def play(done):
    clear()
    secret_word = random.choice(words)
    bad_guesses = []
    good_guesses = []

    while True:
        draw(bad_guesses, good_guesses, secret_word)
        guess = get_guess(bad_guesses, good_guesses)

        if guess in secret_word:
            good_guesses.append(guess)
            found = True
            for letter in secret_word:
                if letter not in good_guesses:
                    found = False

            if found:
                print("You win!")
                print("The secret word was {}".format(secret_word))
                done = True
        else:
            bad_guesses.append(guess)
            if len(bad_guesses) == 7:
                draw(bad_guesses, good_guesses, secret_word)
                print("You lost!")
                print("The secret word was {}".format(secret_word))
                done = True

        if done:
            play_again = input("Play again? Y/N: ").lower()
            if play_again != 'n':
                return play(done=False)
            else:
                sys.exit()

def welcome():
    start = input("Press enter/return to start or 'Q' to quit: ").lower()
    if start == 'q':
        print("Bye!")
        sys.exit()
    else:
        return True

print("Welcome to Letter Guess!")

done = False

while True:
    clear()
    welcome()
    play(done)

1 Answer

Steven Parker
Steven Parker
243,656 Points

This program has 3 "while" loops, all used when things (may) need to be repeated.

  1. In the "get_guess" function, the loop continues to ask for a choice until a valid one is entered. It only needs to repeat if the first choice is not valid.
  2. In the "play" function, the loop repeats the process of getting and testing a guess until the game is either won or lost.
  3. The main loop restarts the game over as long as the player chooses to play another game.

These loops are all necessary for the program to function as intended and without repeating sections of code many times.