Explain it simply
Explain it simply
Casting means converting a value from one type to another. The text "25" looks like a number to a person, but to Python it is just a string of two characters. Only after int("25") does it become the number 25 that you can add to or subtract from.
In Python you simply call the name of the target type like a function: int(), float(), str() or bool(). These functions do not change the original value; they return a new value of the new type, so remember to store the result in a variable.
Problem → Why → Solution
The problem: input() hands you a string, not a number
You write a tiny program that asks for the user's age and works out next year's age. The user types 25, but instead of showing 26 the program stops with a TypeError. Trying another approach, age * 2 prints "2525" instead of 50. The cause is that input() always returns a string, whatever the user types.
age = input("How old are you? ") # user types 25 -> age is "25"
print(age * 2) # 2525 (string repetition, not maths)
print(age + 1) # TypeError: can only concatenate str (not "int") to strWhy does this happen?
Python never converts one type into another behind your back. With a string and an int joined by +, it cannot tell whether you meant to join text or add numbers, so it raises an error. A string times an int, however, repeats the text, so you get a wrong result with no error at all. The fix is to convert user data with int() or float() as soon as you receive it.
Core concept: each type name is a converter function
int(), float(), str() and bool() are classes, and calling one builds a new object of that type from the value you pass in. Whether the conversion works depends on the input; the table below collects the rules.
Python distinguishes two kinds of conversion. Implicit conversion happens on its own only between numeric types, as when 2 + 0.5 quietly becomes the float 2.5. Explicit conversion, which is what casting means, is required everywhere else, and above all between text and numbers.
| Call | Result | Note |
|---|---|---|
| int(3.9) | 3 | Drops the decimals, no rounding |
| int(" 42 ") | 42 | Surrounding spaces are allowed |
| int("3.5") | ValueError | Only whole-number text is accepted |
| float("3.5") | 3.5 | Also reads forms like "1e3" |
| str(10) | "10" | Works on any value |
| bool("False") | True | Every non-empty string is True |
When int() reads a string it accepts surrounding whitespace, a + or - sign and underscores such as 1_000. A decimal point or any letters, though, make it raise ValueError: invalid literal for int() with base 10. To get a whole number from "3.7", convert in two steps: int(float("3.7")). A value of a completely unsuitable type, such as int(None), raises TypeError rather than ValueError.
Converting a number to a string never fails: str() can turn any value into text. When you want values inside a sentence, though, f"Age: {age}" is clearer than "Age: " + str(age), because the f-string performs the conversion for you.
bool() only looks at whether a value is empty; it never reads what the text means. Only "" is False, while "False", "0" and "no" are all True. To turn a yes/no answer into a boolean, write the comparison yourself, for example text.strip().lower() == "yes".
- Outside data arrives as a string
- Convert right away with int()/float()
- Catch ValueError for bad text
- Work only with numbers inside
Cast once at the program's entry point and the rest of your code only ever sees correctly typed data.
General pattern
number = int(text) # whole-number text -> int
real = float(text) # decimal text -> float
label = str(value) # anything -> str
flag = bool(value) # empty -> False, otherwise True
try:
number = int(raw_text)
except ValueError:
number = fallbackEvery conversion function returns a new value that you must assign. Wrapping conversions of outside text in try/except ValueError keeps bad input from crashing the program.
Example: converting numbers, strings and user input
This example tries int(), float() and str() one at a time, then converts the string "25", just as input() would return it, and calculates with it. The last part loops over text that int() accepts and text it rejects, and shows how try/except catches the error; a later lesson covers try/except in depth.
# ===== 1. Basic Casting Examples =====
x = int(3.9) # float -> int (cuts off the decimals)
print(f"int(3.9) = {x}")
y = float(5) # int -> float
print(f"float(5) = {y}")
z = str(10) # int -> str
print(f"str(10) = '{z}', Type: {type(z)}")
# ===== 2. String to Number =====
print("\n===== String to Number =====")
a = int("100")
print(f"int('100') = {a}")
b = float("3.14")
print(f"float('3.14') = {b}")
# ===== 3. Practical Use Case =====
print("\n===== User Input Example =====")
user_age = "25" # input() always returns a str
age = int(user_age)
next_year = age + 1
print(f"Current age: {age}")
print(f"Next year: {next_year}")
# ===== 4. Text That Is Not a Whole Number =====
print("\n===== Invalid Text =====")
for text in [" 42 ", "3.5", "abc"]:
try:
print(f"int({text!r}) = {int(text)}")
except ValueError as err:
print(f"int({text!r}) failed: {err}")Code breakdown
- Line 2
x = int(3.9) # float -> int (cuts off the decimals)int() drops the fractional part of a float, so 3.9 becomes 3, not 4.
- Line 9
print(f"str(10) = '{z}', Type: {type(z)}")z is now a string holding the characters "1" and "0", and type(z) prints <class 'str'>. Writing z + 5 would raise TypeError.
- Lines 21-22
age = int(user_age)user_age = "25" stands in for the string input() returns. Only after int() converts it does age + 1 give 26.
- Line 29
for text in [" 42 ", "3.5", "abc"]:" 42 " has spaces, but int() strips them and returns 42. "3.5" and "abc" are not whole-number text, so both raise ValueError.
- Lines 32-33
except ValueError as err:Catching ValueError and printing Python's message lets the loop carry on to the next text instead of crashing. {text!r} shows the repr with quotes, so you can see the spaces.
int(3.9) = 3
float(5) = 5.0
str(10) = '10', Type: <class 'str'>
===== String to Number =====
int('100') = 100
float('3.14') = 3.14
===== User Input Example =====
Current age: 25
Next year: 26
===== Invalid Text =====
int(' 42 ') = 42
int('3.5') failed: invalid literal for int() with base 10: '3.5'
int('abc') failed: invalid literal for int() with base 10: 'abc'int() with a base, and converting collections
int() takes an optional second argument, the base. int("ff", 16) reads hexadecimal as 255, and int("101", 2) reads binary as 5. With base 0, Python works the base out from a prefix such as "0x" or "0b". This is handy when reading colour codes or permission bits.
Calling a type name like a function works for collections too. list("abc") splits a string into a list of characters, and tuple([1, 2]) turns a list into a tuple. You will meet these again in the List and Tuple lessons.
print(int("ff", 16)) # 255
print(int("101", 2)) # 5
print(int("0x1F", 0)) # 31 (base read from the prefix)
print(list("abc")) # ['a', 'b', 'c']
print(tuple([1, 2])) # (1, 2)
print(int(float("3.7"))) # 3In real projects
Where this shows up in real projects
Most data that enters a program from outside is text. Command-line arguments (sys.argv), environment variables (os.environ), CSV columns, web form fields and URL query strings all arrive as strings. That is why a line like PORT = int(os.environ.get("PORT", "8000")) appears in almost every configuration module.
Frameworks such as Django and FastAPI do this casting for you in the layer that validates form and request data, and show the user an error message when a value cannot be converted. Underneath, they still call int() or float() and catch ValueError. When you write reports or logs you go the other way, turning numbers back into text with str() or an f-string. Spreadsheet imports are a classic source of bugs here, because a cell that looks like 1,250 needs its comma removed before float() will accept it.
Common mistakes
Common mistakes
1. Calculating with input() before converting
After price = input("Price: "), price * 2 repeats the text into something like "1010" and price + 1 raises TypeError. Convert on the same line: price = float(input("Price: ")).
2. Passing decimal text to int()
Even int("3.0") raises ValueError, because int() only accepts whole-number text. If the data may contain decimals, read it with float() and then apply int() or round() if you need a whole number.
3. Expecting bool("False") to be False
Reading DEBUG=False with bool(os.environ["DEBUG"]) gives True, because the string is not empty, and debug mode stays on in production. Compare explicitly instead, for example value.lower() in ("1", "true", "yes"), and treat anything else as False.
Best practices
Best practices
- Convert outside data once, where it enters the program, instead of sprinkling int() calls everywhere.
- Guard conversions of user-typed text with try/except ValueError and show a clear message.
- Prefer f-strings over str() plus + when putting numbers into text.
Mini challenge
Mini challenge: give form data the right types
Write two helper functions that safely convert a dictionary of strings from a web form into int, float and bool values.
- to_int(text, default=0) returns the int, or default when ValueError occurs
- to_bool(text) accepts only "yes", "true" and "1" as True, ignoring case and spaces
- Convert age, height_m, newsletter and pets, then print each value with its type name
- Also print bool("No") so it can be compared with to_bool
def to_int(text: str, default: int = 0) -> int:
# TODO: try int(text); on ValueError return default
...
def to_bool(text: str) -> bool:
# TODO: strip + lower, then check against ("yes", "true", "1")
...
form = {"age": " 31 ", "height_m": "1.68", "newsletter": "No", "pets": "two"}
# TODO: convert each field with the right function
# TODO: print value and type(value).__name__ for age and height
# TODO: print the newsletter flag next to bool("No")
# TODO: print next birthday as text: "Next birthday: 32"Expected: The program prints: age=31 (int) height=1.68 (float) newsletter=False, but bool('No') is True pets=-1 (could not read 'two') Next birthday: 32
Show hint
type(age).__name__ gives the type's name as a string, such as "int". Passing default=-1 for pets makes it obvious that "two" could not be read.
Show solution
def to_int(text: str, default: int = 0) -> int:
"""Convert text to int, or return default if it is not a whole number."""
try:
return int(text)
except ValueError:
return default
def to_bool(text: str) -> bool:
"""Treat yes/true/1 (any case, extra spaces allowed) as True."""
return text.strip().lower() in ("yes", "true", "1")
form = {"age": " 31 ", "height_m": "1.68", "newsletter": "No", "pets": "two"}
age = to_int(form["age"])
height = float(form["height_m"])
newsletter = to_bool(form["newsletter"])
pets = to_int(form["pets"], default=-1)
print(f"age={age} ({type(age).__name__})")
print(f"height={height} ({type(height).__name__})")
print(f"newsletter={newsletter}, but bool('No') is {bool('No')}")
print(f"pets={pets} (could not read 'two')")
print("Next birthday: " + str(age + 1))Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- int(), float(), str() and bool() return a new value that you must store.
- input() and most outside data give you strings, so convert before calculating.
- int() accepts only whole-number text; "3.5" or "abc" raise ValueError.
- bool() only checks for emptiness, so even the string "False" is True.
The Python Tutorial — Python Software Foundation