Variables
In programming, a variable is used to store information that can be used later in your program.
You can think of a variable as a labeled container for data.
Creating variables
In Python, you create a variable by assigning a value to a name:
name = "Alice"
age = 22
height = 1.75
Python automatically determines the type of each variable, so you do not need to declare it explicitly.
Common data types
Here are some of the most commonly used data types in Python:
int– whole numbers (e.g. 1, 10, 100)float– decimal numbers (e.g. 1.5, 3.14)str– text (e.g. "hello")bool– logical values (TrueorFalse)
In addition to basic data types, Python also provides more complex data structures that allow you to store collections of values.
Working with variables
You can use variables in expressions and print their values:
name = "Alice"
age = 22
print(name)
print(age)
You can also update a variable:
age = 22
age = age + 1
print(age)
Simple example
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name)
Lists (arrays)
A list is an ordered collection of values. Lists are mutable, which means you can change their contents.
numbers = [1, 2, 3, 4]
names = ["Alice", "Bob", "Charlie"]
You can access elements using their index:
print(numbers[0]) # 1
Tuples
A tuple is similar to a list, but it is immutable. This means that once it is created, its values cannot be changed.
coordinates = (10, 20)
Tuples are often used when you want to group related data that should not be modified.
Dictionaries
A dictionary stores data as key-value pairs.
user = {
"name": "Alice",
"age": 22
}
You can access values using their keys:
print(user["name"]) # Alice
Dictionaries are useful when you want to associate values with meaningful labels instead of positions.
Exercise 1
Create variables for:
- your name
- your age
- your favorite programming language
Then print them using print(). The format should be {name} - {age} - {favorite_programming_language}.
To concatenate strings, use the '+' operator as shown above. Concatenating strings means combining two or more strings together.
Exercise 2
Create a list and a dictionary:
- a list of your favorite programming languages
- a dictionary that stores your name and age
Example:
languages = ["Python", "JavaScript", "C++"]
user = {
"name": "Alice",
"age": 22
}
Print:
- the first language from the list
- your name from the dictionary
This will help you understand how to work with collections of data.
Notes
- Variable names should be descriptive (e.g.
user_ageinstead ofx) - Python is case-sensitive (
nameandNameare different variables) - Avoid using spaces in variable names; use underscores instead