Note that there are some explanatory texts on larger screens.

plurals
  1. POLooking for ways to improve my hangman code
    primarykey
    data
    text
    <p>Just getting into python, and so I decided to make a hangman game. Works good, but I was wondering if there was any kind of optimizations I could make or ways to clean up the code. Also, if anyone could recommend a project that I could do next that'd be cool.</p> <pre><code>import sys import codecs import random def printInterface(lst, attempts): """ Prints user interface which includes: - hangman drawing - word updater """ for update in lst: print (update, end = '') if attempts == 1: print ("\n\n\n\n\n\n\n\n\n\n\n\t\t _____________") elif attempts == 2: print (""" | | | | | | | | | ______|______""") elif attempts == 3: print (""" ______ | | | | | | | | | ______|______""") elif attempts == 4: print (""" ______ | | | | (x_X) | | | | | | | ______|______""") elif attempts == 5: print (""" ______ | | | | (x_X) | | | | | | | | | | ______|______""") elif attempts == 6: print (""" ______ | | | | (x_X) | | | /| | | | | | | ______|______""") elif attempts == 7: print (""" ______ | | | | (x_X) | | | /|\ | | | | | | ______|______""") elif attempts == 8: print (""" ______ | | | | (x_X) | | | /|\ | | | / | | | ______|______""") elif attempts == 9: print (""" ______ | | | | (x_X) | | | /|\ | | | / \ | | | ______|______""") def main(): try: wordlist = codecs.open("words.txt", "r") except Exception as ex: print (ex) print ("\n**Could not open file!**\n") sys.exit(0) rand = random.randint(1,5) i = 0 for word in wordlist: i+=1 if i == rand: break word = word.strip() wordlist.close() lst = [] for h in word: lst.append('_ ') attempts = 0 printInterface(lst,attempts) while True: guess = input("Guess a letter: ").strip() i = 0 for letters in lst: if guess not in word: print ("No '{0}' in the word, try again!".format(guess)) attempts += 1 break if guess in word[i] and lst[i] == "_ ": lst[i] = (guess + ' ') i+=1 printInterface(lst,attempts) x = lst.count('_ ') if x == 0: print ("You win!") break elif attempts == 9: print ("You suck! You iz ded!") break if __name__ == '__main__': while True: main() again = input("Would you like to play again? (y/n): ").strip() if again.lower() == "n": sys.exit(1) print ('\n') </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload