擅长:python、mysql、java
<p>一种选择是使用寻址字典:</p>
<pre><code>import random
def dice():
help_message = (
"Valid commands include:\n"
"Coin, d4, d6, d8, d10, d12 or d20 in order to roll the corresponding dice or flip a coin.\n"
"Type Quit to close program.\n"
)
commands_dict = {
"help": lambda: help_message,
"coin": lambda: random.choice(("Heads", "Tails")),
"d4" : lambda: random.randint(1, 4),
"d8" : lambda: random.randint(1, 8),
"d10" : lambda: random.randint(1, 10),
"d12" : lambda: random.randint(1, 12),
"d20" : lambda: random.randint(1, 20)
}
default = lambda: "Invalid command. Type \"Help\" for list of valid commands."
while True:
dice_entry = input(":> ").lower().strip()
if dice_entry == "quit":
break
print(commands_dict.get(dice_entry, default)())
</code></pre>
<p>这是<a href="https://repl.it/repls/IllLavishBruteforceprogramming" rel="nofollow noreferrer">live example</a></p>