1

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://")
CFGal
  • 45
  • 4

1 Answers1

4

"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://"))
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
  • 3
    There's a better way actually; [`startswith` also accepts a `tuple` of prefixes to check for](https://docs.python.org/3/library/stdtypes.html#str.startswith), and returns `True` if any of them match. So you could write `URL.startswith(("http://", "https://"))` and it would behave identically to the `or` separated version you wrote (just shorter to type, and faster to run). – ShadowRanger Mar 06 '19 at 16:00
  • @ShadowRanger Brilliant, I just added your note to my answer. – DjaouadNM Mar 06 '19 at 16:03