<p>当然有:</p>
<p>变量命名:您的变量dice\u条目名称不正确。你也可以扔硬币,或退出,或键入与骰子无关的帮助。你知道吗</p>
<p>使用<code>random.choices</code>:您可以使用<code>random.choice</code>,而不要使用<code>"".join</code></p>
<p><a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself" rel="nofollow noreferrer">WET</a>:有些代码被多次复制,您可以使用一个函数。你知道吗</p>
<p>无用代码:命令变量的作用是什么?尤其是<code>"".lower()</code>的意义是什么?为什么不干脆<code>""</code></p>
<pre><code>import random
def throw_dice(nb_faces):
return random.randint(1, nb_faces)
def throw_coin():
return random.choice(['Heads', 'Tails'])
def main():
while True:
entry = input(":> ").lower().strip()
if entry == "help":
print("""
Valid commands include:
Coin, d4, d6, d8, d10, d12 or d20
in order to roll the corresponding dice
or flip a coin.
Type Quit to close program.""")
elif entry == "coin":
print(throw_coin())
elif entry in ["d4", "d6", "d8", "d10", "d12", "d20"]:
nb_faces = int(entry[1:])
print(throw_dice(nb_faces))
elif entry == "quit":
break
else:
print('Invalid command. Type "Help" for list of valid commands.')
</code></pre>