1

Here is my code (for hangman game):

import random, os

def main():

  print("******THIS IS HANGMAN******")
  print("1. Play Game ")
  print("2. Quit Game ")
  choice = input("Please enter option 1 or 2")

  if choice == "1":
     words = ["school", "holiday", "computer", "books"]
     word = random.choice(words)
     guess = ['_'] * len(word)
     guesses = 7

     while '_' in guess and guesses > 0:
         print(' '.join(guess))
         character = input('Enter character: ')

         if len(character) > 1:
             print('Only enter one character.')
             continue

         if character not in word:
             guesses -= 1

         for i, x in enumerate(word):
             if x == character:
                 guess[i] = character

         if guesses == 0:
             print('You LOST!')
             break

         else:
             print('You have only', guesses, 'chances left to win.')

     else:
         print('You won')

  elif choice == "2":
      os.system("cls")
      main()

  else:
    print("that is not a valid option")

main()

I have tried os.system("clear") but it doesn't clear the screen, I want it to clear the entire screen but instead (cls) makes it print my menu again and (clear) does nothing except clear the 2. If I'm missing something obvious it's probably because I'm new to python.

Moshe Slavin
  • 5,127
  • 5
  • 23
  • 38

1 Answers1

0

It prints the menu again because you call main() again instead of just stopping there. :-)

elif choice == "2":
      os.system("cls")
      main() # <--- this is the line that causes issues

Now for the clearing itself, os.system("cls") works on Windows and os.system("clear") works on Linux / OS X as answered here.

Also, your program currently tells the user if their choice is not supported but does not offer a second chance. You could have something like this:

def main():

  ...

  while True:
      choice = input("Please enter option 1 or 2")
      if choice not in ("1", "2"):
          print("that is not a valid option")
      else:
          break

  if choice == "1":
      ...

  elif choice == "2":
      ...

main()
hspil
  • 117
  • 1
  • 6
Guimoute
  • 4,407
  • 3
  • 12
  • 28