2013-12-11 41 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'))