1
沒有數字
我試過了/除外,但我無法得到它的工作輸出響應如果輸入包含在Python
下面的代碼:
#This is a guess the number game.
import random
secretNumber = random.randint(1, 20)
print('I am thinking of a number between 1 and 20.')
# Ask the player to guess 6 times.
for guessesTaken in range(1, 7):
print('Take a guess.')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print('Your guess is too high.')
else:
break # This condition is the correct guess!
if guess == secretNumber:
print('Good job! You guessed my number in ' + str(guessesTaken) + ' guesses!')
else:
print('Nope. The number I was thinking of was ' + str(secretNumber))
~~~~ 顯然如果我輸入一個字符串,它不會滿足任何條件,它只會打破一個錯誤。我不希望它打破一個錯誤。我該怎麼辦? 錯誤的是(這個詞,而不是數量「測試」響應時):
Traceback (most recent call last):
line 8, in <module>
guess = int(input())
ValueError: invalid literal for int() with base 10: 'test'
收集'ValueError'異常,例如 - '除了ValueError:'並處理它(例如'pass'忽略)。 – AChampion