Search code examples
pythonfunctionstartswith

startswith function - incorrect arguements - not throwing error


Can someone tell me why this doesn't throw an error? It prints True when the user types in http:// and false when they type in https://. I can't understand why it would work at all.

URL = input("Enter an URL address: ")
URL.startswith("http://" or "https://")

Solution

  • "http://" or "https://" is a boolean expression which evaluates to "http://", because that's what an or statement is (because "http://" is the first True-ish value encountered in the or statement), you need to do this instead:

    URL.startswith("http://") or URL.startswith("https://")
    

    Also, as @ShadowRanger suggested, you could make this shorter and faster by passing a tuple of accepted starting strings to the startswith method, it will then return True if any of the strings in the tuple matched with the start of the string:

    URL.startswith(("http://", "https://"))