What is the most Pythonic way to provide a fall-back value in an assignment?

后端 未结 9 2066
暗喜
暗喜 2021-02-01 04:29

In Perl, it\'s often nice to be able to assign an object, but specify some fall-back value if the variable being assigned from is \'undef\'. For instance:

my $x         


        
9条回答
  •  [愿得一人]
    2021-02-01 05:01

    If it's an argument to a function you can do this:

    def MyFunc( a=2 ):
        print "a is %d"%a
    
    >>> MyFunc()
    ...a is 2
    >>> MyFunc(5)
    ...a is 5
    

    [Edit] For the downvoters.. the if/else bit is unnecessary for the solution - just added to make the results clear. Edited it to remove the if statement if that makes it clearer?

提交回复
热议问题