What is Type Casting?
Type Casting is the process of converting a variable from one data type to another (for example, turning a string "10" into an integer 10).
In Python, there are two types of type casting:
Implicit Type Conversion (Done automatically by Python)
Explicit Type Conversion (Done manually by you)
1. Implicit Type Conversion (Automatic)
Python automatically converts one data type to another to prevent data loss.
How it works: If you add an integer and a float, Python automatically converts the integer to a float.
num_int = 5 # Integer
num_flo = 2.5 # Float
# Python automatically converts num_int to float before adding
result = num_int + num_flo
print(result) # Output: 7.5
print(type(result)) # Output: <class 'float'>2. Explicit Type Conversion (Manual)
This is what we usually mean by "Type Casting." You use built-in Python functions to force a data type change.
Common Type Casting Functions
Function | What it does | Example | Output |
| Converts to an Integer |
|
|
| Converts to a Float |
|
|
| Converts to a String |
|
|
| Converts to a Boolean |
|
|
Key Rules & Gotchas
⚠️ The Value Must Make Sense: You can only convert a string to an integer if the string looks like a number.
int("123")works perfectly.
int("apple")will crash your code with aValueError.
Boolean Truths: When casting to
bool(), numbers equal to0and empty items (like"",[],{}) becomeFalse. Almost everything else becomesTrue.
Why do we need it? (A Practical Example)
By default, user input in Python always comes in as a string. If you want to do math with it, you must type cast it.
# Without Type Casting (This will cause an error or weird behavior)
age = input("Enter your age: ") # User enters 20 -> age is "20" (string)
# next_year = age + 1 # ERROR: Cannot add string and integer
# With Type Casting
age = int(input("Enter your age: ")) # Converts the string "20" to integer 20
next_year = age + 1 # Works perfectly! (21)<div class="infographic-typeconv">
<style>
.infographic-typeconv {
--ink: #1a1a1a;
--ink-soft: #5c5c5c;
--paper: #ffffff;
--paper-alt: #f0ece4;
--accent: #2563eb;
--accent-soft:#e3ebfd;
--line: #ddd6c9;
--error: #c0392b;
--error-soft: #fbe9e7;
--mono-font: 'IBM Plex Mono', 'SFMono-Regular', Menlo, monospace;
--display-font: 'Fraunces', Georgia, serif;
--body-font: 'Inter', system-ui, sans-serif;
box-sizing: border-box;
max-width: 880px;
margin: 0 auto;
font-family: var(--body-font);
color: var(--ink);
background: var(--paper);
}
.infographic-typeconv[data-theme="dark"] {
--ink: #e8e6e1;
--ink-soft: #9a968c;
--paper: #121212;
--paper-alt: #1e1e26;
--accent: #5b8def;
--accent-soft:#202942;
--line: #2c313d;
--error: #e57373;
--error-soft: #3a2222;
}
.infographic-typeconv *, .infographic-typeconv *::before, .infographic-typeconv *::after { box-sizing: border-box; }
.infographic-typeconv .tc-wrap { padding: 0 clamp(1rem, 4vw, 2rem) 1.5rem; }
.infographic-typeconv h1 {
font-family: var(--display-font); font-weight: 600;
font-size: clamp(1.6rem, 5vw, 2.2rem); text-align: center; margin: 1.5rem 0 0.25rem; letter-spacing: -0.01em;
}
.infographic-typeconv .tc-sub { text-align: center; color: var(--ink-soft); font-size: 0.9rem; margin: 0 0 1.75rem; }
.infographic-typeconv .tc-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 1.25rem; }
@media (max-width: 700px) { .infographic-typeconv .tc-grid { grid-template-columns: 1fr; } }
.infographic-typeconv .tc-card { background: var(--paper-alt); border: 1px solid var(--line); padding: 1.1rem 1.15rem 1.3rem; }
.infographic-typeconv .tc-card-head { display: flex; align-items: center; gap: 0.6rem; margin-bottom: 0.9rem; }
.infographic-typeconv .tc-badge {
font-family: var(--display-font); font-size: 1.1rem; color: var(--accent);
width: 30px; height: 30px; border: 1.5px solid var(--accent); border-radius: 50%;
display: flex; align-items: center; justify-content: center; flex: none;
}
.infographic-typeconv .tc-card-title { font-weight: 700; font-size: 1rem; }
.infographic-typeconv .tc-card-tag { font-size: 0.72rem; color: var(--ink-soft); display: block; }
/* implicit playground */
.infographic-typeconv .imp-row { display: flex; align-items: center; justify-content: center; gap: 0.6rem; flex-wrap: wrap; margin: 1rem 0; }
.infographic-typeconv .imp-slot { display: flex; flex-direction: column; align-items: center; gap: 0.3rem; }
.infographic-typeconv .imp-input {
width: 84px; font-family: var(--mono-font); font-size: 1.05rem; text-align: center;
padding: 0.4rem 0.3rem; border: 1.5px solid var(--line); background: var(--paper); color: var(--ink);
border-radius: 4px;
}
.infographic-typeconv .imp-input:focus { outline: none; border-color: var(--accent); }
.infographic-typeconv .imp-type-chip {
font-family: var(--mono-font); font-size: 0.68rem; font-weight: 700; padding: 0.1rem 0.4rem;
border-radius: 3px; background: var(--paper); border: 1px solid var(--line); color: var(--ink-soft);
}
.infographic-typeconv .imp-op { font-size: 1.3rem; color: var(--ink-soft); }
.infographic-typeconv .imp-arrow { color: var(--accent); font-size: 1.3rem; }
.infographic-typeconv .imp-result-slot { display: flex; flex-direction: column; align-items: center; gap: 0.3rem; }
.infographic-typeconv .imp-result {
font-family: var(--mono-font); font-size: 1.15rem; font-weight: 700; color: var(--accent);
background: var(--accent-soft); border: 1.5px solid var(--accent); border-radius: 4px;
padding: 0.4rem 0.7rem; min-width: 84px; text-align: center;
}
.infographic-typeconv .imp-result-type { font-family: var(--mono-font); font-size: 0.68rem; font-weight: 700; color: var(--accent); }
.infographic-typeconv .imp-note { text-align: center; font-size: 0.78rem; color: var(--ink-soft); margin-top: 0.4rem; }
/* explicit playground */
.infographic-typeconv .exp-input-row { display: flex; gap: 0.5rem; margin-bottom: 0.8rem; }
.infographic-typeconv .exp-input {
flex: 1; font-family: var(--mono-font); font-size: 0.95rem; padding: 0.45rem 0.6rem;
border: 1.5px solid var(--line); background: var(--paper); color: var(--ink); border-radius: 4px;
}
.infographic-typeconv .exp-input:focus { outline: none; border-color: var(--accent); }
.infographic-typeconv .fn-row { display: grid; grid-template-columns: repeat(4, 1fr); gap: 0.4rem; margin-bottom: 0.9rem; }
.infographic-typeconv .fn-btn {
font: inherit; font-family: var(--mono-font); font-size: 0.78rem; font-weight: 700;
background: var(--paper); border: 1.5px solid var(--line); color: var(--ink-soft);
padding: 0.45rem 0.2rem; cursor: pointer; border-radius: 4px; text-align: center;
}
.infographic-typeconv .fn-btn.is-selected { border-color: var(--accent); color: var(--accent); background: var(--accent-soft); }
.infographic-typeconv .exp-output {
font-family: var(--mono-font); font-size: 1.05rem; font-weight: 700;
padding: 0.65rem 0.75rem; border-radius: 4px; background: var(--paper);
border: 1.5px solid var(--line); color: var(--ink); text-align: center;
transition: background 0.2s, border-color 0.2s, color 0.2s;
min-height: 1.4em; display: flex; align-items: center; justify-content: center; gap: 0.5rem;
}
.infographic-typeconv .exp-output .out-type {
font-size: 0.68rem; font-weight: 700; padding: 0.1rem 0.4rem; border-radius: 3px;
background: var(--accent-soft); color: var(--accent);
}
.infographic-typeconv .exp-output.flash-success { background: var(--accent-soft); border-color: var(--accent); color: var(--accent); }
.infographic-typeconv .exp-output.flash-error {
background: var(--error-soft); border-color: var(--error); color: var(--error); animation: tc-shake 0.4s;
}
@keyframes tc-shake {
0%, 100% { transform: translateX(0); } 20% { transform: translateX(-4px); } 40% { transform: translateX(4px); }
60% { transform: translateX(-3px); } 80% { transform: translateX(3px); }
}
@media (prefers-reduced-motion: reduce) {
.infographic-typeconv *, .infographic-typeconv *::before, .infographic-typeconv *::after {
animation-duration: 0.001ms !important; transition-duration: 0.001ms !important;
}
}
</style>
<div class="tc-wrap">
<h1>Type Conversion Playground</h1>
<p class="tc-sub">Edit the values. Watch the type change live.</p>
<div class="tc-grid">
<!-- Implicit -->
<div class="tc-card">
<div class="tc-card-head">
<div class="tc-badge">1</div>
<div>
<div class="tc-card-title">Implicit</div>
<span class="tc-card-tag">Python does it for you</span>
</div>
</div>
<div class="imp-row">
<div class="imp-slot">
<input class="imp-input" id="impA" type="text" value="5" inputmode="decimal" />
<span class="imp-type-chip" id="impATypeChip">int</span>
</div>
<span class="imp-op">+</span>
<div class="imp-slot">
<input class="imp-input" id="impB" type="text" value="2.5" inputmode="decimal" />
<span class="imp-type-chip" id="impBTypeChip">float</span>
</div>
<span class="imp-arrow">→</span>
<div class="imp-result-slot">
<div class="imp-result" id="impResult">7.5</div>
<span class="imp-result-type" id="impResultType">float</span>
</div>
</div>
<p class="imp-note" id="impNote">One value is a float, so Python upgrades both.</p>
</div>
<!-- Explicit -->
<div class="tc-card">
<div class="tc-card-head">
<div class="tc-badge">2</div>
<div>
<div class="tc-card-title">Explicit</div>
<span class="tc-card-tag">You choose the function</span>
</div>
</div>
<div class="exp-input-row">
<input class="exp-input" id="expInput" type="text" value="15" />
</div>
<div class="fn-row">
<button class="fn-btn is-selected" data-fn="int">int()</button>
<button class="fn-btn" data-fn="float">float()</button>
<button class="fn-btn" data-fn="str">str()</button>
<button class="fn-btn" data-fn="bool">bool()</button>
</div>
<div class="exp-output" id="expOutput">15 <span class="out-type">int</span></div>
</div>
</div>
</div>
<script>
(function () {
var root = document.currentScript.closest('.infographic-typeconv')
|| document.querySelector('.infographic-typeconv');
var bodyAttr = document.body.getAttribute('data-darkmode');
var dark;
if (bodyAttr === 'true') { dark = true; }
else if (bodyAttr === 'false') { dark = false; }
else {
var match = document.cookie.match(/(?:^|;\s*)darkMode=([^;]+)/);
dark = match ? match[1] === 'true' : false;
}
if (dark) root.setAttribute('data-theme', 'dark');
/* ---------- Implicit playground ---------- */
var impA = root.querySelector('#impA');
var impB = root.querySelector('#impB');
var impATypeChip = root.querySelector('#impATypeChip');
var impBTypeChip = root.querySelector('#impBTypeChip');
var impResult = root.querySelector('#impResult');
var impResultType = root.querySelector('#impResultType');
var impNote = root.querySelector('#impNote');
function isFloatLiteral(raw) {
return /\./.test(raw);
}
function formatNum(n, isFloat) {
if (isFloat) {
var s = String(n);
if (!/\./.test(s)) s += '.0';
return s;
}
return String(Math.trunc(n));
}
function recomputeImplicit() {
var rawA = impA.value.trim();
var rawB = impB.value.trim();
var a = parseFloat(rawA);
var b = parseFloat(rawB);
if (isNaN(a) || isNaN(b)) {
impResult.textContent = '—';
impResultType.textContent = '';
impNote.textContent = 'Enter two numbers to see the result.';
return;
}
var aFloat = isFloatLiteral(rawA);
var bFloat = isFloatLiteral(rawB);
impATypeChip.textContent = aFloat ? 'float' : 'int';
impBTypeChip.textContent = bFloat ? 'float' : 'int';
var resultIsFloat = aFloat || bFloat;
var sum = a + b;
impResult.textContent = formatNum(sum, resultIsFloat);
impResultType.textContent = resultIsFloat ? 'float' : 'int';
if (resultIsFloat && !(aFloat && bFloat)) {
impNote.textContent = 'One value is a float, so Python upgrades both.';
} else if (resultIsFloat) {
impNote.textContent = 'Both already floats — result stays a float.';
} else {
impNote.textContent = 'Both are ints — no conversion needed.';
}
}
impA.addEventListener('input', recomputeImplicit);
impB.addEventListener('input', recomputeImplicit);
recomputeImplicit();
/* ---------- Explicit playground ---------- */
var expInput = root.querySelector('#expInput');
var expOutput = root.querySelector('#expOutput');
var fnBtns = root.querySelectorAll('.fn-btn');
var currentFn = 'int';
function isNumericLiteral(raw) {
return /^-?\d+(\.\d+)?$/.test(raw);
}
function convert(fn, raw) {
var trimmed = raw.trim();
if (fn === 'int') {
if (/^-?\d+$/.test(trimmed)) {
return { ok: true, value: String(parseInt(trimmed, 10)), type: 'int' };
}
if (/^-?\d+\.\d+$/.test(trimmed)) {
return { ok: true, value: String(Math.trunc(parseFloat(trimmed))), type: 'int' };
}
return { ok: false, msg: 'ValueError: invalid literal' };
}
if (fn === 'float') {
if (isNumericLiteral(trimmed)) {
var f = parseFloat(trimmed);
var s = String(f);
if (!/\./.test(s)) s += '.0';
return { ok: true, value: s, type: 'float' };
}
return { ok: false, msg: 'ValueError: could not convert' };
}
if (fn === 'str') {
return { ok: true, value: '"' + raw + '"', type: 'str' };
}
if (fn === 'bool') {
if (trimmed === '') return { ok: true, value: 'False', type: 'bool' };
if (isNumericLiteral(trimmed)) {
return { ok: true, value: (parseFloat(trimmed) === 0 ? 'False' : 'True'), type: 'bool' };
}
return { ok: true, value: 'True', type: 'bool' };
}
}
function recomputeExplicit() {
var raw = expInput.value;
var res = convert(currentFn, raw);
expOutput.classList.remove('flash-success', 'flash-error');
void expOutput.offsetWidth; // restart animation
if (res.ok) {
expOutput.innerHTML = res.value + ' <span class="out-type">' + res.type + '</span>';
requestAnimationFrame(function () { expOutput.classList.add('flash-success'); });
} else {
expOutput.innerHTML = res.msg;
requestAnimationFrame(function () { expOutput.classList.add('flash-error'); });
}
}
fnBtns.forEach(function (btn) {
btn.addEventListener('click', function () {
fnBtns.forEach(function (b) { b.classList.toggle('is-selected', b === btn); });
currentFn = btn.dataset.fn;
recomputeExplicit();
});
});
expInput.addEventListener('input', recomputeExplicit);
recomputeExplicit();
})();
</script>
</div>