2

我通过深入研究自学python。如果你把它留空,我不确定一个函数是否会这样做:

#My first section that pulls a value from a random shuffle of codes
print "\n"
print "-"*10
print 'This is a test of the %s system'% codes[0]
print "-"*10
print "\n"

#My second section that pulls a value from a random shuffle of codes
print "\n"
print "-"*10
print 'This is not a test of the %s system and all is good'% codes[1]
print "-"*10
print "\n"

我的问题是,有没有办法让它看起来更好看,代码行更少?还是我坚持打印 10 行?

4

4 回答 4

3

你可以使用一个函数:

def print_stuff(what,addendum=''):
    print "\n"
    print "-"*10
    print 'This is a test of the %s system%s' % (what,addendum)
    print "-"*10
    print "\n"

print_stuff(codes[0])
print_stuff(codes[1],addendum = " and all is good")
于 2013-01-25T16:24:46.447 回答
3

Python 有非常棒的多行字符串:

def print_it(somethig):
    print """
----------
This is a test of the {} system.
----------
""".format(something)

print_it(0)
print_it(1)
于 2013-01-25T16:28:26.420 回答
2

使用索引号创建一个函数:

def print_codes(i):
    #My first section that pulls a value from a random shuffle of codes
    print "\n"
    print "-"*10
    print 'This is a test of the %s system'% codes[i]
    print "-"*10
    print "\n"

print_codes(0)
print_codes(1)

另请阅读此文档

于 2013-01-25T16:25:19.993 回答
1

如果要显示不同的消息,可以定义一个函数来接收要打印的消息:

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 is not a test of the %s system and all is good'% codes[1])
于 2013-01-25T16:38:09.117 回答