With an if
-statement, we test a condition. We make a decision. With keywords (and, not, or) we modify the expressions within an if.
In Python the important thing to remember is that indentation is important. The whitespace is part of the language. If
-statements should be indented in a consistent way.
With "if," we start a chain of statements. Each condition is evaluated to a boolean. An if
-statement can be followed by an elif
-statement and an else
-statement.
elif
evaluate to false.elif
and else scopes must have an additional level of indentation. This program uses 4 spaces.def test(n): # Return a number based on the argument. if n == 0: return 1 elif n <= 10: return 2 elif n <= 50: return 3 else: return 4 # Call the method 3 times. print(test(-1)) print(test(0)) print(test(1000))2 1 4
When dealing with strings, dictionaries and lists, we can use the if
-statement with "in." Here we test for an element's existence in a string
, and then in a dictionary.
# Test for substring in string. letters = "abc" if "c" in letters: print("FOUND 1") # Test for key in dictionary. birds = {"parakeet": 1, "parrot": 2} if "parrot" in birds: print("FOUND 2")FOUND 1 FOUND 2
We can use a special operator to assign a variable within the expression of an if
-statement. This is commonly called the "walrus operator" for its syntax.
def get_id(index): if index == 1: return 25 return 0 # Set id to the result of get_id. # The expression evaluates to true if get_id does not return 0. # Id will have the value returned by get_id. if (id := get_id(1)) != 0: print(id)25
An if
-statement can be on the same line as its body. This only works if there is one only statement in the body. A syntax error occurs otherwise.
# A variable. a = 1 # Test variable. if a == 1: print("1") elif a == 2: print("2")1
In Python we use instead the "and" and "or" keywords to specify conditional logic. This syntax is easier to read. We can use parentheses to form expressions.
if
-statements have expressions that use "and" or "or." They all evaluate to true, and the inner print statements are reached.If
-statements can also be nested. And sometimes it is possible to change complex expressions into a simpler if-else
chain.a = 1 b = 2 if a == 1 and b == 2: print(True) if a == 0 or b == 2: print(True) if not (a == 1 and b == 3): print(True) if a != 0 and b != 3: print(True)True True True True
This is used in ifs. It causes false expressions to evaluate to true ones. It comes before some expressions, but for "in" expressions, we use the "not in" construct.
number = 1 # See if number is not equal to 2. if not number == 2: print("True") birds = {"cormorant" : 1, "cardinal" : 2} # See if string not in collection. if "automobile" not in birds: print("Not found")True Not found
If
-statements can become complex. Often repetition is at fault. The same variables, in the same expressions, are tested many times.
a = 1 b = 2 c = 3 # Store result in expression. all = a == 1 and b == 2 and c == 3 # Test variable. if all: print(1) # Use it again. if all: print(2)1 2
Tuple
The if
-statement is helpful with a tuple. In this example, we use a tuple directly inside the if
-statement. The method test()
prints "Match
" if its argument is 0, 2 or 4.
def test(x): # Test x with tuple syntax. if x in (0, 2, 4): print("Match") else: print("Nope") test(0) test(1) test(2)Match x = 0 Nope x = 1 Match x = 2
Let us consider the truth of things. Python considers some values True, in an if
-statement, and others false. The "None
" value is False, and a class
instance is True.
# An empty class for testing. class Box: pass # Some values to test. values = [-1, 0, 1, None, Box(), []] # See if the values are treated as "true" or "false". for value in values: if value: print("True ", end="") else: print("False", end="") # Display value. print("... ", value)True ... -1 False... 0 True ... 1 False... None True ... <__main__.Box object at 0x01984f50> False... []
Programs can always access the True and False constants. We can use True and False in ifs to make our logic clearer. This code makes explicit what value we are comparing.
value1 = 10 value2 = 10 # See if these two values are equal. equal = value1 == value2 # Test True and False constants. if equal == True: print(1) if equal != False: print(2)1 2
Often we test variables directly in if
-statements. But we can test the result of methods. This can simplify complex logic. Here, we invoke result()
in if
-statements.
def result(a): if a == 10: return True # Use method in an if-statement condition. if result(10): print("A") if not result(5): print("B")A B
This tests identity. Every object (like integers, classes) has an id. When the ids of two objects are equal, their identities too are equal. And the is
-test will return True.
class Bird: pass # Create two separate objects. owl = Bird() parrot = Bird() # The objects are not identical. if owl is not parrot: print(False, id(owl), id(parrot)) # These objects are identical. copy = owl if copy is owl: print(True, id(copy), id(owl))False 4353337736 4353337792 True 4353337736 4353337736
SyntaxError
When comparing two values in an if
-statement, two equals signs are required. Python reports a compile-time error when only one is found. One equals sign means an assignment.
value = 100 # This should have two equals signs! if value = 1000: print(True) File "C:\programs\file.py", line 6 if value = 1000: ^ SyntaxError: invalid syntax
The and-operator short
-circuits. This means when a sub-expression evaluates to false, no further ones are evaluated. We can exploit this principle to improve speed.
values = [[1, 1], [2, 1], [1, 1], [3, 1]] for pair in values: # We test the first part of each list first. # ... It is most specific. # ... This reduces total checks. if pair[0] == 1 and pair[1] == 1: print(True)True True
We can use two greater-than or less-than operators in a single expression. So we can see if a number is between 6 and 4.
value = 5 # Use two comparison operators to test for a range of values. if 6 > value > 4: print("Value is between 6 and 4") if 4 < value < 10: print("Value is between 4 and 10")Value is between 6 and 4 Value is between 4 and 10
If
-statements can be written in many ways. A tuple can be used inside of an if
-statement condition to replace (and optimize) a group of if-else
branches.
if
-statement is needed.if
-elif
construct that does the same thing. Multiple lines of Python code are required here.import time print(time.time()) # Version 1: use tuple. v = 0 i = 0 x = 2 while i < 10000000: if x in (1, 2, 3): v += 1 i += 1 print(time.time()) # Version 2: use if-elif. v = 0 i = 0 while i < 10000000: if x == 1: v += 1 elif x == 2: v += 1 elif x == 3: v += 1 i += 1 print(time.time())1361579543.768 1361579547.067 Tuple syntax = 3.23 s 1361579550.634 If-elif = 3.57 s
If
-statements are used in nearly every Python program. The else
-statement can also be used with loop constructs—if a loop never iterates once, the else is reached.