这是我确定涉及Python的相当基本的问题,但我最近才开始使用该程序。这是挑战:
“编写一个模拟幸运饼干的程序。程序应该在每次运行时随机显示五个独特财富中的一个。”
我的方法是将五个不同的变量分配给他们自己的财富:
fortune_1 = str("Good things come to those who wait.")
fortune_2 = str("Patience is a virtue.")
fortune_3 = str("The early bird gets the worm.")
fortune_4 = str("A wise man once said, everything in its own time and place.")
fortune_5 = str("Fortune cookies rarely share fortunes.")
我不清楚的是如何随机产生财富。有没有办法利用随机。模块每次唯一地选择五个预定命运之一?例如,我可以将这五个命运设置为数字,然后说出类似的内容:
user_fortune = random.randfortune(1,5)
?我希望这是有道理的。由于我是Python的新手,并且在本论坛发帖,我可能需要一些时间来更清楚地沟通。
谢谢!
答案 0 :(得分:3)
我的第一直觉是告诉你把你的命运分成某种序列(例如,列表,元组)。然后,您只需要选择一个随机元素。我在Python提示符下执行了以下操作:
>>> import random
>>> help(random)
Help on module random:
NAME
random - Random variable generators.
FILE
/usr/lib/python2.7/random.py
MODULE DOCS
http://docs.python.org/library/random
DESCRIPTION
integers
--------
uniform within range
sequences
---------
**pick random element**
pick random sample
generate random permutation
distributions on the real line:
啊哈! "选择随机元素"听起来不错。所以,我继续滚动:
| **choice**(self, seq)
| Choose a random element from a non-empty sequence.
|
啊哈啊!我想我应该知道这一点,但知道如何在需要时查看这些内容会很好。
可能的解决方案(Python 2.7):
import random
fortunes = ["Good things come to those who wait.",
"Patience is a virtue.",
"The early bird gets the worm.",
"A wise man once said, everything in its own time and place.",
"Fortune cookies rarely share fortunes."]
print random.choice(fortunes)
答案 1 :(得分:2)
您可以将财富添加到列表中,然后使用choice
从列表中选择随机项:
import random
fortunes = [fortune_1, fortune_2, fortune_3, fortune_4, fortune_5]
print random.choice(fortunes)
答案 2 :(得分:0)
非常感谢!
我也注意到我可以尝试以下方法:
import random
fortune = random.randint(1,5)
if fortune == 1:
print("Good things come to those who wait.")
elif fortune == 2:
print("Patience is a virtue.")
elif fortune == 3:
print("The early bird gets the worm.")
elif fortune == 4:
print("A wise man once said, everything in its own time and place.")
elif fortune == 5:
print("Fortune cookies rarely share fortunes.")