我正在做一個簡單的「猜一到十之間的數字」遊戲。我已經使用了一些基本的錯誤處理,並且打印了隨機模塊生成的數字用於測試目的。如何讓這段代碼更簡潔?
但是我想知道是否有一個不太詳細的方式來寫這個。
這是代碼:
import random
while True:
"""Variable declaration"""
number_of_attempts = 1
number = random.randrange (1,11)
print (number)
print("Time to play a guessing game! Muhahaha...")
"""Error handling and main game code/while loop"""
while True:
try:
guess = int(input("Guess a number between one and ten."))
except ValueError:
print("Input a whole number between one and ten silly!")
continue
if guess >= 1 and guess <= 10:
pass
else:
print("Input a number between one and ten silly!")
continue
if guess == number:
print("You were successful and it took you", number_of_attempts, "attempts!!!")
break
else:
print("Try again!")
number_of_attempts = number_of_attempts +1
"""Game Exit/Restart"""
play_again = input("Would you like to play again, y/n?")
if "y" in play_again or "yes" in play_again:
continue
else:
break
感謝,
本
請嘗試http://codereview.stackexchange.com/而不是 –
您有太多無用的'pass','continue'和'break'語句。另外play_again中的「if」或play_again中的「yes」與play_again中的if'y'完全等價。 – Shashank