Python 3 – Variable Types
In programming, variables are used to store and manipulate data. Python is a dynamically typed language, which means that the interpreter automatically identifies the data type based on the value assigned to the variable.
There are several data types in Python. In this article, we will discuss the most commonly used data types and their characteristics.
Numeric Data Types
Numeric data types in Python are int, float, and complex.
Integers
Integers are whole numbers that can be positive, negative, or zero. In Python, integers have unlimited precision, which means they can be arbitrarily large or small.
# Example of integer
x = 10
print(x)
Output:
10
Floating-Point Numbers
Floating-point numbers, or simply floats, are numbers that have a decimal point. They can represent both rational and irrational numbers.
# Example of float
y = 3.14
print(y)
Output:
3.14
Complex Numbers
Complex numbers are numbers that have a real part and an imaginary part. They are represented in Python using the j or J suffix.
# Example of complex number
z = 2 + 3j
print(z)
Output:
(2+3j)
Sequence Data Types
Sequence data types in Python include strings, lists, and tuples.
Strings
Strings are used to represent textual data in Python. They can be enclosed in single, double, or triple quotes.
# Example of string
text = "Hello, World!"
print(text)
Output:
Hello, World!
Lists
Lists are used to store an ordered collection of items. They are similar to arrays in other programming languages. Lists can contain elements of different data types.
# Example of list
lst = [1, 2, 3, "four", 5.0]
print(lst)
Output:
[1, 2, 3, 'four', 5.0]
Tuples
Tuples are similar to lists, but they are immutable, which means their values cannot be changed after they are created. Tuples are often used to represent fixed collections of data.
# Example of tuple
tpl = (1, 2, 3, "four", 5.0)
print(tpl)
Output:
(1, 2, 3, 'four', 5.0)
Boolean Data Type
Boolean data type in Python is bool. It has two possible values: True and False. Boolean values are often used in conditional statements and loops.
# Example of boolean
x = True
y = False
print(x, y)
Output:
True False
Type Conversion
Python allows us to convert one data type to another using type casting. Type casting is useful when we need to perform operations on data of different types.
# Example of type conversion
x = 10
y = float(x)
print(x, y)
Output:
10 10.0
Conclusion
In this article, we discussed the most commonly used variable types in Python. We learned about numeric data types, sequence data types, boolean data type, and type conversion. Understanding these data types is essential to effectively use Python for programming.