Create your own
Lesson illustration

Variables and Basic Operators: Numbers, Strings, and Boolean Values

Good to see you again. In the previous lesson, you learned how a notebook separates Markdown explanation, executable code, and the output produced by that code. You also established an important habit: after changing a code cell, rerun it before trusting the output beneath it.

Now we make notebooks useful for calculations that persist across cells. You will create named Python values, update them as a calculation evolves, and combine them with arithmetic, comparison, and Boolean operators. These are the small building blocks behind every later research notebook: prices, dates, positions, costs, data-quality flags, and performance results all begin as values stored under meaningful names.


Variables: names for values

A variable is a name Python uses to keep track of a value. Think of it as a clearly labelled place in the current notebook session.

entry_price = 100.00

This statement has three parts:

PartMeaning
entry_priceThe variable name
=Assignment: store the value on the right under the name on the left
100.00The value being stored

After running the cell, you can use the name in another expression:

entry_price

The output is:

100.0

In a notebook, a value remains available after its cell runs, until you restart the Python session or assign a new value to the same name. This is convenient, but it also means execution order matters. If a later cell uses entry_price, run the cell that defines it first.

Assignment is not mathematical equality

In mathematics, is impossible. In Python, however, this is a normal update:

share_count = 3
share_count = share_count + 1

print(share_count)

The result is:

4

Python first evaluates the right-hand side using the old value, . It then replaces the old value stored under share_count with the new value, 4.

Use names that explain what a value means. Quantitative work benefits from names such as:

initial_cash = 1_000.00
transaction_cost = 1.25
daily_return = 0.004

rather than vague names such as x, a, or thing.

A good beginner convention is:

  • Start names with a letter.
  • Use lowercase letters.
  • Separate words with underscores: closing_price, data_is_complete.
  • Do not use spaces or hyphens.
  • Remember that capitalization matters: price and Price are different names.

Python variables for beginners ❎

Watch “Python variables for beginners” from Bro Code for a visual introduction to variables and the core value types you will use in this lesson.

Begin with the variable idea. Focus on why a descriptive label stands for the value assigned to it. Then skip ahead to the core types, covering integers, floats, strings, and Booleans. Pay particular attention to the fact that Boolean values use capital letters and do not have quotation marks.


Numbers, text, and Boolean values

Every Python value has a type. For this course, the most immediately useful types are int, float, str, and bool.

TypeRepresentsPython examplesQuantitative use
intA whole number3, 0, -12Number of shares or trading days
floatA decimal number100.50, 0.03, -1.25Prices, returns, costs, rates
strText, enclosed in quotes"ABC", "2024-01-02"Tickers, labels, notes, date text
boolA true-or-false valueTrue, FalseData checks and research flags

You can inspect a value’s type with type():

shares = 5
price = 102.75
ticker = "ABC"
data_is_complete = True

print(type(shares))
print(type(price))
print(type(ticker))
print(type(data_is_complete))

The outputs identify the values as an integer, float, string, and Boolean respectively.

Numbers are not text

The quotation marks are crucial:

price_number = 100.00
price_text = "100.00"

They may look similar when printed, but Python treats them differently. price_number can participate in arithmetic; price_text is a sequence of characters.

print(price_number + 5)
print(price_text + price_text)

The first line produces a numeric result. The second joins text, producing:

100.00100.00

This distinction matters later when importing market data: a column that visually resembles prices may be stored as text and therefore be unsuitable for calculation until converted. For now, make sure financial quantities are entered without quotation marks.

Strings label and explain calculations

A string is useful when you want the notebook to communicate clearly:

ticker = "ABC"
research_note = "Toy trade calculation"

To combine a string with a variable in readable output, use an f-string. Place f directly before the opening quotation mark and place variable names inside curly braces:

ticker = "ABC"
net_profit = 9.50

print(f"{ticker}: net profit = {net_profit}")

Output:

ABC: net profit = 9.5

The quotation marks belong to the surrounding text. The value inside {net_profit} is evaluated by Python and inserted into the message.


Arithmetic operators: turning values into a calculation

Python uses familiar arithmetic operators.

OperatorMeaningExample
+Addition100 + 5
-Subtraction105 - 100
*Multiplication3 * 100
/Division6 / 100
**Exponentiation2 ** 3

Python follows the usual mathematical order of operations: exponentiation first, then multiplication and division, then addition and subtraction. Parentheses make the intended calculation explicit.

entry_price = 100.00
exit_price = 104.00
shares = 3
commission_per_trade = 1.25

gross_profit = (exit_price - entry_price) * shares
total_commission = 2 * commission_per_trade
net_profit = gross_profit - total_commission

print(f"Gross profit: {gross_profit}")
print(f"Total commission: {total_commission}")
print(f"Net profit: {net_profit}")

This is a deliberately simplified one-share-price example. Its net-profit calculation is:

The two commissions represent one cost on purchase and one on sale. Realistic trading calculations later need bid-ask spreads, timing, financing, corporate actions, and other details. But the structure is already important: define assumptions as variables, calculate intermediate quantities, and name the final result.

Python Tutorial for Beginners 3: Integers and Floats - Working with Numeric Data

Watch the selected parts of Corey Schafer’s “Python Tutorial for Beginners 3: Integers and Floats - Working with Numeric Data.” It reinforces numeric types, arithmetic precedence, variable updates, and comparisons.

Watch numeric operations. Focus on the difference between integers and floats, the arithmetic operators, parentheses, and the equivalence between value = value + 1 and value += 1. Then skip to numeric comparisons for the distinction between assignment with = and testing equality with ==.

Updating a numeric variable

The long form of an update makes its logic visible:

cash_balance = 1_000.00
cash_balance = cash_balance - 301.25

print(cash_balance)

The result is 698.75.

Python offers shorthand forms once the long form is familiar:

cash_balance -= 301.25

This means the same thing as:

cash_balance = cash_balance - 301.25

Other common update forms include:

cash_balance += 50.00
share_count *= 2

For research code, the goal is not to use the shortest possible notation. It is to make the calculation accurate and readable.


Comparisons create Boolean results

A comparison asks whether a statement is true or false. Its result is a Boolean value: exactly True or False.

OperatorMeaningExample
==Equal toexit_price == entry_price
!=Not equal toexit_price != entry_price
>Greater thanexit_price > entry_price
<Less thanexit_price < entry_price
>=Greater than or equal tocash >= cost
<=Less than or equal todrawdown <= limit

The difference between = and == is fundamental:

shares = 3              # Assign 3 to shares
shares == 3             # Ask whether shares equals 3

The second line produces True; it does not change shares.

Here are practical Boolean values derived from a simple calculation:

net_profit = 9.50
initial_cash = 1_000.00
purchase_cost = 301.25

profitable_trade = net_profit > 0
can_afford_purchase = initial_cash >= purchase_cost

print(profitable_trade)
print(can_afford_purchase)

Both outputs are True.

A Boolean is not the string "True". These are different:

data_is_complete = True       # Boolean
data_status = "True"          # Text string

The first is suitable for a logical check. The second is merely text that happens to spell the word “True.”


Combining Boolean conditions

Python provides three basic logical operators:

  • and is True only when both conditions are True.
  • or is True when at least one condition is True.
  • not reverses a Boolean value.
The image depicts the outcomes of the logical operators `not`, `or`, and `and`: `not` reverses a Boolean, `or` accepts either true condition, and `and` requires both conditions to be true.

For example:

data_is_complete = True
market_is_holiday = False
has_permission = True

can_run_research = data_is_complete and has_permission
trading_day = not market_is_holiday
needs_attention = (not data_is_complete) or market_is_holiday

print(can_run_research)
print(trading_day)
print(needs_attention)

This produces:

True
True
False

Parentheses around a comparison or logical phrase are often optional, but they improve readability. In quantitative research, readable logic is valuable: a future reader should be able to see exactly which conditions must hold before a calculation is trusted.

You will use Boolean values with if statements in the next lesson, where the notebook will select actions based on rules. For now, focus on creating and interpreting the True or False result correctly.


Build a small notebook calculation

Create a new code cell beneath a Markdown heading such as:

## Toy trade calculation

Then run this code cell from top to bottom:

ticker = "ABC"

initial_cash = 1_000.00
entry_price = 100.00
exit_price = 104.00
shares = 3
commission_per_trade = 1.25

market_data_complete = True
market_is_holiday = False

purchase_cost = entry_price * shares + commission_per_trade
cash_balance = initial_cash - purchase_cost

sale_proceeds = exit_price * shares - commission_per_trade
cash_balance = cash_balance + sale_proceeds

net_profit = cash_balance - initial_cash
profitable_trade = net_profit > 0
can_afford_purchase = initial_cash >= purchase_cost
calculation_is_ready = (
    market_data_complete
    and can_afford_purchase
    and not market_is_holiday
)

print(f"Ticker: {ticker}")
print(f"Ending cash: {cash_balance}")
print(f"Net profit: {net_profit}")
print(f"Profitable trade: {profitable_trade}")
print(f"Calculation ready: {calculation_is_ready}")

Notice the progression:

  1. Inputs store stated assumptions: prices, shares, costs, and flags.
  2. Intermediate variables give names to purchase cost and sale proceeds.
  3. cash_balance is updated after each part of the toy transaction.
  4. The final arithmetic expression produces net_profit.
  5. Comparisons and logical operators produce Boolean status values.

Now change only this line:

exit_price = 96.00

Rerun the entire cell. The net profit should become negative and profitable_trade should become False. This is a useful notebook discipline: alter one stated assumption, rerun the relevant code, and inspect which outputs changed.

Common early mistakes

MistakeWhy it fails or misleadsBetter approach
entry price = 100Spaces are not allowed in variable names.entry_price = 100
entry-price = 100A hyphen means subtraction.entry_price = 100
price = "100"This creates text, not a numeric price.price = 100.00
data_is_complete = "True"This is a string, not a Boolean.data_is_complete = True
shares = 3 when you meant to compare= assigns a value.shares == 3 compares values.
Editing a value but trusting old outputNotebook output may be stale.Rerun the cell, preferably from top to bottom.

You can now use Python variables to retain information, distinguish numerical values from text and Boolean flags, update a calculation step by step, and evaluate a compact quantitative expression. The central habits are simple but durable: use descriptive names, keep units and types in mind, expose intermediate calculations, and rerun code whenever an assumption changes.

Next, you will move from individual values to collections: lists for ordered observations and dictionaries for labeled information.

Can't find a good explanation? Sign up and we'll make it for you

Sign up