2013-12-11 84 views
-1

嗨,我已經做了這個隨機骰子游戲,需要幫助創建一個循環,讓我當用戶輸入一個無效的數字我想他們再試一次。這裏是我的代碼請幫忙!骰子重複需要幫助

import random 
dice = int(input("What sided dice do you want to use? (e.g. 4, 6 or 12): ")) 
if dice == 4: 
       random_number = int(random.randrange(1,4)) 
       print ("You selected a 4 sided dice") 
       print ("Your dice has rolled ") 
       print (random_number) 
elif dice == 6: 
       random_number2 = int(random.randrange(1,6)) 
       print ("You selected a 6 sided dice") 
       print("Your dice has rolled ") 
       print (random_number2) 
elif dice == 12: 
       random_number3 = int(random.randrange(1,12)) 
       print ("You selected a 12 sided dice") 
       print("Your dice has rolled ") 
       print (random_number3) 
else: 
       print(("You didn't select a valid sided dice, try again!"))* 
+0

注意'random.randrange'不包括端點,所以'randrange(1,4) '只會給你任何'[1,2,3]'。 –

+1

這段代碼中有很多*重複;你可以使用'dice'變量來削減它的三分之二(例如'random.randrange(1,dice + 1')。 – jonrsharpe

回答

1

使用while循環:

import random 
dice = None 
while dice not in (4, 6, 12): 
    dice = int(input("What sided dice do you want to use? (e.g. 4, 6 or 12): ") 
if dice == 4: 
      random_number = int(random.randrange(1,4)) 
      print ("You selected a 4 sided dice") 
      print ("Your dice has rolled ") 
      print (random_number) 
elif dice == 6: 
      random_number2 = int(random.randrange(1,6)) 
      print ("You selected a 6 sided dice") 
      print("Your dice has rolled ") 
      print (random_number2) 

elif dice == 12: 
      random_number3 = int(random.randrange(1,12)) 
      print ("You selected a 12 sided dice") 
      print("Your dice has rolled ") 
      print (random_number3) 
+0

歡呼這個工程! – James

+0

如果你覺得這個答案有幫助,請[接受答案](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work):) – aIKid

+0

我建議使用一個短循環,提示,直到它得到一個有效的響應,然後切換基於輸入。這更容易出錯;如果任何一個案例缺少一個「break」,它就有一個bug。 – user2357112

3

你需要兩樣東西對於這樣的:

  1. 一個while循環,以保持繞來繞去,直到你得到你想要的東西;和
  2. 收集可接受的答案來檢查。

例如,一個簡單的解決辦法是用包裹當前的input聲明:

dice = 0 
while dice not in (4, 6, 12): 
    dice = ... 
# continue