Python Variables & Types
Python Variables
In Python, variables are dynamically typed, meaning you do not need to explicitly declare their types before using them. A variable is created the moment you first assign a value to it. This dynamic typing provides tremendous flexibility, allowing a variable to store an integer at one point and a string at another during execution.
Behind the scenes, variables in Python act as references to objects in memory rather than memory boxes themselves. When you write x = 10, Python creates an integer object 10 in memory and sets the name x to point to it. If you later assign x = "hello", Python creates a string object and updates the reference, leaving the original integer to be collected by the garbage collector if there are no other references.
Declaration Rules:
- Must start with a letter or underscore.
- Cannot start with a number.
- Case-sensitive (
age,Age, andAGEare different).
Python also supports multiple assignments in a single line, such as a, b, c = 1, 2, 3, which makes code concise. Understanding scope is critical: variables declared inside a function have a local scope, whereas those declared outside have a global scope.
To modify a global variable inside a local context, developers must use the global keyword, though this is generally discouraged to keep code modular and readable.
Type Casting in Python
Type casting is the process of converting a variable from one data type to another. In Python, this is achieved using constructor functions like int(), float(), and str(). This is highly useful when parsing user inputs or reading numbers stored as strings.
x = int("123")
y = float("45.67")
print("Casted x:", x, type(x))
print("Casted y:", y, type(y))name = "Alice"
age = 25
gpa = 3.85
is_student = True
print(f"Name: {name}, Age: {age}, GPA: {gpa}, Student: {is_student}")
print("Type of age:", type(age))