编写随机生成测验,需要调用随机生成的对象

时间:2011-03-27 22:03:41

标签: python

我是python的新手,所以我确定我的代码效率很低,等等,但我只是感觉自己的方式并且现在正在学习,所以请原谅我一般的无知。

我的测验目前需要一系列引号并随机打印它们的前20个字符(通过切片),这个想法是quizee背诵其余部分。

我想添加获取整个引号的功能,但我不知道如何告诉python调用随机模块生成的最后一个对象。

这是我的代码:

import random
control = True

JCIIiii34 = "Valiant men never taste of death but once"
SonnetSeventeen = "If I could write the beauty of your eyes,\nAnd in fresh numbers number all your graces,\nThe age to come would say this poet lies,\nSuch heavenly touches ne'er touched earthly faces."
SonnetEighteen = "So long as men can breath and eyes can see,\nSo long lives this, and this gives life to thee."
JCIii101 = "I had as lief not be as live to be\nIn awe of such a thing as I myself"


print "After quote type 'exit' to leave, or 'next' for next quote"

while control:
    quote = random.choice([SonnetSeventeen,SonnetEighteen,JCIIiii,JCIii])
    print quote[:20]
    var = raw_input ("\n")
    if var == "exit":
        control = False
    elif var == "next":
        print "\n"
        control = True

所以我希望能够做的是添加一个elif语句

elif var == "answer":
     print #the full quote

print语句调用最初切片的对象,但是将其打印出来。

我已经阅读了随机模块的python库条目,但没有找到答案。

我也愿意采用更有效的方法(我知道我可以将引号存储在一个单独的文件中,但还没有想到这一点)。

提前感谢您的帮助!

3 个答案:

答案 0 :(得分:2)

您可以使用quote本身:

while control:
    quote = random.choice([SonnetSeventeen,SonnetEighteen,JCIIiii34,JCIii101])
    print quote[:20]
    var = raw_input ("\n")
    if var == "exit":
        control = False
    elif var == "next":
        print "\n"
        control = True
    elif var == "answer":
        print quote

答案 1 :(得分:2)

quote[:20]不会破坏您原来的quote。所以简单的print quote应该有效!

(顺便说一下。如果你仍然需要它,你不必回忆random的最后一个值,你可以存储它返回的最后一个值)

答案 2 :(得分:0)

与Emilio相同的答案,但您也可以使用print [20:]打印以前未显示的其余报价。而且,简单地说Emilio说的话,你可以做到:

  while True:
    quote = random.choice([SonnetSeventeen,SonnetEighteen,JCIIiii34,JCIii101])
    print quote[:20]
    var = raw_input ("\n")
    if var == "exit":
        break
    elif var == "next":
        print "\n"
    elif var == "answer":
        print quote[20:]

在“elif var =='next'”语句中,您不需要将控件分配给True,因为它在到达该点时已经为True。