Click to share! ⬇️

Computers work based on absolutes. There’s only yes or no, true or false, and one or zero. Any expression that breaks down to either true or false is called a Conditional or Boolean expression. Is 7 greater than 5? Yes, that would evaluate to True. However, is 2 greater than 5? No, then the result will be False. And finally, here’s an example that doesn’t involve numbers. Do I like shellfish? No, I would rather have Mexican food. This would evaluate as False as well. These are Boolean expressions.

The Python interpreter command line is a great way to test simple boolean expressions. Here are several examples.

>>> 'This string' == 'That string'
>>> 'wiggle' == 'wiggle'
>>> 'willle' == 'waggle'
>>> 2 > 3
>>> 2 == 2
>>> 3 >= 4
>>> 4 >= 4
>>> 5 < 10
>>> 7 <= 7

As we’ve learned, computers don’t speak human language. We can’t just ask questions directly to the computer. This is where relational operators come into play. We’ve already worked with several operators. We’ve used arithmetic operators, like the plus + for addition or the percent sign % for modulo. We’ve also used the equal sign = for assignments. Recall that the single equals sign = is used to assign a value, while the double equals sign == is used to check for equality. Relational operators work with two operands and return a True or False value based on their relation to each, thus the name. The first relational operator we’ll look at is the equality operator. A double equal sign represents it, and it’s used to evaluate the equality of the operands.

# == operator testing

subject = "Python"

if subject == "Python":
    print("You are learning Python")
    print("You are not learning Python")

# You are learning Python

The left side of the operator equals the right side of the operator. Here’s another example. We have a variable called grass. And we’ve set it to equal to the string “Green.” We can test if the grass is green. If the variable grass equals the string “Green”, the program prints out “No fertilizer needed.” However, if the variable grass does not equal “Green,” the program takes a different action.

# == operator testing

grass = 'Green'

if grass == 'Green':
    print('No fertilizer needed')
    print('Fertize the grass')

So be on the lookout for that potential bug if your program isn’t doing what you expect. What If we wanted to check for something that is not the same? Then we would use the not equal sign !=.

grass = 'Green'

if grass != 'Green':
    print('No fertilizer needed')
    print('Fertize the grass')

# Fertize the grass

== Equal to

# == equal to example programs
'black' == 'black' # True
'black' == 'white' # False
[] == [] # True
[] == [1] # False
True == True # True
True == False # False
100 == 100 # True

!= Not equal to

77 != 77 # False
'Boston' != 'New York' # True
'New York' != 'New York' # False
True != False # True
[1, 2, 3] != [1, 2, 3] # False
[1, 2, 3] != [1, 2, 4] # True
{'a': 1, 'b': 2} != {'a': 1, 'b': 2} # False

< Less than

# < less than example programs
1 < 2  # True
1 < 1  # False
'blue' < 'red'  # True
'blue' < 'blue'  # False
[1, 2, 3] < [1, 2, 4]  # True
[1, 2, 3] < [1, 2, 3]  # False
{'a': 1, 'b': 2} < {'a': 1, 'b': 3}  # True
{'a': 1, 'b': 2} < {'a': 1, 'b': 2}  # False

> Greater Than

# > greater than examples
1000 > 100  # True
1000 > 1000  # False
'Boston' > 'Boston'  # False
'Boston' > 'boston'  # True
['small', 'little'] > ['extra large']  # True
[] > []  # False
{'lemon': 3, 'apple': 2} > {'lemon': 1, 'apple': 2}  # True

<= Less than or Equal to

# <= less than or equal to examples
'macbook' <= 'macbook pro'  # True
'macbook' <= 'imac'  # False
10 <= 10  # True
10 <= 9  # False
[1, 2, 3] <= [1, 2, 3]  # True
[1, 2, 3] <= [1, 2]  # False
{'tone': 'high'} <= {'tone': 'low'}  # False
{'tone': 'high'} <= {'tone': 'high'}  # True

>= Greater than or Equal to

# >= greater than or equal to examples
'Macbook' >= 'macbook'  # True
'Macbook' >= 'Macbook'  # True
'Macbook' >= 'Macbook Pro'  # False
712 >= 712  # True
1234 >= 123  # True
['one', 'two'] >= ['one', 'two']  # True
['one', 'two'] >= ['one', 'three']  # False
{'color': 'red'} >= {'color': 'blue'}  # False

Exploring conditional code

In the real world, we make decisions based on current conditions all of the time. If it’s snowing, I’ll take my winter coat. If I’m tired, I’ll grab a cup of coffee. The most common way for a computer to make decisions is by using an if statement. An if statement has this general structure.

It starts with the word if; that’s where it gets its name from, then it checks some condition, and if that condition is True, it will do the work you’ve placed inside of it. To visualize this, think of it as a flow chart with only one check. If it’s true, the program will execute the statements. If not, it ignores those statements as if they don’t exist.

Selection statements, also known as Decision-making statements, control the flow of a program based on the outcome of one or many test expression(s). If the condition is satisfied (True), then the code block is executed. There is also a provision to execute another code block if the condition is not satisfied.

Here’s a simple if statement in Python. It starts with the word if, then we have our condition, or boolean expression, seven less than 9. Next, we have a colon :. This is part of the syntax, or rules, of the Python if statement. And on the next line, we have an indented line of code. This contains a print statement that will run if our condition is True.

if 7 < 9:
    print("7 is less than 9")

The indentation in Python is significant because that’s how the interpreter knows which statements belong to the if. We have a name for statements grouped this way in programming. It’s called a block. In this example, there’s only one statement in our block, but we could easily extend it like this.

if 7 < 9:
    print("7 is less than 9")
    print("Another line in the block")

And now we have two statements in our block. In Python, the block is ended as soon as we come to a line that’s not indented anymore.

if 7 < 9:
    print("7 is less than 9")
    print("Another line in the block")
print("This line is not in the block")

This new print statement isn’t indented. It’s not part of the previous if statement’s block. Python requires indentation so that it knows what code belongs to the if. It’s standard in Python to use four spaces for doing some indenting. If statements allow a program to take different paths while it’s running.

Working with simple conditions

With if statements, we’ve discovered a way to add a bit more flexibility and excitement to our programs, but if the condition is false, then we don’t do anything. But typically, we’ll also want to take action in this case. This is done with the if-else statement. It looks very similar to our normal if statement, except that it has the else keyword along with a colon :, followed by a code block. In programming, this is called the else clause, because you never find it without an accompanying if statement. Just like in English, if I said, every night before I go to bed, and that’s it, that would be an incomplete thought. It’s just a clause. I’d have to add something like every night before I go to bed, I enjoy watching some Netflix. Now the thought is complete. Similarly, we don’t use the else clause without an if statement. Let’s look at an example.

a = input('Enter a number: ')
b = input('Enter another number: ')

if a > b:
    print(f'{a} is greater than {b}')
    print(f'{b} is greater than {a}')

This friendly little program takes two numbers from a user and then uses an if-else clause to determine what to print. Let’s imagine we run this program, and when it asks for the first number, we provide the number 5. When the second number is requested, we enter 7. The if statement will check if five is greater than 7. This is False, so the program skips ahead to the else clause and prints seven is greater than 5. Here is some example output from running the program a few times.

Enter a number: 100
Enter another number: 5000
5000 is greater than 100

Enter a number: 8000
Enter another number: 3
8000 is greater than 3

With if-else statements, we will always execute one of the code blocks depending on the condition test result. This makes it perfect for when we need some action to take place in our programs.

Python if elif else Statement

The elif is short for else-if. It allows us to check for multiple expressions in a program. If the condition for if is False, it checks the condition of the next elif block and so on. If all the conditions are False, the body of else is executed. Only one block among the many if…elif…else blocks is performed according to the condition. The following is an example of the if…elif…else statement.

# if elif else

num = 10

if num > 10:
    print('Greater than 10')
elif num < 10:
    print('Less than 10')
    print('Equal to 10')

It is possible to have Python Nested if statements. We can have an if…elif…else statement inside another if…elif…else statement. This is known as nesting in computer programming. Any number of these statements can be nested inside one another. Indentation is the only way to figure out the level of nesting. Nested if statements can get confusing, so it is best to avoid nesting unless needed.

# nested if elif else

num = 27

if num > 0:
    if num % 2 == 0:
        print("Positive and even")
        print("Positive and odd")

# Positive and odd

Conditionals In Other Languages

By now, you’re pretty familiar with conditionals in Python. We start with an if, followed by our condition, then we end the condition with a colon. Then on the following line, we indent the block of code that we want to be executed. And the else is very similar, except there’s no condition to check. The if else statement in the Java programming language has a slightly different syntax. Remember, the syntax is just the same thing as saying rules for how a programming language expects its code to be written. After the if keyword, there’s a set of opening and closing parentheses. Inside these parentheses is where you put the condition you want to be tested. And instead of a colon after the condition, a pair of opening and closing curly braces are used to denote the code block for the if. The same thing is true for the else clause.

if (100 > 50) {
  System.out.println("100 is greater than 50");

Although it’s typical to indent the statements in the code blocks, it’s not a requirement the way it is for Python. Let’s look at one final example with the Ruby programming language. Ruby is known for its ease of use and flexibility. But just like the other languages, the structure of the if-else statement is the same, but the syntax differs. With Ruby, there are no parentheses or a colon to separate the condition. Even the else clause stands on a line all alone. The addition of the end keyword is the one thing that’s more noticeably different. This is how Ruby notes that it’s done with this if else statement. Not based on indentation or a curly brace like Python and Java. The cool thing about learning the basics of programming is that once you grasp the core statements and principles structure, you can more readily recognize them across all languages.


x = 1
if x > 2
   puts "x is greater than 2"
elsif x <= 2 and x!=0
   puts "x is 1"
   puts "I can't guess the number"
Click to share! ⬇️