【问题标题】:Python- Simple random selectorPython-简单的随机选择器
【发布时间】:2014-09-25 10:36:37
【问题描述】:

我正在用 python 创建一个简单的游戏,它会问你问题,然后使用答案来填补故事中的空白。我想让它每次都以随机顺序提出问题,但我希望提出所有问题。

我在 Mac OSX 上使用 python 2.7.8,想知道我可以做些什么来得到这个结果?

提前感谢您的帮助!

如果有帮助,下面的代码:

while True: 

    print "Welcome to Consequences"
    print ' '
    print "Game is more fun in groups!"
    print''
    print "Group instructions :"
    print "Get in a circle and let each person enter one thing each without the rest of the group seeing    what they enter"
    print ' '
    print ' '
    print raw_input("Press enter to start")
    hide(str)

    nameb = raw_input("Enter a boys name then press enter ")

    hide(str)

    nameg = raw_input("Enter a girls name then press enter ")

    hide(str)

    place = raw_input("Enter a place that two people meet then press enter ")

    hide(str)

    saidtg = raw_input("Enter what the boy said to the girl then press enter ")

    hide(str)

    saidtb = raw_input("Enter what the girl said to the boy and then press enter ")

    hide(str)

    end = raw_input("Enter what happened in the end and then press enter ")

    hide(str)

    print "Here is your story:"
    print ' '
    print nameb, "met", nameg
    print "they met at", place
    print "then",nameb,"said to", nameg, saidtg
    print "then",nameg,"replied with", saidtb
    print "in the end", end

    raw_input("Press enter to start again")
    print ' '
    print ' '
    print ' '
    print ' '

【问题讨论】:

  • 非常聪明,您使用了while True,但我猜您忘记了相应的缩进。 while True 之后的所有语句都在该 while 循环之外。
  • 很抱歉,我一定是在帖子中输入了错误的内容,但我的实际代码中确实有缩进的语句。复制过来一定是做错了什么。
  • 是这样吗?我可以为您正确编辑,以免其他成员指出。
  • 恐怕这个问题很可能被否决。它太笼统了,并没有真正显示出任何解决问题的尝试。
  • 我为这个可怜的问题道歉,但我对此很陌生,并且肯定会很棒 sammy :)

标签: python random


【解决方案1】:

您可以将问题存储在列表中并使用字典来存储变量:

questions = [('Enter name of boy', 'nameb') , ('Enter place', 'place'),...]

然后随机排列列表并询问每个问题:

>>> import random
>>> random.shuffle(questions,random.random) #shuffle list in place
>>> d = {}
>>> for (q,v) in questions:
...    d[v] = raw_input(q)
...    #more stuff like hide(str)

然后代替:

print nameb, "met", nameg
print "they met at", place

你只需要这样做

print d['nameb'], "met", d['nameg']
print "they met at", d['place']

【讨论】:

  • 非常感谢!因为我是 python 和编码的新手,所以需要解决这个问题,但我相信我最终会的。
  • 我想我理解除了这部分之外的所有内容:d = {} >>> for q in questions: ... d[q[1]] = raw_input(q[0])跨度>
  • @EdEdwardTervit 我稍微改变一下:d={} 创建一个新的字典。 for (q,v) in questions 循环所有问题/变量名称并将问题分配给 q,将名称分配给 v。然后 d[v] = raw_input(q) 询问 q 并将答案放入字典中,键为 v
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-01
  • 2014-04-23
  • 2019-05-05
  • 1970-01-01
  • 2019-03-18
相关资源
最近更新 更多