【问题标题】:In python how do I assign a series of commands to one variable?在 python 中,如何将一系列命令分配给一个变量?
【发布时间】:2013-01-09 15:52:43
【问题描述】:

我正在通过深入研究自学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 行?

【问题讨论】:

  • 每个人都有这么好的答案。我尝试了所有这些,它们工作得很好。我选择了最适合我的目的的一个。非常感谢大家的精彩意见。

标签: python dictionary function


【解决方案1】:

你可以使用一个函数:

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

【讨论】:

  • 这也很好用。如果结果是特定字符串,我如何使用附录与第一个 print_stuff(codes[0]) 的结果来打印消息。
【解决方案2】:

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

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

print_it(0)
print_it(1)

【讨论】:

    【解决方案3】:

    用索引号创建一个函数:

    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

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

      • 这很好用。如何根据 print_message 的结果创建 if 语句?我在尝试时不断收到错误,我认为这是因为结果是随机的,或者我无法创建一个变量来针对基于 def 的 if 语句运行。示例:如果第一个 print_message == "A",则从上方打印 print_message 并在其下方打印另一条消息,说“我看到结果是 A。太好了”
      • 你必须在函数中返回你想要的任何东西。在 print_message 中添加一个 return 语句,然后您可以使用 if print_message('My message') == 'A' 检查返回的内容。您还可以将结果分配给变量,例如 my_result = print_message('My message')。如果 my_result == 'A' ...
      • 哦,我现在明白了。非常感谢。
      猜你喜欢
      • 1970-01-01
      • 2023-02-09
      • 1970-01-01
      • 2010-12-29
      • 1970-01-01
      • 2017-08-12
      • 1970-01-01
      • 2021-06-11
      • 2019-08-16
      相关资源
      最近更新 更多