##### how do you do an if statement with python

how do you do an if statement with python

You are viewing a single comment. View All
RobertoBean (41)
``````condition = bool() #Can be anything like x > 0, bool(1), not x, x and y, etc.

if condition:
#runs when the condition is true
pass

else:
#runs when the condition is false
pass``````

To elaborate, let's try an example.

``````x = 2

if x > 1:
print("x is greater than 1!")
else:
print("x i s not greater than 1 D:")``````

That's not all you can do though.
Here's all the comparisons that you can do in example form:

``````x = 0

if x == 0:
print("x equals 0")
else:
print("x does not equal 0")``````
``````x = 0

if x >= 0:
print("x is greater than or equal to 0")
else:
print("x is less than 0")``````
``````x = 0

if x <= 0:
print("x is less than or equal to 0")
else:
print("x is greater than 0")``````
``````x = 0

if x != 0:
print("x is not equal to 0")
else:
print("x equals 0")``````

Those are at least all that I know, someone let me know if I missed any.

You also have modifiers you can put before and inbetween conditions, those are
`and`, `not`, and `or`

To show how to use these and what they do, here's an example:

``````x = 1
y = 2

if x == 1 and x != y:
print("x is equal to 1 and not equal to y")
else:
print("either x is equal to 1 or x does equal y")``````
``````x = 1
y = 2

if x == 1 or x != y:
print("either x is equal to 1, or x is not equal to y")
else:
print("x is not equal to 1 and x is equal to y")``````
``````x = 1
y = 2

if not x > y:
print("x is not greater than y")
else:
print("x is greater than y")``````

We also have one more thing we can do with `if-else`. We also have `if-elif-else` in python as well.

Python sees if the if statement is true, and if it is, executes it. Otherwise, it executes the elif statement, then if that's not true, it executes the else statement.

To make some more sense out of it,

``````if 0 == 1:
pass
else:
if 0 == 2:
pass
else:
pass``````

Is the same as;

``````if 0==1:
pass
elif 0==2:
pass
else:
pass``````

You can also have mutliple `elif`s following an `if`.

I hope this made some sense and helped you out!