我想創建一個學校項目的Python猜數字遊戲。我做了一個基本的遊戲,能夠很好地工作,但我想添加一些異常處理,以防用戶輸入錯誤。例如,這是我的代碼段:'<'不支持案件之間 - 猜數字遊戲
def Normal_Guess():
number = round(random.uniform(0.0, 100.0),2)
guess = ""
while guess != number:
try:
guess = float(input("Please guess a number between 0 and 100: "))
except ValueError or TypeError:
print ("That isn't even a number!")
if guess < number and guess >= 0:
print ("You need to guess higher!")
elif guess > number and guess <= 100:
print ("You need to guess lower!")
elif guess == number:
print("Congratulations! You guessed the number!")
elif guess < 0 or guess > 100:
print ("The number you guessed is not between 0 and 100")
else:
print("That isn't even a number!")
New_Game()
也能正常工作,當用戶進入一個浮點或整數值爲「猜測」,並嘗試,除了條款我看來,如果用戶輸入捕捉首先,除了數字之外的任何事情,但該計劃似乎也繼續進行「如果」的陳述。我得到一個TypeError,說「'str'和'float'的實例之間不支持」'<'「。
我試圖包含一個Try-Except子句中的整個循環,並且不起作用。我不知道我做錯了什麼。任何幫助深表感謝。
,用'繼續'在打印信息後。 – asongtoruin
或者,在'try'-'except'塊中添加一個'else'子句來處理沒有明確異常的情況。 –
或者,在'try'塊內移動'if else'鏈,因爲這是它在邏輯上屬於的地方。 –