Loading...
Loading...
Convert between different data types
Sometimes you have a value as one type but need it as another. For example, a user types their age as "25" (a string), but you need to do math with it (as an integer). Type conversion functions let you change between types explicitly.
# Converting TO different types
int("42") # String → Integer: 42
float("3.14") # String → Float: 3.14
str(42) # Integer → String: "42"
bool(1) # Integer → Boolean: Trueage_str = "25" # This is a string (text)
print(age_str + 5) # ❌ Error! Can't add string + number
age_num = int(age_str) # ✅ Convert string to integer
print(age_num + 5) # 30 — works!# User input always comes in as a string
user_input = input("Enter a number: ") # User types "42"
number = int(user_input) # Convert to integer
print(number * 2) # 84
# Formatting numbers into strings
score = 95
message = "Your score: " + str(score) # "Your score: 95"
# Float to integer (truncates, doesn't round!)
print(int(3.99)) # 3 — truncates toward zero
print(round(3.99)) # 4 — actually roundsReal programs constantly deal with different data types:
| ❌ Wrong | Why | ✅ Right |
|---|---|---|
| `int("3.14")` | You can't convert a float-string directly to int | `int(float("3.14"))` → `3` |
| `int("hello")` | "hello" isn't a number — ValueError! | Check/clean input first |
| `str(42) + 5` | The 42 is now "42" (string) — still can't add number | `42 + 5` or `str(42) + str(5)` |
| `float("$5.99")` | Dollar sign isn't numeric | Strip symbols first: `float("5.99")` |
Create a variable score = "87" (as a string). Then:
score = "87"
final = int(score) + 10
print(f"Final score: {final}")