有关缩短此python代码的任何建议吗?

时间:2013-12-11 20:10:40

标签: 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()

有没有办法缩短这个?

由于

2 个答案:

答案 0 :(得分: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()

每当您在源代码中看到重复的模式时,通常可以将它们提取到一个块中。

答案 1 :(得分:2)

整个程序(特别是没有varscript之间的递归循环以及对callstack的隐含轰击。虽然你的调用处于尾部位置,但这在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'))