Variables and Data Types in Python
In Python, variables are used to store data values. Python is dynamically typed, meaning you don't need to declare the type of a variable explicitly. Variables can hold different types of data, such as numbers, strings, booleans, lists, tuples, and dictionaries.
Declaring Variables
Variables in Python are created when you assign a value to them. You can reassign variables to different types of data.
x = 10 # Integer
name = "Alice" # String
is_student = True # Boolean
Common Data Types
- int: Whole numbers (e.g.,
10
,-5
). - float: Decimal numbers (e.g.,
3.14
,-0.001
). - str: Text data (e.g.,
"Hello"
,'Python'
). - bool: True or False values.
- list: Ordered collection of elements (e.g.,
[1, 2, 3]
). - tuple: Immutable ordered collection (e.g.,
(1, 2, 3)
). - dict: Key-value pairs (e.g.,
{"name": "Alice", "age": 25}
). - set: Unordered collection of unique elements (e.g.,
{1, 2, 3}
).
Example:
age = 25
name = "Alice"
is_student = True
scores = [90, 85, 95]
person = {"name": "Alice", "age": 25}
print("Name:", name)
print("Age:", age)
print("Is Student:", is_student)
Type Conversion
Python allows you to convert one data type to another using built-in functions like int()
,
float()
, str()
, and bool()
.
# Converting between types
num_str = "10"
num_int = int(num_str) # Convert string to integer
num_float = float(num_int) # Convert integer to float
bool_val = bool(num_float) # Convert float to boolean
print(num_int, num_float, bool_val)
Dynamic Typing
Python is dynamically typed, meaning the type of a variable is determined at runtime and can change.
x = 10 # x is an integer
x = "Hello" # x is now a string
x = [1, 2, 3] # x is now a list
Variable Naming Rules
Variable names in Python must follow these rules:
- Must start with a letter or underscore (
_
). - Can only contain letters, numbers, and underscores.
- Cannot be a reserved keyword (e.g.,
if
,else
,for
). - Are case-sensitive (e.g.,
name
andName
are different).
# Valid variable names
my_var = 10
_var2 = "Hello"
myVar3 = 3.14
# Invalid variable names
# 2var = 10 # Error: Cannot start with a number
# my-var = 20 # Error: Cannot contain hyphens
Constants
Although Python doesn't have built-in support for constants, it's a convention to use uppercase names for variables that should not be changed.
PI = 3.14159
GRAVITY = 9.81
# Attempting to change a constant (not enforced)
PI = 3.14 # This is allowed but not recommended
Multiple Assignment
Python allows you to assign multiple variables in a single line.
x, y, z = 10, 20, 30
print(x, y, z) # Output: 10 20 30
# Swapping variables
x, y = y, x
print(x, y) # Output: 20 10
Next: Control Structures