Skip to main content

Python Selections: Conditions and Decisions

This article explores how Python uses Boolean logic, selection statements (if, if-else, elif), and random numbers to make decisions in programming. It covers Boolean types, values, expressions, relational and logical operators, operator precedence, conditional expressions, and debugging logic errors.

Save this reading to your study set

Sign up free

In programming, we often want our code to behave differently depending on the situation. Imagine a program calculating the area of a circle: if a user enters a negative radius, the calculation becomes mathematically invalid. To prevent such errors, we use selection control, which allows a program to choose specific actions based on whether certain conditions are met. This article explores how Python uses Boolean logic, selection statements, and random numbers to make these decisions.

Boolean Types, Values, and Expressions

At the heart of every decision is a Boolean expression. A Boolean expression is a mathematical or logical statement that evaluates to one of two values: True or False.

To create these expressions, Python uses six relational (comparison) operators:

  • == (equal to)
  • != (not equal to)
  • > (greater than)
  • < (less than)
  • >= (greater than or equal to)
  • <= (less than or equal to)

Caution: A common mistake is using a single equal sign (=) instead of a double equal sign (==) when comparing values. In Python, = is used for assignment, while == is used for comparison.

Python also allows you to convert between types. You can turn a Boolean into an integer using int(), where True becomes 1 and False becomes 0. Conversely, you can use bool() to convert numbers to Booleans; any numeric value that is not 0 will evaluate to True.

This diagram illustrates the mapping of boolean values (True and False) to integer values (1 and 0) in programming, along with a code snippet demonstrating this conversion.
This diagram illustrates the mapping of boolean values (True and False) to integer values (1 and 0) in programming, along with a code snippet demonstrating this conversion.

Generating Random Numbers

Sometimes, decisions should be based on chance rather than user input. Python's random module provides tools for this. To generate a random integer between two values aa and bb (including both endpoints), use random.randint(a, b). For example, random.randint(0, 9) produces a single-digit integer.

Keep reading for free.

Create an account to finish this reading and make it part of your study routine.

Continue reading free

Already have an account? Log in

Updated

Study it your way.

Import this reading into your study set to get started with another study mode.

Make it your own.

Keep this reading in a new study set, or add it to one you already use.