2013-10-08 134 views
0

我正在做一個簡單的「猜一到十之間的數字」遊戲。我已經使用了一些基本的錯誤處理,並且打印了隨機模塊生成的數字用於測試目的。如何讓這段代碼更簡潔?

但是我想知道是否有一個不太詳細的方式來寫這個。

這是代碼:

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   

感謝,

+4

請嘗試http://codereview.stackexchange.com/而不是 –

+0

您有太多無用的'pass','continue'和'break'語句。另外play_again中的「if」或play_again中的「yes」與play_again中的if'y'完全等價。 – Shashank

回答

2
if guess >= 1 and guess <= 10: 

可以寫爲:

if 1 <= guess <= 10: 

而且,你的第一個條件可以簡單地書面爲:

if not 1 <= guess <= 10: 
    print("Input a number between one and ten silly!") 
    continue 

但是這也可以把try位內,從寫continue兩次拯救你:

try: 
    guess = int(input("Guess a number between one and ten.")) 
    if not 1 <= guess <= 10: 
     print("Input a number between one and ten silly!") 
     continue 
except ValueError: 
    print("Input a whole number between one and ten silly!") 
    continue 

最後你最後有條件的可以僅僅是:

if play_again not in ('y', 'yes'): 
    break 

continue ISN不需要。

您可能還想將其全部包裝到一個函數中,以擺脫那些無限的while循環,並防止您使用continuebreak這麼多。

0

爲什麼不把實際條件放在while循環中,所以你不必尋找休息時間來理解循環?它會使你的代碼更清晰和更小。

if guess == number: 
     print("You were successful and it took you", number_of_attempts, "attempts!!!") 
     break 

例如,如果你把guess == number作爲while循環的條件,那麼打印將是循環之後的第一件事。初始化猜測爲-1,所以它總是第一次工作。再次演奏if語句也可以在條件中消失。