Python Conditionals

Python Conditionals expressions, involving keywords such as if, elif, and else, provide Python programs with the ability to perform different actions depending on a boolean condition: True or False. This section covers the use of Python conditionals, boolean logic, and ternary statements.

Python Conditionals Expression (or “The Ternary Operator”)

The ternary operator is used for inline conditional expressions. It is best used in simple, concise operations that are easily read.

The order of the arguments is different from many other languages (such as C, Ruby, Java, etc.), which may lead to bugs when people unfamiliar with Python’s “surprising” behaviour use it (they may reverse the order). Some find it “unwieldy”, since it goes contrary to the normal flow of thought (thinking of the condition first and then the effects).

n = 5
"Greater than 2" if n > 2 else "Smaller than or equal to 2"

Out: ‘Greater than 2’

The result of this expression will be as it is read in English – if the conditional expression is True, then it will evaluate to the expression on the left side, otherwise, the right side.

Ternary operations can also be nested, as here:

n = 5

“Hello” if n > 10 else “Goodbye” if n > 5 else “Good day”
They also provide a method of including conditionals in lambda functions.

Python Conditionals: if, elif, and else

In Python you can define a series of conditionals using if for the first one, elif for the rest, up until the final (optional) else for anything not caught by the other conditionals.

number = 5
if number > 2:
print("Number is bigger than 2.")
elif number < 2: # Optional clause (you can have multiple elifs)
print("Number is smaller than 2.")
else: # Optional clause (you can only have one else)
print("Number is 2.")

Outputs Number is bigger than 2

Using else if instead of elif will trigger a syntax error and is not allowed.

Python Conditionals: Truth Values

The following values are considered falsey, in that they evaluate to False when applied to a boolean operator.

  • None
  • False
  • 0, or any numerical value equivalent to zero, for example 0L, 0.0, 0j
  • Empty sequences: ”, “”, (), []
  • Empty mappings: {}
  • User-defined types where the bool or len methods return 0 or False
  • All other values in Python evaluate to True.

Note: A common mistake is to simply check for the Falseness of an operation which returns different Falsey values where the difference matters. For example, using if foo() rather than the more explicit if foo() is None

Python Conditionals: Boolean Logic Expressions

Boolean logic expressions, in addition to evaluating to True or False, return the value that was interpreted as True or False. It is Pythonic way to represent logic that might otherwise require an if-else test.

And operator

The and operator evaluates all expressions and returns the last expression if all expressions evaluate to True.

Otherwise it returns the first value that evaluates to False:

1 and 2
2
1 and 0
0
1 and "Hello World" "Hello World"
"" and "Pancakes"

“”

Or operator

The or operator evaluates the expressions left to right and returns the first value that evaluates to True or the last value (if none are True).

1 or 2
1
None or 1
1
0 or []
[]

Lazy evaluation

When you use this approach, remember that the evaluation is lazy. Expressions that are not required to be evaluated to determine the result are not evaluated. For example:

def print_me():
print('I am here!')
0 and print_me()
0

In the above example, print_me is never executed because Python can determine the entire expression is False when it encounters the 0 (False). Keep this in mind if print_me needs to execute to serve your program logic.

Testing for multiple conditions

A common mistake when checking for multiple conditions is to apply the logic incorrectly.

This example is trying to check if two variables are each greater than 2. The statement is evaluated as – if (a) and (b > 2). This produces an unexpected result because bool(a) evaluates as True when a is not zero.

a = 1
b = 6
if a and b > 2:
…print('yes')
… else:
…print('no')
yes

Each variable needs to be compared separately.

if a > 2 and b > 2:
…print('yes')
… else:
…print('no')
no

Another, similar, mistake is made when checking if a variable is one of multiple values. The statement in this example is evaluated as – if (a == 3) or (4) or (6). This produces an unexpected result because bool(4) and bool(6) each evaluate to True

a = 1
if a == 3 or 4 or 6:
…print('yes')
… else:
…print('no')
yes

Again each comparison must be made separately

if a == 3 or a == 4 or a == 6:
…print('yes')
… else:
…print('no')
no

Using the in operator is the canonical way to write this.

GoalKicker.com – Python® Notes for Professionals 80

if a in (3, 4, 6):
…print('yes')
… else:
…print('no')
no

Python Conditionals: Using the cmp function to get the comparison result of two objects

Python 2 includes a cmp function which allows you to determine if one object is less than, equal to, or greater than another object. This function can be used to pick a choice out of a list based on one of those three options.

Suppose you need to print ‘greater than’ if x > y, ‘less than’ if x < y and ‘equal’ if x == y.

['equal', 'greater than', 'less than', ][cmp(x,y)]
x,y = 1,1 output: 'equal'
x,y = 1,2 output: 'less than'
x,y = 2,1 output: 'greater than'

cmp(x,y) returns the following values

Comparison Result

x < y -1 x == y 0 x > y 1

This function is removed on Python 3. You can use the cmp_to_key(func) helper function located in functools in Python 3 to convert old comparison functions to key functions.

Section 14.6: Else statement

if condition:
body
else:
body

The else statement will execute it’s body only if preceding conditional statements all evaluate to False.

if True:
print "It is true!"
else:
print "This won't get printed.."

Output: It is true!

if False:
print "This won't get printed.."
else:
print "It is false!"

Output: It is false!

Section 14.7: Testing if an object is None and assigning it

You’ll often want to assign something to an object if it is None, indicating it has not been assigned. We’ll use aDate.

The simplest way to do this is to use the is None test.

if aDate is None:
aDate=datetime.date.today()

(Note that it is more Pythonic to say is None instead of == None.)

But this can be optimized slightly by exploiting the notion that not None will evaluate to True in a boolean expression. The following code is equivalent:

if not aDate:
aDate=datetime.date.today()

But there is a more Pythonic way. The following code is also equivalent:

aDate=aDate or datetime.date.today()

This does a Short Circuit evaluation. If aDate is initialized and is not None, then it gets assigned to itself with no net effect. If it is None, then the datetime.date.today() gets assigned to aDate.

Section 14.8: If statement

if condition:
body

The if statements checks the condition. If it evaluates to True, it executes the body of the if statement. If it evaluates to False, it skips the body.

if True:
print "It is true!"
It is true!
if False:
print "This won't get printed.."

The condition can be any valid expression:

if 2 + 2 == 4:
print "I know math!"

I know math!

Read more:

Must Read Python Interview Questions

200+ Python Tutorials With Coding Examples

Python Language Basics TutorialPython String Representations of Class Instances
Python For Beginners TutorialPython Debugging Tutorial
Python Data Types TutorialReading and Writing CSV File Using Python
Python Indentation TutorialWriting to CSV in Python from String/List
Python Comments and Documentation TutorialPython Dynamic Code Execution Tutorial
Python Date And Time TutorialPython Code Distributing using Pyinstaller
Python Date Formatting TutorialPython Data Visualization Tutorial
Python Enum TutorialPython Interpreter Tutorial
Python Set TutorialPython Args and Kwargs
Python Mathematical Operators TutorialPython Garbage Collection Tutorial
Python Bitwise Operators TutorialPython Pickle Data Serialisation
Python Bolean Operators TutorialPython Binary Data Tutorial
Python Operator Precedance TutorialPython Idioms Tutorial
Python Variable Scope And Binding TutorialPython Data Serialization Tutorial
Python Conditionals TutorialPython Multiprocessing Tutorial
Python Comparisons TutorialPython Multithreading Tutorial
Python Loops TutorialPython Processes and Threads
Python Arrays TutorialPython Concurrency Tutorial
Python Multidimensional Arrays TutorialPython Parallel Computation Tutorial
Python List TutorialPython Sockets Module Tutorial
Python List Comprehensions TutorialPython Websockets Tutorial
Python List Slicing TutorialSockets Encryption Decryption in Python
Python Grouby() TutorialPython Networking Tutorial
Python Linked Lists TutorialPython http Server Tutorial
Linked List Node TutorialPython Flask Tutorial
Python Filter TutorialIntroduction to Rabbitmq using Amqpstorm Python
Python Heapq TutorialPython Descriptor Tutorial
Python Tuple TutorialPython Tempflile Tutorial
Python Basic Input And Output TutorialInput Subset and Output External Data Files using Pandas in Python
Python Files And Folders I/O TutorialUnzipping Files in Python Tutorial
Python os.path TutorialWorking with Zip Archives in Python
Python Iterables And Iterators Tutorialgzip in Python Tutorial
Python Functions TutorialStack in Python Tutorial
Defining Functions With List Arguments In PythonWorking with Global Interpreter Lock (GIL)
Functional Programming In PythonPython Deployment Tutorial
Partial Functions In PythonPython Logging Tutorial
Decorators Function In PythonPython Server Sent Events Tutorial
Python Classes TutorialPython Web Server Gateway Interface (WSGI)
Python Metaclasses TutorialPython Alternatives to Switch Statement
Python String Formatting TutorialPython Packing and Unpacking Tutorial
Python String Methods TutorialAccessing Python Sourcecode and Bytecode
Using Loops Within Functions In PythonPython Mixins Tutorial
Python Importing Modules TutorialPython Attribute Access Tutorial
Difference Betweeb Module And Package In PythonPython Arcpy Tutorial
Python Math Module TutorialPython Abstract Base Class Tutorial
Python Complex Math TutorialPython Plugin and Extension Classes
Python Collections Module TutorialPython Immutable Datatypes Tutorial
Python Operator Module TutorialPython Incompatibilities Moving from Python 2 to Python 3
Python JSON Module TutorialPython 2to3 Tool Tutorial
Python Sqlite3 Module TutorialNon-Official Python implementations
Python os Module TutorialPython Abstract Syntax Tree
Python Locale Module TutorialPython Unicode and Bytes
Python Itertools Module TutorialPython Serial Communication (pyserial)
Python Asyncio Module TutorialNeo4j and Cypher using Py2Neo
Python Random Module TutorialBasic Curses with Python
Python Functools Module TutorialTemplates in Python
Python dis Module TutorialPython Pillow
Python Base64 Module TutorialPython CLI subcommands with precise help output
Python Queue Module TutorialPython Database Access
Python Deque Module TutorialConnecting Python to SQL Server
Python Webbrowser Module TutorialPython and Excel
Python tkinter TutorialPython Turtle Graphics
Python pyautogui Module TutorialPython Persistence
Python Indexing And Slicing TutorialPython Design Patterns
Python Plotting With Matplotlib TutorialPython hashlib
Python Graph Tool TutorialCreating a Windows Service Using Python
Python Generators TutorialMutable vs Immutable (and Hashable) in Python
Python Reduce TutorialPython configparser
Python Map Function TutorialPython Optical Character Recognition
Python Exponentiation TutorialPython Virtual Environments
Python Searching TutorialPython Virtual Environment – virtualenv
Sorting Minimum And Maximum In PythonPython Virtual environment with virtualenvwrapper
Python Print Function TutorialCreate virtual environment with virtualenvwrapper in windows
Python Regular Expressions Regex TutorialPython sys Tutorial
Copying Data In Python TutorialChemPy – Python package
Python Context Managers (“with” Statement) TutorialPython pygame
Python Name Special Variable TutorialPython pyglet
Checking Path Existence And Permissions In PythonWorking with Audio in Python
Creating Python Packages TutorialPython pyaudio
Usage of pip Module In Python TutorialPython shelve
Python PyPi Package Manager TutorialIoT Programming with Python and Raspberry PI
Parsing Command Line Arguments In Pythonkivy – Cross-platform Python Framework for NUI Development
Python Subprocess Library TutorialPandas Transform
Python setup.py TutorialPython vs. JavaScript
Python Recursion TutorialCall Python from C#
Python Type Hints TutorialPython Writing Extensions
Python Exceptions TutorialPython Lex-Yacc
Raise Custom Exceptions In PythonPython Unit Testing
Python Commonwealth Exceptions TutorialPython py.test
Python urllib TutorialPython Profiling
Web Scraping With Python TutorialPython Speed of Program
Python HTML Parsing TutorialPython Performance Optimization
Manipulating XML In PythonPython Security and Cryptography
Python Requests Post TutorialSecure Shell Connection in Python
Python Distribution TutorialPython Anti Patterns
Python Property Objects TutorialPython Common Pitfalls
Python Overloading TutorialPython Hidden Features
Python Polymorphism TutorialPython For Machine Learning
Python Method Overriding TutorialPython Interview Questions And Answers For Experienced
Python User Defined Methods TutorialPython Coding Interview Questions And Answers
Python Programming Tutorials With Examples

Other Python Tutorials

Leave a Comment