Python Variables
Learn to store and manipulate data using variables in Python
📦 Understanding Variables
Variables are containers for storing data values. In Python, variables are created when you assign a value to them. They're like labeled boxes where you can store different types of information and retrieve them later.
# Creating a variable
name = "John"
print(name) # Output: John
Creating Variables
Python has no command for declaring a variable. A variable is created the moment you first assign a value to it.
String Variables
Store text data
name = "Alice"
message = 'Hello, World!'
Numeric Variables
Store numbers (int, float)
age = 25
height = 5.6
Boolean Variables
Store True/False values
is_student = True
has_license = False
Dynamic Typing
Type changes automatically
x = 10 # int
x = "text" # now string
Variable Types
Python variables can store different types of data. The type is determined automatically based on the value assigned.
String (str)
Text data enclosed in quotes
message = "Hello, World!"
single_quotes = 'Python is awesome'
multiline = """This is a
multiline string"""
Integer (int)
Whole numbers without decimals
count = 42
negative = -17
zero = 0
Float (float)
Numbers with decimal points
price = 19.99
pi = 3.14159
scientific = 2.5e4 # 25000.0
Boolean (bool)
True or False values
is_active = True
is_complete = False
result = 5 > 3 # True
Checking Variable Types
You can check the type of any variable using the
type()
function.
# Create variables of different types
name = "Python"
version = 3.11
is_popular = True
users = 1000000
# Check their types
print(f"name is of type: {type(name)}") #
print(f"version is of type: {type(version)}") #
print(f"is_popular is of type: {type(is_popular)}")#
print(f"users is of type: {type(users)}") #
# You can also use isinstance() to check if a variable is of a specific type
print(f"Is name a string? {isinstance(name, str)}") # True
print(f"Is version an integer? {isinstance(version, int)}")# False
print(f"Is users a number? {isinstance(users, (int, float))}")# True
Variable Naming Rules
Python has specific rules for naming variables and follows conventions that make code more readable.
✅ Valid Variable Names
name = "Alice"
age = 25
user_name = "alice123"
first_name = "Alice" # snake_case (preferred)
PI = 3.14159 # constants in UPPERCASE
❌ Invalid Variable Names
# These will cause SyntaxError
2name = "Alice" # starts with number
first-name = "Alice" # contains hyphen
class = "Python" # reserved keyword
Variable Naming Rules
Python has specific rules for naming variables that you must follow:
Valid Names
# Valid variable names
name = "Alice"
age = 25
first_name = "John"
lastName = "Doe" # camelCase
_private = "hidden"
PI = 3.14159
user123 = "user"
my_var_2 = "value"
Invalid Names
# Invalid variable names (will cause errors)
# 2name = "Alice" # Can't start with number
# first-name = "John" # Can't contain hyphens
# class = "Python" # Can't use reserved keywords
# my name = "Alice" # Can't contain spaces
# @variable = "value" # Can't contain special characters
🎯 Naming Best Practices
Multiple Assignment
Python allows you to assign values to multiple variables in different ways:
🔹 Assign Same Value to Multiple Variables
x = y = z = 10
print(f"x={x}, y={y}, z={z}") # x=10, y=10, z=10
🔹 Assign Different Values to Multiple Variables
a, b, c = 1, 2, 3
print(f"a={a}, b={b}, c={c}") # a=1, b=2, c=3
🔹 Unpacking a List or Tuple
coordinates = (10, 20)
x_pos, y_pos = coordinates
print(f"Position: ({x_pos}, {y_pos})") # Position: (10, 20)
🔹 Swapping Variables
first = "Hello"
second = "World"
print(f"Before swap: first='{first}', second='{second}'")
first, second = second, first # Swap values
print(f"After swap: first='{first}', second='{second}'")
🔹 Unpacking with Asterisk
numbers = [1, 2, 3, 4, 5]
first, *middle, last = numbers
print(f"First: {first}") # First: 1
print(f"Middle: {middle}") # Middle: [2, 3, 4]
print(f"Last: {last}") # Last: 5
Global vs Local Variables
Variables can have different scopes - they can be global (accessible everywhere) or local (accessible only within a function).
# Example 1: Basic Global vs Local
message = "Hello World!" # Global variable
def greet():
name = "Alice" # Local variable
print(message) # Can access global
print(name) # Can access local
greet()
# Example 2: Using global keyword
score = 0
def update_score():
global score
score += 10
print(f"Score: {score}")
update_score() # Score: 10
print(f"Final score: {score}") # Final score: 10
Variable Operations
You can perform various operations with variables depending on their types:
Numeric Operations
a = 10
b = 3
print(f"Addition: {a + b}") # 13
print(f"Subtraction: {a - b}") # 7
print(f"Multiplication: {a * b}")# 30
print(f"Division: {a / b}") # 3.33...
print(f"Floor Division: {a // b}")# 3
print(f"Modulus: {a % b}") # 1
print(f"Exponentiation: {a ** b}")# 1000
String Operations
first_name = "John"
last_name = "Doe"
# String concatenation
full_name = first_name + " " + last_name
print(full_name) # John Doe
# String repetition
greeting = "Hello! " * 3
print(greeting) # Hello! Hello! Hello!
# String formatting
age = 25
message = f"My name is {full_name} and I'm {age} years old"
print(message)
Boolean Operations
is_sunny = True
is_warm = False
# Logical operations
print(f"Sunny AND Warm: {is_sunny and is_warm}") # False
print(f"Sunny OR Warm: {is_sunny or is_warm}") # True
print(f"NOT Sunny: {not is_sunny}") # False
# Comparison operations
x = 5
y = 10
print(f"x > y: {x > y}") # False
print(f"x < y: {x < y}") # True
print(f"x == y: {x == y}") # False
List Operations
fruits = ["apple", "banana"]
vegetables = ["carrot", "broccoli"]
# List concatenation
food = fruits + vegetables
print(food) # ['apple', 'banana', 'carrot', 'broccoli']
# List repetition
repeated = ["hello"] * 3
print(repeated) # ['hello', 'hello', 'hello']
# List modification
fruits.append("orange")
print(fruits) # ['apple', 'banana', 'orange']
🏋️ Practice Exercise: Personal Budget Calculator
Let's create a practical example that demonstrates various variable concepts:
# Simple Variable Examples
# Shows basic variable usage in Python
# String variables
name = "John"
greeting = "Hello"
# Number variables
age = 25
height = 1.75
# Boolean variable
is_student = True
# Basic calculations
birth_year = 2024 - age
next_year_age = age + 1
# Using variables together
message = f"{greeting}, {name}!"
height_in_feet = height * 3.28
# Display information
print("=" * 30)
print("Personal Information")
print("=" * 30)
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Height: {height_in_feet:.1f} feet")
print(f"Birth Year: {birth_year}")
print(f"Next year's age: {next_year_age}")
print(f"Student: {'Yes' if is_student else 'No'}")
print(f"Message: {message}")
# Show variable types
print("\nVariable Types:")
print(f"name is type: {type(name)}")
print(f"age is type: {type(age)}")
print(f"height is type: {type(height)}")
print(f"is_student is type: {type(is_student)}")
Real-World Example: Student Information System
Let's create a practical example that demonstrates various variable concepts: