7Conditionals and Control Flow

Python can make decisions when executing code based on the logic you add to a script. The logic you add determines what should happen if the code encounters a situation that is either true or false. In Python, the situation is called a condition. Your script can contain one or many conditions all with their own set of actions.

Comparison Operators

You may be familiar with comparing numbers in math using phrases such as “greater than,” “less than,” or even “less than or equal to.” Python shares the same comparators with a few additional ones for you to use when comparing numbers or strings. Comparison operators are used to compare two values. When using a comparison operator, Python will return a Boolean value of either True or False. The return value indicates whether a comparison is true or false. Python will always capitalize the Boolean value.

“Tabular chart for comparing numbers in math using phrases such as “greater than,” “less than,” or even “less than or equal to.” Python shares the same comparators to use when comparing numbers or strings.”

Comparators can also be used for more complex comparisons that involve math equations. Python completes the equation for both sides of the comparator before determining whether the Boolean value is True or False.

>>> 4 * 7> 98 / 2
False
>>> 5 + (6**2 + 3) <= 99 - (23 * 12/2)
False
>>> 12/2 == 3 * 2
True

Strings can also be compared to see whether each value is the same or different.

>>> favorite_flower = 'rose'
>>> flower = 'Rose'
>>> print(favorite_flower == flower)
False

In the previous example, although ...

Get Bite-Size Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.