Variables are containers that store data values. In Python, you don't need to declare variables explicitly - they're created when you assign a value.
# Creating variables
name = "Alice" # String variable
age = 25 # Integer variable
height = 5.6 # Float variable
is_student = True # Boolean variable
print(name) # Output: Alice
print(type(name)) # Output: <class 'str'>
Data Type | Description | Example |
---|---|---|
str | Text/String | "Hello World" |
int | Integer numbers | 42, -10, 0 |
float | Decimal numbers | 3.14, -2.5 |
bool | True/False values | True, False |
list | Ordered collection | [1, 2, 3] |
dict | Key-value pairs | {"name": "Bob"} |
# String creation
single_quotes = 'Hello'
double_quotes = "World"
multiline = """This is a
multiline string"""
# String operations
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name # Concatenation
print(f"Hello, {full_name}!") # f-string formatting
# String methods
text = "python programming"
print(text.upper()) # PYTHON PROGRAMMING
print(text.capitalize()) # Python programming
print(text.replace("python", "Python")) # Python programming
print(len(text)) # 18
# Integer operations
x = 10
y = 3
print(x + y) # Addition: 13
print(x - y) # Subtraction: 7
print(x * y) # Multiplication: 30
print(x / y) # Division: 3.333...
print(x // y) # Floor division: 3
print(x % y) # Modulus: 1
print(x ** y) # Exponentiation: 1000
# Float operations
pi = 3.14159
radius = 5
area = pi * radius ** 2
print(f"Circle area: {area:.2f}") # Circle area: 78.54
# Boolean values
is_sunny = True
is_raining = False
# Comparison operators
age = 18
print(age >= 18) # True
print(age < 21) # True
print(age == 18) # True
print(age != 20) # True
# Logical operators
has_license = True
has_car = False
can_drive = has_license and has_car # False
can_travel = has_license or has_car # True
is_not_ready = not has_license # False
user_age
instead of a
. This makes your code more readable and maintainable.
Name
and name
are different variables.
# Valid variable names
user_name = "Alice"
_private_var = 42
firstName = "John"
age2 = 25
# Invalid variable names (will cause errors)
# 2age = 25 # Starts with number
# user-name = "Bob" # Contains hyphen
# if = 10 # Uses Python keyword