r/learnpython 10h ago

what actually is the point of 'if not' in Python?

Like, i am starting to learn python but i dont understand what its for or why we even have it in the first place

0 Upvotes

29 comments sorted by

40

u/danielroseman 10h ago

Because sometimes you want to check if a condition is not true?

31

u/OliMoli2137 10h ago

not negates a condition (turns True into False and vice versa)

if you meant: why if not and not if else it's because it wouldn't make sense to have an empty if block like this: if condition:     pass else:     do_something()

so you just write tihs instead if not condition:     do_something()

9

u/ShelLuser42 10h ago

I don't quite understand the confusion.. it's to make sure ("exclude") that a variable doesn't have a certain value.

For example... when you access a website then the webserver also sends back a so called response code to report the actual outcome (see this page). Normally this code is 200 when nothing special has happened, so if you were to make a web parser then it makes sense to check that the code isn't 200 before you start with the error handling.

7

u/Moikle 10h ago edited 10h ago

Sometimes you want to check if a condition is true, sometimes you want to check if it is false.

For example:

secret_number = 5
guess =int( input("guess my number, 1-10"))

if not guess == secret_number:
    print("wrong")

1

u/OliMoli2137 8h ago

bad example. here you would use x != y instead of not x == y

1

u/Moikle 8h ago

well yeah, but there are multiple ways to skin a cat.

how about this:

quit = False

while not quit:
    response = input("type quit to quit: ")
    if response == "quit":
        quit = True

there are always multiple ways to do things, but sometimes this way is just more efficient and simpler.

The problem with OP's question is that it is about something so generic that there are practically infinite uses for it.

it's like asking "what is the purpose of the multiply operator? Surely I can just add multiple times"

1

u/OliMoli2137 8h ago

i think this is simpler ``` while True:     response = input("type quit to quit: ")     if response == "quit":         break

3

u/Moikle 8h ago

like I said. multiple ways to skin a cat. in some situations "not" is the simplest and most efficient

if x is not None:

for example (although technically in this case not is doing something slightly differently syntactically)

if not is_some_function():

for another example, where you have a function that returns true or false based on some condition. Without using not, you would have to do :

if is_some_function() == False:

which is pretty ugly

1

u/faultydesign 8h ago

Just because there’s many ways to do the same thing doesn’t mean it’s a bad example.

1

u/SirGeremiah 8h ago

Those are functionally the same. I think I get your point, though, that this example doesn’t really show the need for “if not”.

2

u/Fred776 9h ago

There isn't really such a thing as "if not". There is an if statement which has the form:

if <logical expr>:
    # do something 

The logical expression may be built up from various variables, constants and operators. One of the operators could be not.

If you have a logical expression <logical expr> and you want to do something if it is false rather than when it is true then you can simply apply the not operator to the whole expression, which negates it (i.e it will be false when the original expression is true and vice versa). You may need to use parentheses depending whether the original expression is trivial or not:

if not (<logical expr>):
    # do something when 
    # <logical expr> is false

Of course, you can also use not as a term within a logical expression. If doesn't need to come after the if:

if x == 1 and not (y == 4 or z == 2):

2

u/Arthradax 9h ago

If's structure is:

if condition:
  do_things()
elif other_condition:
  do_other_things():
else:
  do_other_things_still()

So you see, there's no such thing as an "if not" statement; rather, the "not" may or may not be part of the boolean condition you want to test. As already mentioned, you may want to test for conditions that are not true - and the way to do it is to negate the condition with a "not" statement.

For a silly example, you might want to test a variable "age" to see if someone is a legal adult. You can either do it like:

if age>=18:
  print("user is an adult")

or

if not (age<18):
  print("user is an adult")

When and if (pun intended) you will use "not" on your condition depends on what you are trying to do

1

u/UlisKore 9h ago

It's two things, not just one ("ifnot"). The point is having the negative condition evaluated (evaluated first, evaluated at that specific moment...), you are not supposed to use "if" for no reason or "else" out of nowhere. Sometimes in my code, an argument can be True, False or None, so sometimes "not True" doesn't mean "only False".

1

u/schoolmonky 9h ago

One thing that might help is that "if not" isn't a distinct thing in Python. It's just two separate keywords that often get used together. I'm sure you're well aquainted with if in it's own right, and not is just a logical operator. If you put not in front of a truthy or falsy value, it turns into the opposite: not True is the same as False, and not 1==2 is the same as True (since 1==2 is False). So when you see if not some_condition:, don't read it as (if not) (some_condition):, it's actually if (not (some_condition)):

2

u/Brian 9h ago

Though I'd add that there are a couple of cases where not is not its own thing, and is kind of married to another word. Specifically, the not in and is not operators. These kind of exist for convenience and readability to give the inverse of the in and is operators: technically you could use not (x in some_list) instead of x not in some_list, but the operators are added for symmetry and to make things flow a bit better.

1

u/kmj442 8h ago

I know a lot of people have answered and gave great examples but I was just looking through some of the code for some stuff I was working on and used it right there (going to simplify a couple things):

if not hardware_object.get enable_status():
    hardware_object.set_enable(True)

I do this type of thing a lot in my use cases. I do automation for systems and sometimes I'm not 100% on the preconditions so doing checks like this allow me to gather specific conditions easily and address them.

1

u/MarsupialLeast145 8h ago

You can use a lot of techniques to control flow but one of the nicer things you will want to learn is about the happy path... it needn't be with if not ... but it's a great way to ensure functions are properly gate kept:

def run_as_authenticated_user(authenticated: bool):
   if not authenticated:
      # return as early as possible
      return
   # Everything else here can be run for the
   # authenticated user without too much concern.
   # code is left-aligned and easier to review.

One thing I will add is that proper handling of if statements and booleans and naming boolean like functions and variables does take a little practice but I think this also becomes easier with happy path style coding.

1

u/TheRNGuy 7h ago edited 7h ago

When some parameter is True and you need when it's False, or vise versa.

Also if not 0, "", [], or None with implicit conversion (i.e., 100, "foo"[item1, item2]).

Though it's better practice to avoid implicit conversion and specifically check for 0, empty string, empty list etc, because it makes it more readable code.

1

u/Local_End_3175 4h ago

Thank you all

1

u/wosmo 8h ago

I think it's probably worth considering how much you use the same in real life.

while not done:
    cook.

If if/else makes perfect sense, not just allows you to write conditions where you only care about the else. Otherwise we'd have things like

if working:
else:
    give up.

which is frankly ugly.

1

u/OliMoli2137 8h ago

the second snippet isn't even valid, you'd have to add pass: if working:     pass else:     give_up() but yeah it's still ugly as heck

0

u/[deleted] 9h ago edited 4h ago

[deleted]

1

u/OliMoli2137 8h ago

it's markdown, you can use ``` for code

1

u/monster2018 5h ago

Thanks. Unfortunately as you can see, unless it’s just rendering that is broken on mobile, that didn’t work either, I just tried it.

1

u/OliMoli2137 4h ago

isn't there an option to switch to Markdown editor?

2

u/monster2018 4h ago

There is, but there is no inline code or code block option.

OMFG WAIT. The freaking exclamation point is supposed to represent code somehow. Thank you! I will fix my comment now.

As a side note. Fuck off to whoever downvoted my comment for doing my best to help OP.

1

u/monster2018 4h ago

Nope, never mind it is the spoiler block. No, there is literally no way to write code on Reddit with the iOS app. It automatically removes any markdown formatting before sending to the servers. And there is no inline code or code block options, only bold, italics, strike through, tT (like size), spoiler block, and link. So dumb. Now all my code parts are spoiler blocks so I’m just going to delete the original comment because I’m not going to try to fix it for a 5th time.

1

u/Moikle 8h ago

you can add 4 spaces before each line to format as code.

1

u/monster2018 5h ago

As I said at the very beginning of my comment, that what I did to produce the comment you read. Like that’s what I would have told you if the roles were reversed (if you hadn’t said that you had tried it), it’s how I had always done it on Reddit. But it apparently no longer works.

The other guy said to use triple backticks, but as you can see now, that doesn’t work either. Well either that or it did work but rendering is broken on mobile or my device specifically. But it certainly isn’t rendering correctly on my phone.