Variables & Data Types

What are Variables?

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'>

Python Data Types

Data TypeDescriptionExample
strText/String"Hello World"
intInteger numbers42, -10, 0
floatDecimal numbers3.14, -2.5
boolTrue/False valuesTrue, False
listOrdered collection[1, 2, 3]
dictKey-value pairs{"name": "Bob"}

Working with Strings

# 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

Numbers and Math Operations

# 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 and Logic

# 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
💡 Tip: Use descriptive variable names like user_age instead of a. This makes your code more readable and maintainable.
⚠️ Remember: Python is case-sensitive! Name and name are different variables.

Variable Naming Rules

# 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
Next: Control Flow →