In programming, a data type defines the type of data you’re working with, such as numbers, text, or true/false values. Python, like many other programming languages, includes several basic data types to handle common data forms efficiently. Let’s dive into these types and how to work with them in Python!
What Are Variables?
In Python, variables are placeholders for data values. You can store different types of data in variables, and then refer to these variables throughout your code to access or manipulate their values.
Rules for Naming Variables:
- Use letters, numbers, and underscores.
- Do not start with a number.
- Avoid spaces and Python keywords (see full list of keywords).
- Remember that variable names are case-sensitive (
Name
andname
are different).
# Assigning values to variables
x = 10 # Integer
y = 20.5 # Float
name = "Alice" # String
is_student = True # Boolean
# Multiple assignment in one line
a, b, status = 1, "hello", False
# Assign the same value to multiple variables
p = q = r = 10
Basic Data Types in Python
Here are some fundamental data types you’ll use frequently:
- Integers: Whole numbers without any decimal points. For example:
1
,42
,-7
. - Floating Point Numbers: Numbers with decimal points, allowing for greater precision. For example:
3.14
,0.001
,-15.6
. - Strings: Text data enclosed in quotation marks (
'hello'
,"world"
). Strings are sequences of characters and are commonly used to store words and sentences. - Booleans: Represent logical values,
True
orFalse
. Booleans are useful in conditions and decision-making in programs.
Printing Variables in Python
In Python, you can display the value of a variable using the print()
function. This allows you to output text and values to the console. Here’s a simple example:
# Defining variables
name = "Alice"
age = 21
height = 5.9
is_student = True
# Printing variables
print(name) # Output: Alice
print(age) # Output: 21
print(height) # Output: 5.9
print(is_student) # Output: True
Printing Multiple Variables
You can also print multiple variables at once by separating them with commas within the print()
function.
print("Name:", name, "Age:", age, "Height:", height, "Is student:", is_student)
Output:
Name: Alice Age: 21 Height: 5.9 Is student: True
Using Formatted Strings
Python offers formatted strings (f-strings) to make it easier to print variables within strings.
print(f"My name is {name}, I am {age} years old, and my height is {height} meters.")
Output:
My name is Alice, I am 21 years old, and my height is 5.9 meters.
Exercise: Basic Data Types in Python
Try it yourself!
Use the editor below to declare 4 variables: name
, age
, height
and is_student
with values: Alice, 21, 5.9 and True respectively.
Mutable vs. Immutable Data Types
Data types can also be classified as mutable or immutable:
- Mutable Data Types: These can be changed after they are created. Examples include lists, dictionaries, and sets.
- Immutable Data Types: Once created, their values cannot be changed. Examples include integers, floats, strings, and tuples.
Advanced Data Types
Python provides more complex data types for organizing and manipulating data.
1. Lists: A collection of items stored in a single variable. Lists are mutable, so you can modify them after creating them.
A list is heterogenous
data type. Which means you can use a single list to store any type of data.
List can be created by enclosing items in square brackets []
and items are separated by a comma (,).
fruits = ["apple", "banana", "cherry"]
print(fruits[1])
output:
banana
items = [1, 2, "bottle", True, 22.5] # This is also a valid list
Mutability of Lists:
As mentioned, list items can be changed after declaring the list.
items = ["apple", "banana", "cherry"]
items[0] = "strawberry"
print(items)
output:
["strawberry", "banana", "cherry"]
2. Tuples: Similar to lists, but they are immutable, meaning their values cannot be changed once assigned.
Tuples can be created using round brackets ()
.
colors = ("red", "green", "blue")
Lets see what happens if we try to change the item in a tuple.
TypeError: 'tuple' object does not support item assignment
List after modification: [1, 2, 3, 4]
3. Dictionaries: Dictionaries are based on the concept of hash tables. They store data in a key-value pair.
Every key in a dictionary should be unique.
A dictionary is defined using curly braces {}
. Each key value pair is defined as follows:
person = {
"name": "Alice", # Here 'name' is the key and 'Alice' is the value
"age": 25,
"city": "New York"
}
person["age"] = 26 # Dictionary items are also mutable
Each key-value pair is separated by a comma.
4. Sets: A set stores unique items, similar to mathematical sets. They are mutable and support operations like union, intersection, and difference.
Sets are also defined using curly braces {}
, but the items inside are separated by comma.
unique_numbers = {1, 2, 3, 3, 4}
Be aware that if you define a variable with empty curly braces, it will be declared as a dictionary. To define an empty set you can do it as follows:
my_dictionary = {}
my_set = set()
You can use the above way as an alternative to create lists and dicts too
items = list(1,2,3,4,5)
items2 = tuple("one", "two", "three")
student = dict(name="Alice", age=25, city="New York")
numbers = set(1,2,3,4,5,6,7,8)
Updating Variable Values
Variables in Python can be easily updated, allowing you to modify stored data dynamically.
x = 10
print(x) # Output: 10
x = 20 # Updating the value of x
print(x) # Output: 20
Play with variables
Now that you have understood the concept of datatypes and variables. Use the editor below to play around and try different things as you please.