Stage 1 of 4, lesson 3 of 31. No coding experience needed
If statements and comparisons: let the program decide
Ask a question in code and do different things depending on the answer. It introduces comparisons, if, elif and else, and the words and, or and not.
Risk warning: CFDs and spread bets are complex instruments and come with a high risk of losing money rapidly due to leverage. You can lose money on these products, and each provider publishes its own loss figure under FCA rules. You should consider whether you understand how they work and whether you can afford to take the high risk of losing your money. Automated and API trading can amplify losses through bugs, connectivity failures and runaway orders.
You need: The lesson on variables and types. No broker account.
A comparison is a question with a yes or no answer: is this price above that level? Python answers True or False, and an if statement runs a block of code only when the answer is True.
With if, elif and else the tests are tried from the top and only the first one that is true runs. The order you write them in is part of the logic, so read the chain in the script as a list of questions asked one after another.
The price and the levels in the script are invented, and the tests are there to show the syntax. They are not rules for trading. The last two lines show a trap worth meeting early: two decimal numbers that should be equal often are not, quite.
The code
# If statements and comparisons: let the program choose what to do.
# No broker, no account, no internet. The price and the levels are invented, and the tests
# below are examples of syntax, not rules to trade by.
price = 104.3
stop_level = 101.0
limit_level = 108.0
direction = "BUY"
market_open = True
# A comparison is a question whose answer is True or False.
print("price > stop_level:", price > stop_level)
print("price == limit_level:", price == limit_level)
print("direction != 'SELL':", direction != "SELL")
# if, elif and else: the first branch whose test is True runs, and the rest are skipped.
if price <= stop_level:
state = "at or below the stop"
elif price >= limit_level:
state = "at or above the limit"
else:
state = "between the stop and the limit"
print("The price is", state)
# and, or and not join tests together.
if market_open and direction == "BUY":
print("The market is open and the direction is BUY")
if price < stop_level or price > limit_level:
print("Outside the range")
else:
print("Inside the range")
if not market_open:
print("The market is closed")
# A chained comparison reads like the maths.
print("stop_level < price < limit_level:", stop_level < price < limit_level)
# Do not test floats with ==. Arithmetic on floats is very slightly inexact.
total = 0.1 + 0.2
print("0.1 + 0.2 == 0.3:", total == 0.3)
print("Close enough to 0.3:", abs(total - 0.3) < 0.000001)What you should see
price > stop_level: True price == limit_level: False direction != 'SELL': True The price is between the stop and the limit The market is open and the direction is BUY Inside the range stop_level < price < limit_level: True 0.1 + 0.2 == 0.3: False Close enough to 0.3: True
Run with Python 3.12 on Windows. No network and no account.
Check yourself
Answer each question from the code above before you open it. The answers were written from the script on this page and what it printed.
If price were exactly 101.0, which branch of the if, elif, else chain would run?
The first. The test is price <= stop_level, and <= is true when the two are equal. The script would print that the price is at or below the stop.
Why does the chain use elif for the second test instead of a second if?
With elif the second test is only tried when the first was false, so exactly one branch runs. Two separate if statements are two separate questions, and both could run.
Why does 0.1 + 0.2 == 0.3 print False, and what does the script do instead?
Decimal fractions are stored very slightly inexactly, so the sum is not exactly 0.3. The script checks that the difference is tiny, with abs(total - 0.3) < 0.000001.
Exercise
Change price to 108.0, the same as the limit level. Predict which lines of output change, then run it.
What the changed script prints
price > stop_level: True price == limit_level: True direction != 'SELL': True The price is at or above the limit The market is open and the direction is BUY Inside the range stop_level < price < limit_level: False 0.1 + 0.2 == 0.3: False Close enough to 0.3: True
Captured from a run of the solution on . Run with Python 3.12 on Windows. No network and no account.
One solution
# Exercise solution: the lesson script with the one change the exercise asks for.
# If statements and comparisons: let the program choose what to do.
# No broker, no account, no internet. The price and the levels are invented, and the tests
# below are examples of syntax, not rules to trade by.
price = 108.0
stop_level = 101.0
limit_level = 108.0
direction = "BUY"
market_open = True
# A comparison is a question whose answer is True or False.
print("price > stop_level:", price > stop_level)
print("price == limit_level:", price == limit_level)
print("direction != 'SELL':", direction != "SELL")
# if, elif and else: the first branch whose test is True runs, and the rest are skipped.
if price <= stop_level:
state = "at or below the stop"
elif price >= limit_level:
state = "at or above the limit"
else:
state = "between the stop and the limit"
print("The price is", state)
# and, or and not join tests together.
if market_open and direction == "BUY":
print("The market is open and the direction is BUY")
if price < stop_level or price > limit_level:
print("Outside the range")
else:
print("Inside the range")
if not market_open:
print("The market is closed")
# A chained comparison reads like the maths.
print("stop_level < price < limit_level:", stop_level < price < limit_level)
# Do not test floats with ==. Arithmetic on floats is very slightly inexact.
total = 0.1 + 0.2
print("0.1 + 0.2 == 0.3:", total == 0.3)
print("Close enough to 0.3:", abs(total - 0.3) < 0.000001)Your progress
Your marks are kept in this browser only, in its local storage. They are not sent anywhere, there is no account, and they will not follow you to another browser or device. To remove them, use Clear my progress on the learning track page, or clear this site's data in your browser's settings. Marking needs JavaScript. With scripts off the track reads the same, without the ticks.
This browser refused to store anything for this page, so marks cannot be kept here.
Where this sits in the path
Stage 1 of 4: First steps. Values, decisions, loops and functions, and the habit of testing what you wrote. No files and no account.
- First Python scriptDone
- Variables and typesDone
- If and comparisonsDoneYou are here
- Lists and loopsDone
- Functions and sizingDone
- Test your functionsDone