Skip to main content
PROGRAMMING / PYTHON / LESSON 02

Expressions & Interactive Input.

Master arithmetic and precedence, then ask for values and process them using Python's real input() function—inside the browser or on your own computer.

Beginner65–85 minutesInteractive explorerReal Python workbench
00

What you'll learn

You've written statements, used variables and made decisions. Now practice the arithmetic and input skills that almost every beginner program needs. The workbench supplies realistic terminal responses without requiring local installation.

  • Write arithmetic expressions using +, -, *, /, //, %, and **.
  • Predict how precedence and parentheses affect numeric results.
  • Distinguish numeric values from text and convert using int() and float().
  • Use input() safely and recognize that it always returns a string.
  • Provide multiple input lines in order in a browser or local terminal.
  • Recognize invalid numeric responses and catch expected ValueError failures.
  • Independently build a small interactive calculator and test edge cases.
Learning sequence: Read the concept, predict the code's output, experiment with the visual explorer, then write the real Python. Use the optional local Python setup from Lesson 01 to practice the same snippets on your computer.
NUMBER OPERATIONS
01

Write expressions that calculate a result

Start with the familiar PEMDAS rule: Parentheses, Exponents, Multiplication/Division, then Addition/Subtraction. In Python, ** means exponents, * means multiplication, and / means division. Multiplication and division share one priority and run left to right; addition and subtraction also share one priority and run left to right. Before processing inventories or creating functions, become comfortable turning a plain-English calculation into Python. An expression combines values and operators to produce a result. Python supports addition (+), subtraction (-), multiplication (*), division (/), exponentiation (**), floor division (//) and remainder (%). Parentheses group work. Read the requirement first: a count of ports is not the same thing as a percentage or a number of complete groups.

Basic operations

a + b adds, a - b subtracts, a * b multiplies, and a / b divides. Python uses * for multiplication rather than a typographic ×.

PEMDAS is the starting point

P = parentheses; E = exponents (**); MD = multiply/divide at equal precedence, left to right; AS = add/subtract at equal precedence, left to right. PEMDAS does not mean all multiplication must happen before division or all addition before subtraction.

Power is not XOR

2 ** 3 evaluates to 8. A caret (^) is a bitwise operator, not exponentiation. Avoid using it when you mean 'to the power of'.

PYTHON / PREDICT THE RESULTRead before you run
devices = 3
ports_per_device = 8
spare_ports = 2
total = devices * ports_per_device + spare_ports
print(total)
print(2 ** 3)
What two numbers print? What happens if you replace the multiplication with addition? Reveal the explanation after you predict.

The output is 26 then 8. Replacing multiplication with addition would compute 3 + 8 + 2 = 13, which no longer represents the total number of ports.

Remember: Translate the words into the correct arithmetic operation. Use * for multiplication and ** for exponentiation.
ORDER CHANGES RESULTS
02

Operator precedence and parentheses

Remember PEMDAS: P (parentheses), E (exponents), MD (multiplication and division at the same level), AS (addition and subtraction at the same level). Work from higher to lower precedence. At the same level, calculate left to right: 20 / 5 * 2 is 8, and 10 - 3 + 2 is 9. Python writes exponents as **, and a chained exponent such as 2 ** 3 ** 2 groups from the right; parentheses make it explicit. Clear parentheses make an automation script easier for the next technician to read.

What Python evaluates first

2 + 3 * 4 is 14, not 20. Multiplication happens before addition. (2 + 3) * 4 is 20 because parentheses group the sum first.

Prefer clarity over cleverness

Write (used + reserved) * count if that is the requirement, instead of relying on others to guess what should be grouped.

PYTHON / PREDICT THE RESULTRead before you run
normal = 2 + 3 * 4
grouped = (2 + 3) * 4
print(normal)
print(grouped)
Why are the outputs different even though they contain the same numbers and operators? Reveal the explanation after you predict.

Normal prints 14 because 3 * 4 executes before + 2. Grouped prints 20 because the parentheses force the addition first.

INTERACTIVE EXPRESSION EXPLORER / SIMULATED PYTHON

Change a value. Predict the calculation.

Start with PEMDAS: Parentheses, Exponents, Multiplication/Division (same priority, left to right), then Addition/Subtraction (same priority, left to right). Change values and see why parentheses make a difference. The explorer models outcomes; the Python editor below executes actual code.

PYTHON EXPRESSION2 + 3 * 4
RESULT14Multiplication runs first
WHY INPUT REQUIRES CONVERSION
input() RETURNS TEXT"5"Type: str
int(TEXT)5Type: int

Try division by zero, negative numbers, and different typed responses. The real Python workbench is authoritative for Python behavior.

Remember: Use PEMDAS: parentheses, ** exponents, * / // % at the same priority from left to right, then + - from left to right. Add parentheses for clarity; predict before Run.
GROUPS AND LEFTOVERS
03

Understand /, //, and %

IT tasks often ask how many complete groups fit into a count and how much remains. The / operator performs true division and returns a float, even when the answer is a whole number. Floor division // rounds down toward negative infinity. Remainder % gives the leftover quantity after floor division. For nonnegative inventory counts, // and % are the natural pair for full groups and remaining items.

Full groups

23 // 5 is 4 complete batches. 23 / 5 is 4.6, which is not the number of fully packed batches.

Remainder

23 % 5 is 3 leftover devices. For negative values, floor division rounds downward rather than toward zero, so don't assume -7 // 3 is -2.

PYTHON / PREDICT THE RESULTRead before you run
devices = 23
batch_size = 5
print(devices / batch_size)
print(devices // batch_size)
print(devices % batch_size)
Which operation answers 'full batches' and which answers 'leftover devices'? Reveal the explanation after you predict.

The lines print 4.6, 4, and 3. Floor division (//) counts the full batches, while remainder (%) counts what is left.

Remember: Use / for a quotient, // for full nonnegative groups, and % for leftovers.
TYPE CONVERSIONS
04

Convert text to numbers deliberately

Data typed into a terminal arrives as text, even when it looks numeric. That distinction matters because '4' + '2' produces '42', but 4 + 2 produces 6. int() converts a whole-number string and float() converts decimal text; str() converts a value to text. Conversions can raise ValueError on invalid input. Learn the difference between int() truncating a float toward zero and mathematical rounding, which has separate rules.

Text is not a number

int('12') becomes 12; float('1.5') becomes 1.5. int('1.5') raises ValueError because that text is not a valid integer literal.

Format the final result

An f-string can format decimals: f'{ratio:.2f}' displays two digits after the decimal. This controls display, not the underlying numeric value.

PYTHON / PREDICT THE RESULTRead before you run
ap_count_text = '4'
ports_per_ap = 6
ports = int(ap_count_text) * ports_per_ap
ratio = 7 / 2
print(ports)
print(f'{ratio:.2f}')
Why doesn't the first calculation produce '444444'? Does the formatted ratio become a string? Reveal the explanation after you predict.

int(ap_count_text) converts the string to 4 before multiplication, so the first result is 24. The second output is 3.50. Formatting creates a text representation for display; ratio itself remains a float.

Remember: Convert input deliberately, perform arithmetic with numeric types, and format only when presenting output.
THE PROGRAM ASKS THE USER
05

Your first input() prompt

input(prompt) pauses a normal Python program until someone types a line and presses Enter. It returns a string without the trailing newline. The prompt text appears before the input. In the JoeLearns browser workbench, supply responses using the Program Input panel; the sandbox feeds those lines to input() in order. No dialog opens, and nothing is sent to a live service. If your code asks for more responses than you provided, Python raises EOFError with a helpful explanation.

input always returns text

age = input('Age: ') stores a str. Use int(age) only when you need to calculate with a valid integer.

Practice here and locally

In JoeLearns, fill the Program Input box before Run. On your own computer, type the response in Terminal when prompted. Both use actual Python input() behavior.

PYTHON / PREDICT THE RESULTRead before you run
minutes_text = input('Minutes: ')
minutes = int(minutes_text)
print(f'{minutes * 60} seconds')
If the provided input line is 5, what does Python receive and what does the program calculate? Reveal the explanation after you predict.

input() returns the text '5'. int() converts that text to the number 5; multiplying by 60 gives 300 seconds. The browser console shows the prompt and simulated typed response.

Remember: input() returns str. Provide one line per call and convert only when a calculation needs numbers.
MULTIPLE INPUT CALLS
06

Process answers in order

Each input() consumes the next available line. If a program asks two questions, provide two response lines in that order. Use distinct variable names and avoid reading an input twice by accident. On a normal terminal the user types after each prompt; in JoeLearns the input panel collects those values before execution. This also makes testing reproducible: the same inputs should produce the same output.

One line per prompt

The first input() reads line 1 and the second input() reads line 2. An empty line counts as a response, but may not be valid for numeric conversion.

Convert and verify

Don't multiply two strings to guess a numeric result. Convert responses, compute, and check a second sample after the first works.

PYTHON / PREDICT THE RESULTRead before you run
access_points = int(input('Access points: '))
ports_each = int(input('Ports each: '))
print(f'{access_points * ports_each} ports')
For lines 3 and 4, what final line prints? What if the order is reversed? Reveal the explanation after you predict.

The result is 12 ports. Reversing these two values still multiplies to 12, but not every calculation is commutative; for subtraction, order changes the result.

Remember: Each input() consumes a single line in sequence. Know exactly which question each answer belongs to.
WHEN INPUT IS NOT A NUMBER
07

Handle invalid and empty responses

A learner can enter a blank line or a word instead of a number. Calling int() on either raises ValueError. A small try/except block lets you give a helpful message without lying about a valid result. You will explore exception handling in depth later; for now, recognize what failed, provide a clear response and avoid fabricating a numeric value.

Never silently invent a value

If a count is unknown, printing '0 devices' would claim something the user did not supply. Ask again or report invalid input as appropriate.

Be specific about what failed

Except ValueError handles an invalid numeric conversion. It should not hide unrelated programmer errors with a broad except.

PYTHON / PREDICT THE RESULTRead before you run
raw = input('Number of devices: ')
try:
    count = int(raw)
    print(f'Entered {count}')
except ValueError:
    print('Enter a whole number')
What happens if the learner supplies 'N/A'? Does the program silently assume zero? Reveal the explanation after you predict.

int('N/A') raises ValueError. The exception handler prints Enter a whole number instead of claiming a valid count; no zero is invented.

Remember: Invalid text is feedback, not a valid numeric result. Handle expected conversion errors explicitly.
TURN A REQUIREMENT INTO A SCRIPT
08

Build a useful interactive calculation

You've now encountered arithmetic, grouping, formatting, user input and conversion. Combine them: ask for the number of endpoints and the number of devices per rack, calculate how many complete racks can be filled, and report the leftover endpoints. Write the algorithm in plain English first. Validate positive rack capacity to avoid division by zero; if a number is invalid, explain the problem. This is a small but genuine interactive command-line workflow.

Inputs, processing, output

Inputs are text until converted. Processing uses // and %. Output is a clear f-string with the derived counts.

Test the boundaries

Try exactly 10 endpoints in groups of 5, then 11, then zero. A rack capacity of zero is invalid and must not be used as a divisor.

PYTHON / PREDICT THE RESULTRead before you run
endpoints = int('11')
per_rack = int('5')
if per_rack > 0:
    full_racks = endpoints // per_rack
    remaining = endpoints % per_rack
    print(f'{full_racks} full racks, {remaining} remaining')
How many full racks hold 11 endpoints in groups of 5, and what should happen if per_rack is zero? Reveal the explanation after you predict.

The result is 2 full racks and 1 remaining endpoint. A zero rack capacity cannot be used as a divisor; the program should reject it rather than dividing by zero.

Remember: Turn a requirement into input, conversion, computation, validation and explicit output.
APPLY IT YOURSELF
09

Build your first calculation

The lesson begins with a guided exercise; complete the full coding clinic afterward. Edit real Python, read the console and trace, then check the result with the given inputs. Change the inputs and test other cases too.

JOELEARNS / PYTHON WORKBENCH

Write it. Run it. Understand it.

Learn arithmetic, operator precedence and real Python input() with a controlled text-input panel.

Python 3.14 · in-browser
CHALLENGE 01 / 8 · BEGINNER

Calculate connected ports

Northstar has three switches with eight connected ports each and two spare ports. Calculate total_ports using multiplication and addition, then print exactly '26 ports total'. Use the given values rather than writing the answer directly.

EXPECTED OUTPUT26 ports total
script.py editableCtrl / Cmd + Enter to run
Your code is stored only in session storage when enabled. Never paste secrets. Clearing this option clears saved drafts, not the editor.
Code executes only when you choose Run or Check. No account needed.
HINTS · OPTIONAL

Try solving it before asking for help. Hints never show a completed program.

PYTHON OUTPUTReady

Your printed output and errors will appear here.

VARIABLE TRACER

Run the code, then step through the executed lines to watch variable values change.

About this environment: The Python runtime is loaded on demand from a version-pinned CDN and runs inside a sandboxed, opaque-origin browser frame. Runs have a time limit. OS/network automation is outside this introductory workbench. If your code calls input(), a response panel appears to supply text to those calls. Don't paste secrets or untrusted scripts.

Next required step: complete the 8-challenge Practice milestone →
NEXT STEP / PRACTICE

Move from recognition to independent coding.

Some tasks fix a short script; later tasks require you to write the algorithm yourself. Optional hints provide direction without revealing the finished program.

Continue to all Expressions & Interactive Input challenges →After Practice: Control Flow →
10

Official references

Use the official Python documentation to confirm exact syntax or behavior. The browser workbench and the local Python interpreter should agree for these basic operations.

NEXT REQUIRED STEP · PYTHON FUNDAMENTALS

Complete the Practice milestone

You've reached the end of this written lesson. Your next step is practice—complete Expressions & Interactive Input Coding Challenges before proceeding to a new lesson. This is milestone 4 of 18. You can revisit the explanation whenever you need it.