Python inline elif possible?

前端 未结 7 2246
耶瑟儿~
耶瑟儿~ 2021-02-07 11:16
\'Hello \' + (\'there\' if name is None else name)

Is the equivalent of

msg = \'Hello \'
if name is None:
    msg += \'there\'
else:
          


        
7条回答
  •  暖寄归人
    2021-02-07 11:52

    Firstly, run 'pip install pyswitch'

    Then:

    import pyswitch
    
    mySwitch = pyswitch.Switch()
    
    @mySwitch.case(None):
    def gotNone(value):
        return 'Hello there'
    
    @mySwitch.case('Mr. Anderson')
    def gotMrAnderson(value):
        return 'Hello Neo'
    
    @mySwitch.default
    def gotDefault(value):
        return 'Hello %s' % value
    
    msg = mySwitch.switch(None)  # Returns 'Hello there'
    msg = mySwitch.switch('Mr. Anderson')  # Returns 'Hello Neo'
    msg = mySwitch.switch('OoglyMoogly')  # Returns 'Hello OoglyMoogly'
    

提交回复
热议问题