<blockquote>
<p>"... that forces them to <strong>reenter</strong> until it is correct?... "</p>
</blockquote>
<p>由于您还要求一种重新输入的方法,下面的代码片段使用格式为<code>\033[<N>A</code>的转义序列<a href="http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/x361.html" rel="nofollow">moves the cursor <strong>up</strong> N lines</a>和<a href="https://en.wikipedia.org/wiki/Carriage_return" rel="nofollow">Carriage Return</a>转义序列<code>\r</code>,打印无效数据并再次接受输入。在</p>
<pre><code>import sys
age = 0
gender = ""
agePrompt = "How old are they? "
genderPrompt = "What is their gender Male or Female? "
#Input for age
print("")
while not ( 18 <= age <= 25 ):
sys.stdout.write( "\033[1A\r" + " " * (len(agePrompt) + len(str(age))) )
sys.stdout.write( "\r" + agePrompt )
sys.stdout.flush()
age=int(input())
#Input for gender
print("")
while not ( gender == "Male" or gender == "Female" ) :
sys.stdout.write( "\033[1A\r" + " " * (len(genderPrompt) + len(str(gender))) )
sys.stdout.write( "\r" + genderPrompt )
sys.stdout.flush()
gender=str(input())
</code></pre>
<p>另一种解决方案是使用<code>\033[<N>D</code>形式的转义序列<a href="http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/x361.html" rel="nofollow">moves the cursor <strong>backward</strong> N columns</a>。在</p>