~/learn/Python · Fundamentals
Numbers, types and calculations
Understand whole numbers, decimals, arithmetic and converting numeric text safely.
why this matters
Data often arrives as text. Knowing when to convert it prevents accidental text joining and incorrect calculations.
A type tells Python what kind of value it has and what operations make sense. int means integer, a whole number such as 3 or -2. float is a number that can have a fractional part, such as 2.5. str means string, or text: "3" is text even though it looks like a number. type(value) reveals the type.
Try it: Change quantity to 4. Predict the total before running it.
Expected output
<class 'int'> <class 'float'> <class 'str'> 7.5
An operator is a symbol that performs an operation. + adds, - subtracts, * multiplies and / divides. // gives the floor of the division result (rounded down), % gives the remainder, and ** raises a number to a power. For positive numbers, 7 // 2 is 3 and 7 % 2 is 1.
Try it: Use // and % to split 17 items into full groups of 5 and leftover items.
Order matters
Multiplication and division happen before addition and subtraction. Parentheses make a chosen part happen first: 2 + 3 * 4 is 14, but (2 + 3) * 4 is 20.
Conversion changes a value into another type. int("3") makes the whole number 3; float("2.5") makes 2.5; str(3) makes text. Conversion returns a new value: it does not change the original variable unless you assign the result.
Try it: Convert the text "12" to a number and add 5. The result should be 17, not 125.
Conversion is not magic
int("three") and int("2.5") raise ValueError because those strings are not whole-number text. int(2.9) truncates to 2 rather than rounding. Dividing by zero raises ZeroDivisionError.
Decimal arithmetic can have tiny representation errors: a float stores an approximation of many decimals. Use round(value, places) for a rounded numeric result and formatting for display. Precise financial calculations often use Decimal; that is a later topic.
key takeaways
- int is a whole number, float is a decimal number and str is text.
- Convert numeric text before doing arithmetic.
- // gives floor division, % gives a remainder and ** gives a power.
- Parentheses control the order of a calculation.
check your understanding
raw = "12" What does print(int(raw) + 5) show?
free practice
Build confidence with a question you can solve without Pro.