Python is a dynamically typed programming language, which means that the data type of a variable is determined at runtime, rather than at compile-time. Python supports a wide range of data types that can be used to represent different kinds of data. In this blog post, we will explore the various data types in Python and how to use them.
- Numeric Data Types
Python has three numeric data types – int, float, and complex. Integers are whole numbers, positive or negative, without decimals. Floats are decimal numbers, while complex numbers are represented as a sum of a real part and an imaginary part.
Here's an example of how to declare and use these data types in Python:
x = 5 # int
y = 3.14 # float
z = 2 + 3j # complex
print(x)
print(y)
print(z)
- String Data Type
Strings are used to represent text data in Python. They are declared using single quotes or double quotes.
Here's an example of how to declare and use a string in Python:
name = 'Dhananjay'
print(name)
- Boolean Data Type
Boolean data types are used to represent true or false values. In Python, the keywords True and False are used to represent these values.
Here's an example of how to declare and use a boolean in Python:
x = True
y = False
print(x)
print(y)
- List Data Type
Lists are used to store collections of items in Python. They are declared using square brackets and can contain any combination of data types.
Here's an example of how to declare and use a list in Python:
fruits = ['apple', 'banana', 'cherry']
print(fruits)
print(fruits[1]) # Accessing an element in the list
- Tuple Data Type
Tuples are similar to lists but are immutable, meaning that their contents cannot be changed after they are created. They are declared using parentheses.
Here's an example of how to declare and use a tuple in Python:
fruits = ('apple', 'banana', 'cherry')
print(fruits)
print(fruits[1]) # Accessing an element in the tuple
- Set Data Type
Sets are used to store collections of unique items in Python. They are declared using curly braces.
Here's an example of how to declare and use a set in Python:
fruits = {'apple', 'banana', 'cherry'}
print(fruits)
Output:
{'apple', 'banana', 'cherry'}
- Dictionary Data Type
Dictionaries are used to store key-value pairs in Python. They are declared using curly braces and colons to separate the keys and values.
Here's an example of how to declare and use a dictionary in Python:
person = {
'name': 'John Doe',
'age': 30,
'location': 'New York'
}
print(person)
print(person['name']) # Accessing a value using its key
Output:
{'name': 'John Doe', 'age': 30, 'location': 'New York'}
John Doe
In conclusion, Python has a rich set of data types that can be used to represent different kinds of data.