0
codes = ["A", "B", "C", "D", "E"]
random.shuffle(codes)

    def print_message(message):
        print "\n"
        print "-"*10
        print message
        print "-"*10
        print "\n"

    print_message('This is a test of the %s system' % codes[0])

然后,我如何根据出现的随机字母为 print_message('This...') 的结果执行 if 语句。

例子。如果代码 [0] 的结果最终是 print_message() 的“A”,那么您会在屏幕上看到以下内容:

----------
This is a test of the A system. 
The A system is really great. 
---------

再运行几次命令,你会看到:

----------
This is a test of the C system.
The C system sucks. 
----------

----------
This is a test of the B system. 
The B system has improved greatly over the years. 
----------
4

2 回答 2

3

我会使用字典,并使用代码(“A”、“B”、“C”)作为字典键,并将“消息”放入 dict 值中。

codes = {
    'A': 'The A system is really great.',
    'B': 'The B system has improved greatly over the years.',
    'C': 'The C system sucks.'
}

random_key = random.choice(codes.keys())
print("This is a test of the %s system" % random_key)
print(codes[random_key])

注意:正如@mgilson 指出的,对于 python 3.x,random.choice需要一个列表,所以你可以这样做:

random_key = random.choice(list(codes.keys()))
于 2013-01-25T18:47:29.063 回答
1

这将为您提供问题中示例的结果:

#! /usr/bin/env python
import random
codes = ["A", "B", "C", "D", "E"]
random.shuffle(codes)

def print_sys_result(sys_code):
    results = {
        "A": "is really great",
        "B": "has improved greatly over the years",
        "C": "sucks",
        "D": "screwed us up really badly",
        "E": "stinks like monkey balls"
    }
    print "\n"
    print "-"*10
    print 'This is a test of the {0} system'.format(sys_code)
    if sys_code in results:
        print "The {0} system {1}.".format(sys_code, results[sys_code])
    else:
        print "No results available for system " + sys_code
    print "-"*10
    print "\n"

print_sys_result(codes[0])
于 2013-01-25T19:01:40.970 回答