Is it possible only to declare a variable without assigning any value in Python?

后端 未结 14 1869
暖寄归人
暖寄归人 2020-11-30 17:26

Is it possible to declare a variable in Python, like so?:

var

so that it initialized to None? It seems like Python allows this, but as soon

14条回答
  •  心在旅途
    2020-11-30 17:51

    First of all, my response to the question you've originally asked

    Q: How do I discover if a variable is defined at a point in my code?

    A: Read up in the source file until you see a line where that variable is defined.

    But further, you've given a code example that there are various permutations of that are quite pythonic. You're after a way to scan a sequence for elements that match a condition, so here are some solutions:

    def findFirstMatch(sequence):
        for value in sequence:
            if matchCondition(value):
                return value
    
        raise LookupError("Could not find match in sequence")
    

    Clearly in this example you could replace the raise with a return None depending on what you wanted to achieve.

    If you wanted everything that matched the condition you could do this:

    def findAllMatches(sequence):
        matches = []
        for value in sequence:
            if matchCondition(value):
                matches.append(value)
    
        return matches
    

    There is another way of doing this with yield that I won't bother showing you, because it's quite complicated in the way that it works.

    Further, there is a one line way of achieving this:

    all_matches = [value for value in sequence if matchCondition(value)]
    

提交回复
热议问题