0
0
Pythonprogramming~5 mins

How variable type changes at runtime in Python

Choose your learning style9 modes available
Introduction

Sometimes, a variable can hold different types of values as the program runs. This helps make code flexible and easy to change.

When you want to store a number first, then later store text in the same variable.
When reading input from a user that can be different types at different times.
When you want to reuse a variable for different purposes in a simple script.
Syntax
Python
variable = value
variable = another_value

You do not need to declare the type of a variable in Python.

The type of the variable changes automatically when you assign a new value of a different type.

Examples
Here, x starts as a number, then changes to text.
Python
x = 10
print(type(x))
x = "hello"
print(type(x))
data first holds a decimal number, then a list of numbers.
Python
data = 3.14
print(type(data))
data = [1, 2, 3]
print(type(data))
Sample Program

This program shows how the variable value changes type from integer to string to list.

Python
value = 5
print(f"Value: {value}, Type: {type(value)}")

value = "five"
print(f"Value: {value}, Type: {type(value)}")

value = [5]
print(f"Value: {value}, Type: {type(value)}")
OutputSuccess
Important Notes

Python variables are like labels that can be moved from one box to another with different contents.

Changing variable types can be useful but be careful to avoid confusion in your code.

Summary

Python variables do not have fixed types.

The type changes automatically when you assign a new value.

This makes Python flexible and easy to use for beginners.