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.
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'.
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.
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.
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.
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.
2 + 3 * 4"5"Type: strTry division by zero, negative numbers, and different typed responses. The real Python workbench is authoritative for Python behavior.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Write it. Run it. Understand it.
Learn arithmetic, operator precedence and real Python input() with a controlled text-input panel.
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.
26 ports totalTry solving it before asking for help. Hints never show a completed program.
Your printed output and errors will appear here.
Run the code, then step through the executed lines to watch variable values change.
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 →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.
