In Python, variables can hold values of various types. Here are some common variable types in Python:
Integers (int
):
Whole numbers without a fractional component.
age = 25
Floating-point Numbers (float
):
Numbers with a decimal point or in scientific notation.
height = 5.9
Strings (str
):
Sequences of characters enclosed in single or double quotes.
name = "John"
Booleans (bool
):
Represents either True or False.
is_student = True
Lists (list
):
Ordered, mutable collections of elements.
numbers = [1, 2, 3, 4, 5]
Tuples (tuple
):
Ordered, immutable collections of elements.
coordinates = (3, 4)
Sets (set
):
Unordered collections of unique elements.
unique_numbers = {1, 2, 3, 4, 5}
Dictionaries (dict
):
Unordered collections of key-value pairs.
person = {'name': 'Alice', 'age': 30}
NoneType (None
):
Represents the absence of a value or a null value.
result = None
Complex Numbers (complex
):
Numbers with a real and an imaginary part.
complex_num = 3 + 4j
These are some of the fundamental types, but Python is a dynamically typed language, which means that a variable's type is determined at runtime. Additionally, there are more specialized types and custom classes that can be used to represent specific kinds of data.
In Python, variable types are dynamically inferred based on the assigned values. The interpreter determines the type of a variable at runtime. In the case of age = 25
, the interpreter recognizes 25
as an integer and assigns the variable age
the type of integer. If you were to later assign a string value to age
, the type would change accordingly. This flexibility is a characteristic of dynamic typing in Python.
type()
function can be used to determine the type of a variable. For example, type(age)
returns the type of the variable age
.int()
, float()
, str()
, etc.NoneType
represents the absence of a value or a null value in Python.global
keyword followed by the variable name, e.g., global x
.It's worth noting that Python supports type inference, allowing variables to be assigned values of different types during their lifetime. For example, a variable can be assigned an integer value initially and later be assigned a string. This dynamic typing is one of the features that makes Python flexible and easy to use.