diff options
-rw-r--r-- | bot/resources/tags/codeblock.md | 2 | ||||
-rw-r--r-- | bot/resources/tags/equals-true.md | 24 | ||||
-rw-r--r-- | bot/resources/tags/range-len.md | 4 |
3 files changed, 27 insertions, 3 deletions
diff --git a/bot/resources/tags/codeblock.md b/bot/resources/tags/codeblock.md index c2b77637e..c7f2990fd 100644 --- a/bot/resources/tags/codeblock.md +++ b/bot/resources/tags/codeblock.md @@ -1,6 +1,6 @@ --- embed: - title: "Formatting code on discord" + title: "Formatting code on Discord" --- Here's how to format Python code on Discord: diff --git a/bot/resources/tags/equals-true.md b/bot/resources/tags/equals-true.md new file mode 100644 index 000000000..d8e1a707e --- /dev/null +++ b/bot/resources/tags/equals-true.md @@ -0,0 +1,24 @@ +--- +embed: + title: "Comparisons to `True` and `False`" +--- +It's tempting to think that if statements always need a comparison operator like `==` or `!=`, but this isn't true. +If you're just checking if a value is truthy or falsey, you don't need `== True` or `== False`. +```py +# instead of this... +if user_input.startswith('y') == True: + my_func(user_input) + +# ...write this +if user_input.startswith('y'): + my_func(user_input) + +# for false conditions, instead of this... +if user_input.startswith('y') == False: + my_func(user_input) + +# ...just use `not` +if not user_input.startswith('y'): + my_func(user_input) +``` +This also applies to expressions that use `is True` or `is False`. diff --git a/bot/resources/tags/range-len.md b/bot/resources/tags/range-len.md index 4bd377d59..76fe9051e 100644 --- a/bot/resources/tags/range-len.md +++ b/bot/resources/tags/range-len.md @@ -2,12 +2,12 @@ embed: title: "Pythonic way of iterating over ordered collections" --- -Iterating over `range(len(...))` is a common approach to accessing each item in an ordered collection. +Beginners often iterate over `range(len(...))` because they look like Java or C-style loops, but this is almost always a bad practice in Python. ```py for i in range(len(my_list)): do_something(my_list[i]) ``` -The pythonic syntax is much simpler, and is guaranteed to produce elements in the same order: +It's much simpler to iterate over the list (or other sequence) directly: ```py for item in my_list: do_something(item) |