Difficulty: Beginner
A variable in Python is a name that refers to a value stored in memory. Unlike statically typed languages, Python variables do not require explicit type declarations. You simply assign a value to a name using the = operator, and Python automatically infers the type based on the value.
Python has several built-in data types. The four most fundamental ones are: int (whole numbers like 42 or -7), float (decimal numbers like 3.14 or -0.5), str (text enclosed in single or double quotes like "hello"), and bool (logical values True or False). Each value in Python has a type, and you can check it using the built-in type() function.
Variable names in Python must start with a letter or underscore, can contain letters, digits, and underscores, and are case-sensitive. By convention, Python uses snake_case for variable names (e.g., my_variable, total_count). Names that start with an uppercase letter are typically reserved for class names.
Python is dynamically typed, which means a variable can be reassigned to a value of a different type at any time. While this offers flexibility, it also means you need to be careful about tracking what type a variable holds, especially in larger programs. The type() function is your friend for debugging type-related issues.
Python also supports multiple assignment in a single line, letting you assign several variables at once. This is a common Python idiom that makes code more concise. You can also swap variable values without a temporary variable using tuple unpacking: a, b = b, a.
name = "Alice"
age = 25
height = 5.6
is_student = True
print(name)
print(age)
print(height)
print(is_student)
Each variable is assigned a value of a different type. Python infers the type automatically: str for text, int for whole numbers, float for decimals, and bool for True/False.
x = 10
y = 3.14
z = "Python"
w = False
print(type(x))
print(type(y))
print(type(z))
print(type(w))
The type() function returns the class/type of any value. This is extremely useful for debugging and understanding what kind of data a variable holds.
a, b, c = 1, 2.5, "hello"
print(a)
print(b)
print(c)
# Reassigning to a different type
a = "now I'm a string"
print(a)
print(type(a))
Python allows assigning multiple variables in one line. Variables can also be reassigned to values of a completely different type -- this is what 'dynamically typed' means.
x = 10
y = 20
print(x, y)
x, y = y, x
print(x, y)
Python supports elegant variable swapping using tuple unpacking. No temporary variable is needed. This is a commonly asked Python idiom in interviews.
Variables, int, float, str, bool, type()