Variables, data types, and strings

3.15.2

Work with numbers and text, convert input, and format values for display.

On this page

Names and types

Assignment binds a name to an object. Common types include int for whole numbers, float for floating-point numbers, str for text, bool for True or False, and NoneType for None. Use / for true division and // for floor division.

quantity = 3
unit_price = 2.5
print(quantity * unit_price)
print(7 / 2, 7 // 2)
Example output
7.5
3.5 3

Clean and format strings

Strings are immutable. strip() and title() return new strings. An f-string evaluates expressions inside braces, and .2f displays a number with two decimal places.

item = "  iced coffee  ".strip().title()
price = 7.5
print(f"{item} — {price:.2f}")
Example output
Iced Coffee — 7.50

Convert input explicitly

input() returns a string. Convert it with int() or float() before arithmetic. int("3.5") raises ValueError. When using whole numbers for money, decide the smallest unit for storage, such as cents.

text = "4"
print(int(text) * 3)
Example output
12

Official references