condition = {"a": True, "b": True}
if condition["a"]:
print("a is True")
elif not condition["b"]:
print("b is False")
else:
print("neither a nor b is True")
a is True
Python Control Flow
Operator | Description |
---|---|
== |
Equal to |
!= |
Not equal to |
> |
Greater than |
< |
Less than |
>= |
Greater than or equal to |
<= |
Less than or equal to |
Operator | Description |
---|---|
== | Equal to |
!= | Not equal to |
> | Greater than |
< | Less than |
>= | Greater than or equal to |
<= | Less than or equal to |
if
statements are used to make decisions in code.True
, the code block is executed.False
, the code block is skipped.False
[]
, tuple ()
, set set()
, string ""
, or dictionary {}
0
, 0.0
, or complex 3j
False
(obviously), or None
a is falsy
b is truthy
d equals 0
so d evaluates to: False
True
.False
, the second operand is not evaluated.x = True
y = False
z = True
if x and y:
print("This will not print because both x and y are not true")
else:
print("box x and y are not true")
if x and z:
print("But both x and z evaluate to true, so you see me")
elif z and x:
print("This will not print because the first if is true")
else:
print("box x and y are not true")
if x and z:
print("But both x and z evaluate to true, so you see me")
else:
print("You will not see this, because x and z evaluate to true")
box x and y are not true
But both x and z evaluate to true, so you see me
But both x and z evaluate to true, so you see me
or
operator evaluates to True
if either of the operands is True
.x = True
y = False
z = True
a = 1
b = 0
if x or y:
print("This first if will print because x is true")
else:
print("box x and y are not true")
if a or b == 0:
print("This will print because b == 0 is true")
else:
print("You will not see this, because b is true")
This first if will print because x is true
This will print because b == 0 is true
not
operator negates the boolean value of the operand.x = 10
y = 20
z = 10
a = "Something"
b = True
if not x == y:
print("x is not equal to y")
else:
print("x is equal to y") # this will not print
if type(a) != int:
print("a is not an integer")
else:
print("a is an integer") # this will not print
print(not b)
x is not equal to y
a is not an integer
False
in
operator checks if a value is in a sequence.
if
statements inside other if
statements.my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
if 3 in my_list:
if 3 in my_list[:5]:
if 3 in my_list[:3]:
print("3 is in the first quarter of the list")
else:
print("3 is in the first 3 of the list")
else:
print("3 is in the second half of the list")
else:
print("3 is not in the list")
3 is in the first quarter of the list