Skip to main content

Someone wanted to learn this too, so Grasp built them a personal learning path.

You can keep exploring this one or create your own

Writing Python Expressions and Using Type Conversion

Hello! Last time, you set up a virtual environment and confirmed which Python installation your terminal uses. Keep that environment available; this lesson is where you begin writing code in it.

You’ll use variables to build expressions with numbers, text, and Boolean values, then convert between types when data arrives in the wrong form. These are the building blocks for the decisions and calculations you’ll later make in a Django application.


Give values names

An expression is code that Python evaluates to a value. The expression 2 + 3 evaluates to 5. An assignment gives a value a name so you can use it again:

quantity = 3
unit_price = 12.5
subtotal = quantity * unit_price

print(subtotal)  # 37.5

The single equals sign assigns the result on its right to the name on its left. It does not ask whether the two sides are equal; that comparison uses ==, which we’ll meet shortly.

If you’ve worked with JavaScript, the idea of assigning a value to a variable is familiar. In Python, you don’t write let or const: quantity = 3 is a complete assignment. Python also does not require a type declaration here. The value 3 has type int, while 12.5 has type float; type(quantity) lets you inspect the type of the value currently associated with quantity.

Real Python’s Variables in Python develops this distinction between a name, its value, and an expression.

Variables in Python: Usage and Best Practices – Real Python

Read Real Python’s explanation of assignment and using names in expressions. It gives you a precise mental model for the code above.

In “Getting to Know Variables in Python,” read “Creating Variables With Assignments,” beginning at names and assignment. Then read “Setting and Changing a Variable’s Data Type,” from dynamic typing. Under “Working With Variables in Python” → “Expressions,” start at the example comparing hard-coded calculations with a named radius; read reusable expressions. Stop before “Object Counters.”

Names are case-sensitive: unit_price and Unit_Price are different names. Prefer descriptive snake_case names, with underscores between words. You can later assign a string to quantity, but doing so changes what operations make sense for that name. Keeping a variable’s intended meaning consistent makes code easier to follow.

To try the examples, activate your existing .venv, create a file named expressions.py beside it, and run python expressions.py. No extra package is needed.


Calculate with integers and floats

Python’s int represents whole numbers, such as an item count. A float represents a floating-point number, such as 12.5 or 12.0. The decimal point matters: 12 is an int; 12.0 is a float.

Watch Corey Schafer work through the numeric types and arithmetic operators. The parenthesized examples are particularly useful: they show why an expression’s grouping is part of its meaning.

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

Watch “Python Tutorial for Beginners 3: Integers and Floats - Working with Numeric Data” by Corey Schafer for numeric types and the main arithmetic operators.

Watch numeric types, then arithmetic operators. Continue through grouping expressions for parentheses and reassignment. Notice especially that / produces a float, while // performs floor division.

Here are the operators in one place:

print(7 + 2)    # 9
print(7 - 2)    # 5
print(7 * 2)    # 14
print(7 / 2)    # 3.5
print(7 // 2)   # 3
print(7 % 2)    # 1
print(7 ** 2)   # 49

% gives the remainder after division; ** raises a number to a power. Python follows normal arithmetic precedence, so 3 * (2 + 1) is 9, while 3 * 2 + 1 is 7. Use parentheses when they make your intent clearer, even if precedence would already give the same answer.

One detail to remember: // floors a result rather than merely removing its decimal portion. That distinction matters for negative numbers: -7 // 2 is -4. Dividing by zero with either / or // raises an error.

Floats are convenient for learning arithmetic, but many decimal fractions cannot be represented exactly as binary floating-point values. You may see a result such as 0.1 + 0.2 displayed as 0.30000000000000004. When the course reaches financial data, you’ll use an appropriate representation for prices rather than rely on floats for exact money calculations.


Build and display strings

A string, or str, holds text. Both single and double quotes work:

product_name = "Notebook"
category = 'Stationery'
sku = "0042"

Although sku contains digits, its quotes make it text. That is often appropriate for an identifier: you display it, but you do not add it to a price. Python distinguishes "3" from 3 for the same reason.

You can join strings with +, but you cannot directly add a string and an integer:

label = product_name + " — " + category
print(label)                 # Notebook — Stationery

# print("Quantity: " + 3)    # TypeError: str and int cannot be joined this way

For readable output containing values of different types, use an f-string. Put f immediately before the opening quote and put expressions to insert inside braces:

quantity = 3
unit_price = 12.5
message = f"{quantity} {product_name}s cost {quantity * unit_price}"
print(message)  # 3 Notebooks cost 37.5

The result of an f-string is itself a string; inserting a number for display does not change the original numeric variable. If you know JavaScript template literals, f-strings serve a similar purpose, with Python’s f"..." and {...} syntax.

Basic Data Types in Python: A Quick Exploration – Real Python

Read Real Python’s short introductions to ordinary strings and f-strings. Concentrate on how quotation marks create text and how braces insert a value.

Under “Strings and Characters” → “Regular String Literals,” read from string literals; stop before “Escape Sequences in Strings.” Then skip to “F-String Literals” and read from f-string basics. Stop before the paragraph beginning “You can also use f-strings to format.” The intervening string features are useful later but aren’t required for this lesson.


Produce Boolean values with comparisons

A Boolean has one of two values: True or False, capitalized and without quotes. A comparison produces a Boolean. The supplied comparison-operator chart shows the six operators you’ll use most often:

Python’s equality and ordering operators, with example comparisons and their Boolean results. Each comparison evaluates to `True` or `False`.

Equality is ==, not assignment’s =. Inequality is !=; the ordering operators are <, >, <=, and >=. For example:

stock = 5
requested = 3

print(requested <= stock)    # True
print(requested == stock)    # False
print(requested != stock)    # True

You can combine Boolean expressions with and, or, and not:

is_available = requested <= stock
is_valid_quantity = requested > 0

print(is_available and is_valid_quantity)  # True
print(is_available or is_valid_quantity)   # True
print(not is_available)                    # False

With Boolean operands, and requires both to be true, or requires at least one, and not reverses the value. Parentheses can make a larger expression unambiguous: (requested > 0) and (requested <= stock). In the next lesson, you’ll use expressions like this to decide which code runs.

Python also evaluates many non-Boolean values in a Boolean context. 0 and "" are falsy; nonzero numbers and nonempty strings are truthy. The bool() function lets you inspect that result:

print(bool(0))        # False
print(bool("hello"))  # True
print(bool("False"))  # True

The last result is a common trap. "False" is nonempty text, not the Boolean value False.

Basic Data Types in Python: A Quick Exploration – Real Python

Return to Real Python’s basic-data-types guide for the distinction between Boolean values and the truth value of other objects.

In “Booleans,” read the opening explanation from two truth values. Then, in “The Built-in bool() Function,” read the falsy-value rules from truthiness rules. Stop before the discussion of custom classes.


Convert values when their types do not match the task

Text arriving from a form or API may look numeric without being a number. If a quantity arrives as "3", adding it to another string joins text rather than performing arithmetic:

quantity_text = "3"
print(quantity_text + "2")  # 32, not 5

Convert it deliberately with int() before calculating. Use float() when a valid numeric string includes a decimal point, and str() when you specifically need a string:

quantity = int("3")       # 3
measurement = float("2.5")  # 2.5
quantity_label = str(3)  # "3"

print(type(quantity))      # <class 'int'>
print(type(measurement))   # <class 'float'>

Corey Schafer demonstrates the text-versus-number problem using values that could have come from an external source.

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

Return to Corey Schafer’s numeric-data tutorial for comparisons and converting numeric text. The conversion example connects directly to the form and API values you’ll handle later.

Watch comparisons, paying attention to = versus ==. Then watch numeric text to see why adding two strings gives a different result from adding two integers.

Conversion is not a guess about what you meant: the input must be valid for the requested type. int("three") and int("3.5") raise ValueError; use float("3.5") for the latter. Also, int(3.9) produces 3 by discarding the fractional part—it does not round to 4.

Here is one small program that brings the lesson together:

product_name = "Notebook"
quantity_text = "3"          # Imagine text supplied by a form
unit_price = 12.5
stock = 5

quantity = int(quantity_text)
subtotal = quantity * unit_price
can_fulfill = quantity > 0 and quantity <= stock

print(f"{quantity} {product_name}s: {subtotal}")
print(f"Can fulfill: {can_fulfill}")

It prints:

3 Notebooks: 37.5
Can fulfill: True

The important boundary is between received text and values used for a calculation. Convert the quantity before multiplying it, and keep can_fulfill as a Boolean rather than the string "True".


What to carry forward

You can now assign and reuse values; calculate with int and float; create strings and f-strings; produce Booleans with comparisons; and convert values with int(), float(), and str(). When an expression surprises you, check the types of its inputs first: "3" and 3 may look similar on screen, but Python gives them different behavior.

Next, you’ll use Boolean expressions to control program flow with conditional statements.

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

Sign up