我通过钻研来自学自学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行?
答案 0 :(得分: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")
答案 1 :(得分:3)
Python有很棒的多行字符串:
def print_it(somethig):
print """
----------
This is a test of the {} system.
----------
""".format(something)
print_it(0)
print_it(1)
答案 2 :(得分: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)
另请阅读此documentation
答案 3 :(得分: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])