2014-12-01 26 views
-4

我試圖找到一種方法來讓我的程序重複,所以例如我希望用戶能夠選擇骰子方4,得到結果,然後選擇骰子方12,而不必重新啓動代碼。我被告知使用while循環,但我不確定如何執行此操作。請幫助編寫一些代碼,這意味着我的程序可以重複多次。如何讓我的代碼重複? Python骰子

此外,我還希望我的程序詢問用戶是否要再次滾動,如果輸入'是'再次選擇骰子側,如果'否'輸出'再見'。

import random 

dice = raw_input("Choose a dice size from the following: 4, 6, 12: ") 
if dice =="4":    
    print "The result from the 4 sided die is: " ,random.randint(1,4)  
elif dice == "6":  
    print "The result from the 6 sided die is: " ,random.randint(1,6)  
elif dice =="12":  
    print "The result from the 12 sided die is: " ,random.randint(1,12)  
else:  
    print "Invalid die entered, please try again" 
+4

你認爲哪裏可以找到信息關於在Python中使用while循環?提示:從這裏開始:https://docs.python.org/2/tutorial/index.html – 2014-12-01 21:14:02

回答

1

把這些代碼片段在函數內部

import random 
def rollDice(): 
    dice = input("Choose a dice size from the following: 4, 6, 12: ") 
    if dice =="4": 
     print("The result from the 4 sided die is: " ,random.randint(1,4)) 
    elif dice == "6": 
     print("The result from the 6 sided die is: " ,random.randint(1,6)) 
    elif dice =="12": 
     print("The result from the 12 sided die is: " ,random.randint(1,12)) 
    else: 
     print("Invalid die entered, please try again") 

然後你就可以調用該函數在一個循環

for _ in range(5): 
    rollDice() 

注意,你可以寫一個同樣功能更簡潔

def rollDice(): 
    dice = int(input("Choose a dice size from the following: 4, 6, 12: ")) 
    if dice not in (4,6,12): 
     print("Invalid die entered, please try again") 
    else: 
     roll = random.randint(1,dice) 
     print("The result from the {} sided die is {}".format(dice,roll))