better writing style for the following code

后端 未结 5 696
借酒劲吻你
借酒劲吻你 2021-01-28 09:42

I was wondering if someone could tell me the pythonic way to check out the following.

I have a 6 bit binary number and want to check with its decimal values. Using mathe

5条回答
  •  青春惊慌失措
    2021-01-28 10:13

    Personally I prefer a if/elif if I am understanding your ...

    so your:

    if(a==1):
        ....
    else:
        if(a==2)
    .....
    

    Becomes this if you use if elif ladder:

    if a==1:
        ....
    elif a==2:
        .....
    else:
        default
    

    You can also use Python's version of a conditional expression for simple ladders:

    def one():
       print("option 1 it is\n")
    
    def two():
       print("option 2 it is\n")
    
    def three():
       print("not one or two\n")
    
    one() if a==1 else two() if a==2 else three()
    

    Or even dictionaries:

    def one():
       print("option 1 it is\n")
    
    def two():
       print("option 2 it is\n")
    
    def three():
       print("not one or two\n")
    
    options = {1:one,
               2:two,
               3:three,
    }
    
    options[2]()
    

    There is a great discussion on Python forms of switch-case in this SO post.

提交回复
热议问题