0
0
Pythonprogramming~10 mins

How variable type changes at runtime in Python - Visual Walkthrough

Choose your learning style9 modes available
Concept Flow - How variable type changes at runtime
Assign value to variable
Check value type
Variable holds value and type
Reassign variable with new value
Check new value type
Variable updates to new type
This flow shows how a variable in Python can hold a value of one type, then be reassigned to a value of a different type, changing its type at runtime.
Execution Sample
Python
x = 10
print(type(x))
x = 'hello'
print(type(x))
Assign an integer to x, print its type, then assign a string to x and print its new type.
Execution Table
StepCode LineVariable x ValueType of xOutput
1x = 1010int
2print(type(x))10int<class 'int'>
3x = 'hello''hello'str
4print(type(x))'hello'str<class 'str'>
5End'hello'strExecution stops
💡 Code ends after printing the type of x as str.
Variable Tracker
VariableStartAfter Step 1After Step 3Final
xundefined10 (int)'hello' (str)'hello' (str)
Key Moments - 2 Insights
Why does the type of x change after reassignment?
Because Python variables are labels for values, not fixed types. When x is assigned a new value, it points to that new value and its type changes accordingly, as shown in steps 1 and 3 of the execution_table.
Does the original integer value 10 stay linked to x after reassignment?
No, after step 3, x no longer refers to 10. It now refers to the string 'hello'. The integer 10 still exists in memory if used elsewhere, but x points to the new string.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 2, what is the output?
A<class 'str'>
B<class 'int'>
C10
D'hello'
💡 Hint
Check the Output column at step 2 in the execution_table.
At which step does the variable x change its type from int to str?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the Type of x column in the execution_table between steps 2 and 3.
If we assign x = 3.14 after step 4, what would be the type of x?
Afloat
Bstr
Cint
Dbool
💡 Hint
Recall that 3.14 is a decimal number, which in Python is a float type.
Concept Snapshot
Python variables can hold any type of value.
Assigning a new value changes the variable's type.
Variable is a label pointing to a value.
Type is checked at runtime, not fixed.
Use type() to see current type.
Full Transcript
This example shows how a Python variable can change its type during program execution. Initially, x is assigned the integer 10, so its type is int. When we print type(x), it shows <class 'int'>. Later, x is assigned the string 'hello', changing its type to str. Printing type(x) then shows <class 'str'>. This happens because Python variables are just labels for values, and can point to any type of value at any time. The execution table traces each step, showing the value and type of x, and the output printed. This helps beginners see how variable types are dynamic in Python.