编写随机生成的测验,需要回忆随机生成的对象

0 投票
3 回答
800 浏览
提问于 2025-04-16 14:32

我刚开始学习Python,所以我的代码可能效率很低,等等,但我现在只是摸索着学习,请原谅我对这些的无知。

我的测验目前是从一系列引用中随机打印前20个字符(通过切片),目的是让答题者背诵剩下的部分。

我想增加一个功能,可以获取整个引用,但我不知道怎么告诉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

在这里,打印语句调用最开始被切片的对象,但要完整打印出来。

我看过Python随机模块的文档,但没有找到答案。

我也愿意接受更有效的方法(我知道可以把引用存储在一个单独的文件里,但我还没弄明白怎么做)。

提前感谢任何帮助!

3 个回答

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了。

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
2

quote[:20] 这个操作不会改变你原来的 quote 内容。所以直接用 print quote 打印出来是没问题的!

(顺便说一下,如果你还需要这个值,其实你不必去记住 random 的最后一个值,你可以直接把它返回的最后一个值存起来。)

撰写回答