[Tutor] Re: Please critique my hangman.py program (original) (raw)
Isr Gish isrgish at fastem.com
Sun Jul 25 05:55:12 CEST 2004
- Previous message: [Tutor] Converting month names to abbreviated form
- Next message: [Tutor] Re: Please critique my hangman.py program
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Hi Alan,
[snip]
# Setup list to hold correct letters correct_so_far = [] for i in range(word_length): correct_so_far.append("_")correct_so_far = ['_'] * word_lengthBut you could just use a string which is esier to print later:
xcorrect_so_far = '_' * word_length# Setup some other variables incorrect = [] guesses = 0 letters_guessed = 0guesses, letters_guessed = 0, 0# Start main game loop. print "\nI am thinking of a word",word_length,"letters long" while letters_guessed < word_length: # Print status of game on each pass. print print_status (correct_so_far,incorrect,guesses) # Get guess from user while 1: guess = raw_input("Which letter would you like to try?") guess = string.lower(guess) if len(guess) != 1: print "You can only guess one letter at a time!" elif guess in incorrect or guess in correct_so_far: print "You've already tried that letter!" elif guess not in ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q"," r","s","t","u","v","w","x","y","z"]: print "That's not a valid letter." else: break guesses = guesses + 1
# Evaluate guess against word letter_correct = 0 for i in range(word_length): if guess == word[i]: correct_so_far[i] = guess letter_correct=1 letters_guessed = letters_guessed + 1Personally I'd use a while loop here:
i,letter_correct = 0,False while i < word_length and not letter_correct: if guess == word[i]: correct_so_far[i] = guess letter_correct=True letters_guessed += 1 i += 1Same length but I just think the test expresses the intention of the loop better.
I think that there may be a problem with this. For a word that has 2 of the same letter. The original way checks for that, while the latter way would make "letter_correct" = to "True" by the first pass andsthe while loop would terminate.
All the best, Isr
[snip]
Hope those ideas help. They are not definitively better just some alternatives.
Alan G.
Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor
- Previous message: [Tutor] Converting month names to abbreviated form
- Next message: [Tutor] Re: Please critique my hangman.py program
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]