When it comes to programming in Python, understanding data types is essential. Python is a dynamically typed language, which means that variables can hold values of different types. In this tutorial, we will explore how to write different data types in Python.
Numbers
In Python, numbers can be integers or floating-point numbers. Integers are whole numbers, such as 1, 25, or -10.
Floating-point numbers are decimal numbers, such as 3.14 or -0.5.
To assign a number to a variable, you can simply use the assignment operator (=). For example:
x = 10
pi = 3.14
Strings
A string is a sequence of characters enclosed in single quotes (”) or double quotes (“”). For example:
name = 'John'
message = "Hello, World!"
You can also use triple quotes (”’ ”’) or (“””) to create multi-line strings:
paragraph = '''
This is a multi-line string.
It can span across multiple lines.
'''
Boolean
The Boolean data type represents the truth values True and False.
To assign a Boolean value to a variable in Python, you can use the keywords True and False:
is_sunny = True
is_raining = False
List
A list is an ordered collection of items enclosed in square brackets ([]). Each item in the list is separated by a comma.
To create a list in Python:
fruits = ['apple', 'banana', 'orange']
numbers = [1, 2, 3, 4, 5]
Tuple
A tuple is similar to a list but is immutable, meaning its values cannot be changed once assigned. Tuples are enclosed in parentheses (()).
To create a tuple:
coordinates = (10, 20)
colors = ('red', 'green', 'blue')
Dictionary
A dictionary is an unordered collection of key-value pairs enclosed in curly braces ({}). Each key-value pair is separated by a colon (:), and each pair is separated by a comma.
To create a dictionary:
person = {
'name': 'John',
'age': 30,
'city': 'New York'
}
Conclusion
In this tutorial, we have covered the basic data types in Python. Remember that Python is dynamically typed, allowing variables to hold different types of values. Understanding data types is fundamental to writing effective and efficient Python code.