Logical conditions

We use if-statements to decide what path a program can take. That lets the computer make decisions, and we end up with more useful and helpful applications.

We'll continue on that theme here and talk more about the conditions that make up if statements.

If and else

Look att the following example:

age = int(input("How old are you? "))
if age >= 18:
    print("Hello, you are an adult!")

If you enter 20, the computer tells you that you are an adult, because the condition "age >= 18" is true. But if you enter 10, the program says nothing, because the print instruction will not be executed.

We can use the keyword else to express what should happen if the condition is false.

Compound conditions

The conditions used in our if-statement can be combined together using the and, or and not keywords.

For example, I want to buy a new computer if the screen is larger than 14 inches and smaller than 17 inches. If we have several options, and at least one of them needs to be true, we can use or:

screensize = 15
if screensize == 14 or screensize == 15 or screensize == 16:

Each condition must be complete. We can't simply write:

"if screensize == 14 or 15 or 16:"

Even if that's how we humans say it. In Python, we must write the complete condition as in the first example.

If we have several options and all of them need to be true, we can use "and". Let us say we want to buy a computer with at least a 14 inch screen and 8 GB of memory.:

screensize = 15
ram = 12
if screensize > 14 and ram >= 8:


The last important keyword is not.

if not (ram < 8):
    print("Enough memory")

This is equivalent to writing:

if ram >= 8:
    print("Enouph memory")

Notice that it's >= now. Why? (What happens if the variable ram is exactly 8?)

All of this is the field of logic!

Read page in other languages

In this video, we use multiple inputs and combine the responses in a more complex if-statements, all in order to greet the users in the way they desire.

  • If statement: The keyword "if" followed by a logic condition allows our program to make decisions.
  • Logical condition: A comparison between two values. For example:

age > 18 or name == "Marcus".