if Examples
This page was last reviewed on Apr 26, 2024.
Dot Net Perls
If, else. 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.
Example if. 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.
Info Else must come at the end. Else has no expression to evaluate—it is executed when if and elif evaluate to false.
Tip Blocks of code within if, 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
In keyword. 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")
Assignment. 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)
Same line. 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")
And, or. 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.
Note These if-statements have expressions that use "and" or "or." They all evaluate to true, and the inner print statements are reached.
Tip Expressions can be even more complex. And you can call methods and use them instead of variables.
Tip 2 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
Not keyword. 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.
Warning For the first example of "not" here, I recommend instead using the != operator. This style is more familiar to many programmers.
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
Store expressions. If-statements can become complex. Often repetition is at fault. The same variables, in the same expressions, are tested many times.
Result We can store the result of an expression in a variable. Then, we test the variable.
Tip This reduces repetition. It may also improve processing speed: fewer comparisons are done.
Here We store the result of an expression in the "all" variable. We then test it twice.
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
Truth. 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... []
True, 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
Method. 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.
Warning For predicate methods, where a truth value is returned, side effects (like a field assignment) can lead to confusing code.
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")
Is-keyword. 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
Reorder. 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.
Here A list contains four sub-lists. In the value pairs, the first element differs most: there are three unique first numbers.
Detail This is always 1 in the pairs. It is least specific when checking the pairs.
So To find pairs with both values set to 1, we should first check the most specific value—the first one.
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
Two comparisons. 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.
Also The "greater than or equal to" operator (and less than or equal to) are available here.
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
A benchmark. 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.
Version 1 We test an if that checks a variable against a tuple of 3 values. Only one if-statement is needed.
Version 2 We then time an if-elif construct that does the same thing. Multiple lines of Python code are required here.
Result The syntax that uses (1, 2, 3) was faster than the form that uses if and two elifs. The tuple-style syntax is efficient.
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
A summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Apr 26, 2024 (edit link).
© 2007-2024 Sam Allen.