首页 > 解决方案 > 如何让用户的输入在 Python 中消失?

问题描述

我是一个初学者,我正在为一个家庭成员准备一个圣诞游戏。一开始,游戏会要求玩家输入特定的输入,比如地窖里的酒瓶数量。

因此,我写了这样的东西:

correct_wine = 8
wine = int(input("How many wine bottles are there? "))
while correct_wine != wine:
   print("Wrong answer. Please try again.")
   wine = int(input("Number of bottles: "))

最后,游戏要求玩家提供相同的输入。

new_wine = int(input("Just to make sure, how many wine bottles were there? "))
while correct_wine != new_wine:
   print("Perhaps you should go and count them again.")
   new_wine = int(input("Number of bottles: "))

显然,我希望玩家在游戏结束时已经忘记了瓶子的数量,并且不得不重新计算它们。然而,虽然第一个输入在屏幕上仍然可见,但玩家复制它并不困难,从而破坏了再次提问的意义。有没有办法让第一个输入消失?

标签: python-3.x

解决方案


您可以尝试调用 clsclear取决于用户的操作系统是否为WindowsDarwinmacOS)Linux等:

from platform import system
from subprocess import call

def get_int_input(prompt: str) -> int:
    num = -1
    while True:
        try:
            num = int(input(prompt))
            break
        except ValueError:
            print("Error: Enter an integer, try again...")
    return num

correct_wine = 8
wine = get_int_input("How many wine bottles are there? ")
while correct_wine != wine:
    print("Wrong answer. Please try again.")
    wine = get_int_input("Number of bottles: ")
print("Correct")

# ... Other parts of your quiz go here

call('cls') if system() == 'Windows' else call('clear')

new_wine = get_int_input("Just to make sure, how many wine bottles were there? ")
while correct_wine != new_wine:
   print("Perhaps you should go and count them again.")
   new_wine = get_int_input("Number of bottles: ")

推荐阅读