<p>传递给<code>int()</code>的字符串只应包含数字:</p>
<pre><code>>>> int("stop")
Traceback (most recent call last):
File "<ipython-input-114-e5503af2dc1c>", line 1, in <module>
int("stop")
ValueError: invalid literal for int() with base 10: 'stop'
</code></pre>
<p>一个快速的解决方法是在这里使用<a href="http://docs.python.org/2/tutorial/errors.html#exceptions" rel="noreferrer">exception handling</a>:</p>
<pre><code>def guessingGame():
global randomNum
global userScore
guessTry = 3
while True:
guess = input('Guess a Number between 1 - 10, You have 3 Tries, or Enter Stop: ')
try:
if int(guess) == randomNum:
print('Correct')
break
if int(guess) < randomNum:
print('Too Low')
guessTry = guessTry - 1
print('You have, ' + str(guessTry) + ' Guesses Left')
if int(guess) > randomNum:
print('Too High')
guessTry = guessTry - 1
print('You have, ' + str(guessTry) + ' Guesses Left')
if guessTry == 0:
print('You have no more tries')
return
except ValueError:
#no need of str() here
if guess.lower() == 'stop':
break
guessingGame()
</code></pre>
<p>您可以使用<code>guess.lower() == 'stop'</code>来匹配“stop”的任何大小写组合:</p>
<pre><code>>>> "Stop".lower() == "stop"
True
>>> "SToP".lower() == "stop"
True
>>> "sTOp".lower() == "stop"
True
</code></pre>