2013-12-11 67 views
-1

我已經創建了一個程序,根據用戶輸入的邊的數量來擲骰子。這裏是我的代碼:關於縮短這個Python代碼的任何建議?

def var(): 

    import random 

    dicesides = int(input("Please enter the amount of sides you want the dice that is being thrown to have. The dice sides available are: 4, 6 and 12: ")) 
    script(dicesides, random) 

def script(dicesides, random): 

    if dicesides == 4: 
     dice4 = int(random.randrange(1, dicesides)) 
     print(dicesides, " sided dice, score", dice4) 

    elif dicesides == 6: 
     dice6 = int(random.randrange(1, dicesides)) 
     print(dicesides, " sided dice, score", dice6) 

    elif dicesides == 12: 
     dice12 = int(random.randrange(1, dicesides)) 
     print(dicesides, " sided dice, score", dice12) 

    elif dicesides != 4 or dicesides != 6 or dicesides != 12: 
     print("That number is invalid. Please try again.") 
     var() 

    repeat = str(input("Repeat? Simply put yes or no : ")) 

    if repeat == "yes": 
     var() 
    else: 
     quit() 

var() 

有沒有辦法縮短這個?

感謝

+7

這個更適合** http://codereview.stackexchange.com/**。 – lifetimes

+3

更適合:codereview.stackexchange.com –

回答

2

可以將所有三種這些案件簡化成一個塊,因爲它們都具有完全相同的動作。

def script(dicesides, random): 
    if dicesides in [4,6,12]: 
     dice = int(random.randrange(1, dicesides)) 
     print(dicesides, " sided dice, score", dice) 
    else: 
     print("That number is invalid. Please try again.") 
     var() 

無論何時您在源代碼中看到重複模式,通常都可以將它們提取到一個塊中。

2

整個程序(特別是沒有varscript和調用堆棧的隱含轟擊之間的遞歸循環。雖然你的電話是在尾部的位置,這使得在Python沒有區別。):

from random import randint 

while True: 
    sides = int(input('Please enter the amount of sides you want the dice that is being thrown to have. The dice sides available are: 4, 6 and 12:')) 
    if sides in (4, 6, 12): 
     print('{}-sided die, score {}'.format(sides, randint(1, sides))) 
    else: 
     print('That number is invalid.') 
    if input('Repeat? ') != 'yes': 
     break 

還是代碼高爾夫版全程序:

(lambda f,r:f(f, r))((lambda f,r:f(f,r)if((lambda r,i: 
print('{}-sided die, score {}'.format(i,r.randint(1,i) 
)if i in(4, 6,12)else'That number is invalid.')) (r, (
lambda:int(input('Please enter the amount of sides yo' 
'u want the dice that is being thrown to have. The di' 
'ce sides available are: 4, 6 and 12: ')))()),input('' 
'Repeat? '))[1]=='yes'else None),__import__('random'))