DEV Community

sonozig
sonozig

Posted on

All you need to know about IF statements

You may be thinking: I already know how to use IF statements in Python.
Yes, you do.
So, why am I writing this?
Well, if you have just started learning Python, or if you have never used it before, here are some tips that may help you:

If you want to test if a variable is True or False, you can just do this:

variable1 = True
variable2 = False

if variable1:
   print("The first variable is True")

if not variable2:
   print("The second variable is False")
Enter fullscreen mode Exit fullscreen mode

You can do the same thing to test if there is a value assigned to the variable:

variable1 = "Some text"
variable2 = 1
variable3 = ""

if variable1:
   print("The first variable has a value assigned to it")

if variable2:
   print("The second variable has a value assigned to it")

if not variable3:
   print("The third variable has not a value assigned to it")
Enter fullscreen mode Exit fullscreen mode

To check if a value is inside a list, use this:

numbers = ["one", "two", "three", "four", "five"]

if "four" in numbers:
   print("The number four is in the list")
Enter fullscreen mode Exit fullscreen mode

Remember: "one" is numbers[0], not numbers[1]. This last one is "two".

Atention: to check if a value is equal to another, you can't use the examples above. Use x == y.

Top comments (0)