对缩短这段python代码有什么建议吗?

对缩短这段python代码有什么建议吗?,python,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) d

我已经创建了一个程序,根据用户输入的边数掷骰子。这是我的密码:

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()
有没有办法缩短这个时间


谢谢

您可以将这三种情况简化为一个模块,因为它们都有完全相同的操作

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()
每当在源代码中看到重复的模式时,通常可以将它们提取到单个块中

整个程序(尤其是没有
var
script
之间的递归循环,以及隐含的对调用堆栈的轰炸。尽管您的调用处于尾部位置,但这在python中没有区别):

或整个程序的代码版本:

(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'))

这更适合。更适合:codereview.stackexchange.com
(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'))