【问题标题】:How do I clear the screen in Python 3?如何在 Python 3 中清除屏幕?
【发布时间】:2021-01-07 22:55:41
【问题描述】:

这是我的代码(用于刽子手游戏):

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

我尝试过os.system("clear"),但它没有清除屏幕,我希望它清除整个屏幕,但是 (cls) 让它再次打印我的菜单,并且 (clear) 除了清除 2 之外什么都不做。如果我'我遗漏了一些明显的东西,这可能是因为我是 python 新手。

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    它会再次打印菜单,因为您再次调用main() 而不是停在那里。 :-)

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

    现在对于清算本身,os.system("cls") 适用于 Windows,os.system("clear") 适用于 Linux / OS X,如回答 here

    此外,您的程序当前会告诉用户他们的选择是否不受支持但不提供第二次机会。你可以有这样的东西:

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

    【讨论】:

    • 感谢您的回复,这对您有很大帮助。
    猜你喜欢
    • 1970-01-01
    • 2011-06-16
    • 1970-01-01
    • 2015-08-17
    • 2011-04-08
    • 2018-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多