Values, variables & basic types
Work with ints, floats, strings and booleans and convert between them.
By Invicly Tech, , in Python Programming from Zero. About 13 minutes to read.
In short
Every value in Python has a type, such as int, float, str or bool. A variable is just a name that points to a value, and you can point it at a new value at any time.
Think of it like this: A variable is a sticky note with a name; you can peel it off and stick it on a different value.
Explained simply
A value is one piece of data: 42, 3.5, "hello" or True. Every value has a type, which says what kind of data it is and what you can do with it. You can add two numbers or join two pieces of text, but you cannot add a number to a word without converting one of them first.
A variable is a name that points to a value. When you write age = 30, Python creates the value 30 and ties the name age to it. Later, age = 31 moves the name to a new value. Names are case-sensitive, so Age and age are two different variables.
Python works out types by itself while the program runs. This is called dynamic typing. You never write "int age" like in some other languages. A name can even point to a string later, but that confuses readers, so keep one name for one kind of thing.
Data from the outside world, like the keyboard, files or the web, usually arrives as text. Converting it with int(), float() or bool() turns it into real values you can calculate with, and str() turns numbers back into text when you want to show them. Most beginner bugs in this area are a missing conversion.
Press Play on a diagram to walk through it one step at a time.
- Numbers
- int: 42, -7
- float: 3.14, 0.5
- Text
- str: "hello"
- Truth
- bool: True, False
- Nothing
- NoneType: None
- Step 1"42" (str)
Text, e.g. from input() or a file
- Step 2int("42")
Parse the text as a whole number
- Step 342 (int)
Now you can do arithmetic with it
- Step 4str(42)
Turn it back into text for output
- Whole numbers: 42, -7
- Exact, any size
- + - * // % work
- int("42") from text
- Decimals: 3.14, 1e3
- Approximate, about 16 digits
- / always returns a float
- float("3.5") from text
- Text: "hi", '42'
- + joins, * repeats
- "2" + "3" is "23"
- str(42) from a number
- False
- 0 and 0.0
- Empty string ""
- None
- Empty list, dict, tuple, set
- True
- Any other number, even -1
- Any non-empty string, even "False"
- Any non-empty collection
In depth
Names and objects: what = really does
Everything in Python is an object: a box in memory with a type, a value and an identity (id() shows a number for it). A variable does not contain the box; it points at it. y = x does not copy anything, it just adds a second name for the same object.
Numbers and strings are immutable, which means the object itself can never change. So x = x + 1 does not change the 5 that x points to. Python computes a new object, 6, and moves the name x to it. Any other name that pointed at 5 still sees 5.
This model explains a lot of behaviour later, especially with lists, which can change. For now, remember: = binds a name, it never copies. You can bind several names at once, a, b = 1, 2, and swap two values with a, b = b, a, without a temporary variable.
- 1x = 5
Name x points at the int object 5
- 2y = x
Name y points at the same object
- 3x = x + 1
Python builds a new object 6
- 4Move x
x now points at 6
- 5Result
x is 6, y is still 5
int and float under the hood
Python ints have no fixed size. 2 to the power 100 is stored exactly, all 31 digits of it. Very big ints are just slower.
Floats are different. They use the standard 64-bit format (IEEE 754) that almost every language uses, which keeps about 15 to 17 significant digits and stores numbers in binary. Many simple decimals, like 0.1, have no exact binary form, so 0.1 + 0.2 gives 0.30000000000000004. That is not a Python bug. Round for display, compare with math.isclose(), and use decimal.Decimal or whole cents for money.
Division has three operators. / always returns a float. // is floor division: it rounds down toward minus infinity, so -7 // 2 is -4, not -3. % gives the remainder, and its sign follows the right-hand number, so -7 % 2 is 1. round() sends exact halves to the even neighbour: round(2.5) is 2 and round(3.5) is 4.
- 1_000_000 is a valid int; underscores are just for reading
- divmod(135, 60) returns (2, 15) in one step
- math.isclose(0.1 + 0.2, 0.3) is True
bool is a kind of int, and what counts as true
True and False are the only two bool values, and bool is actually a subtype of int: True == 1 and False == 0, so True + True is 2. That is why sum(flags) counts how many items in a list are True.
Any value can be turned into a bool with bool(). The rule is simple: zero and empty things are False, everything else is True. 0, 0.0, an empty string "", None and empty collections are False. Every other number and every non-empty string is True.
This catches beginners out: bool("False") is True, and so is bool("0"), because both are non-empty strings. To turn text such as yes or no into a bool, compare the text itself, for example answer.strip().lower() in ("y", "yes"). None is a separate type, NoneType, and means "no value at all"; check for it with is None.
Conversions that work and ones that fail
Conversion functions build a new value of another type; they never change the original. int() accepts text that looks like a whole number and ignores spaces around it, so int(" 42 ") is 42. It rejects anything else with ValueError, including "4.2" and the empty string. Given a float, int() cuts off the decimals toward zero: int(4.9) is 4 and int(-4.9) is -4.
float() understands "3.5", "1e3" (1000.0), and even "inf" and "nan". str() works on anything and gives you its text form. int("ff", 16) reads a number in another base, here 255.
When the conversion might fail because the text came from a user or a file, wrap it in try/except ValueError and handle the bad case. Passing the wrong kind of thing, such as int(None), raises TypeError instead, which usually points to a bug in your own code.
- int("42") gives 42
- int(" 7 ") gives 7
- float("2.5") gives 2.5
- int(9.99) gives 9
- str(3.0) gives "3.0"
- int("4.2"): ValueError
- int(""): ValueError
- int("seven"): ValueError
- float("1,5"): ValueError
- int(None): TypeError
Naming rules and style
A name may contain letters, digits and underscores, but cannot start with a digit and cannot be a keyword such as if, for, class or None. Python's style guide, PEP 8, recommends snake_case for variables (total_price) and UPPER_CASE for values meant to stay constant (MAX_RETRIES). Python does not enforce constants; the capitals are a promise to readers.
Avoid names that hide built-in functions: list, str, sum, type, input, max and id are all real functions. If you write sum = 10, the sum() function is gone for the rest of that file, and the error appears far from the cause.
You can add optional type hints, such as age: int = 30. Editors and checkers like mypy use them to warn you, but Python itself ignores them when running.
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Assign and reassign variables~45m
- 2Use ints, floats, strings and booleans~45m
- 3Check types with type()~45m
- 4Convert between types with int(), str(), float()~45m
Key points
- Assignment uses = and creates or rebinds a name: x = 5 then x = x + 1.
- type(value) tells you a value's type; Python is dynamically typed.
- Use int(), float(), str() and bool() to convert between types.
- / always gives a float; // is floor division and % is the remainder.
- Floats are approximate: 0.1 + 0.2 is 0.30000000000000004.
Key terms
Tap a card to flip it. 0/6 known
Examples
age = 30
price = 9.99
name = "Sam"
is_member = True
print(type(age), type(price)) # <class 'int'> <class 'float'>
print(7 / 2, 7 // 2, 7 % 2) # 3.5 3 1
text = "42"
number = int(text) + 1
print(number) # 43
print("Age: " + str(age)) # Age: 30Splitting a bill fairly
Three friends share a 100.00 bill, and both numbers arrive as text, just like input() would give them. Step 1: convert the text with float() and int(). Step 2: divide; / gives a float with many digits because 100 / 3 has no exact decimal form. Step 3: round to cents for display. Step 4: notice that 3 x 33.33 is 99.99, so one cent is missing; real billing code works in whole cents (ints) and gives the leftover cent to one person.
total_text, people_text = "100.00", "3"
total = float(total_text)
people = int(people_text)
share = total / people
print(share) # 33.333333333333336
print(round(share, 2)) # 33.33
cents = round(total * 100) # 10000, an exact int
base, extra = divmod(cents, people) # 3333 each, 1 left over
print(base / 100, "each, plus", extra, "cent for one person")Turning minutes into hours and minutes
A timer gives you 135 minutes and you want to show "2 h 15 min". Step 1: // 60 gives the whole hours, 2. Step 2: % 60 gives what is left, 15. Step 3: divmod() does both at once. Step 4: notice that a negative number behaves differently because // rounds down, so check your inputs if negatives are possible. Step 5: str() or an f-string turns the numbers back into text.
minutes = 135
hours = minutes // 60 # 2
rest = minutes % 60 # 15
print(str(hours) + " h " + str(rest) + " min")
hours, rest = divmod(minutes, 60)
print(f"{hours} h {rest} min") # 2 h 15 min
print(-135 // 60, -135 % 60) # -3 45 (rounds down!)
print(type(hours), type(minutes / 60))Quick reference
- type(x) shows the type; isinstance(x, int) checks it (True for bools too)
- 7 / 2 is 3.5, 7 // 2 is 3, 7 % 2 is 1; -7 // 2 is -4 because // rounds down
- int(3.9) is 3 and int(-3.9) is -3: int() drops the decimals toward zero
- round(2.5) is 2 and round(3.5) is 4: exact halves go to the even number
- bool("False") is True: every non-empty string is truthy
- 1_000_000 is the same int as 1000000; underscores only help reading
- Compare floats with math.isclose(a, b), never with ==
- a, b = b, a swaps two variables in one line
Common mistakes
- Adding a str and an int ("Age: " + 30) raises TypeError; convert with str() first.
- int("3.5") fails with ValueError; use float() first, or int() on a float to truncate.
- Comparing floats with == after arithmetic; use round() or math.isclose().
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Set price = "19.99" and qty = "3" as strings, as if they came from a form. Convert them and print the total with exactly two decimals.
- Exercise 2medium
Convert a number of seconds, such as 3725, into hours, minutes and seconds and print it as "1 h 2 min 5 s".
- Exercise 3hard
Write to_bool(text) that turns "yes", "y", "true" and "1" (any case, extra spaces allowed) into True, "no", "n", "false" and "0" into False, and raises ValueError for anything else. Explain why bool(text) is not enough.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is there a maximum size for an int in Python?
- No, ints grow as large as memory allows, so 2 to the power 1000 is exact. One safety limit exists: converting an int with more than 4300 digits to or from text raises ValueError by default.
- Why don't I have to declare variable types in Python?
- Python is dynamically typed: the type belongs to the value, not the name, and is checked while the program runs. You can still add type hints like age: int = 30 for editors and checkers, but Python does not enforce them.
- How should I store amounts of money?
- Floats can drift by tiny amounts, so avoid them for money. Store whole cents in an int, or use decimal.Decimal("19.99"), created from a string rather than a float.
- What is the difference between None, 0 and an empty string?
- 0 is a number, "" is text with no characters, and None means no value at all. All three are falsy, but they are different types, so test for None with is None.