如何在Python中基于随机字符串执行if语句?

时间:2013-01-25 18:40:35

标签: python variables if-statement random statements

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语句。

实施例。如果code [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. 
----------

2 个答案:

答案 0 :(得分:3)

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

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()))

答案 1 :(得分: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])