Variables in Python
Variables store data values. Python has no command for declaring a variable - it is created when you assign a value to it.
Naming Rules
# Valid variable names
my_name = "Alice"
_private = "hidden"
camelCase = True
myVar2 = 42
# Invalid variable names (causes error)
# 2myvar = 42 # cannot start with number
# my-var = 42 # no hyphens
# my var = 42 # no spaces
Data Types
# Numeric types
x = 42 # int
y = 3.14 # float
z = 2 + 3j # complex
# Text type
name = "Alice" # str
# Boolean
is_valid = True # bool
# Sequence types
fruits = ["apple", "banana"] # list
coords = (10, 20) # tuple
letters = range(5) # range
# Mapping type
person = {"name": "Alice", "age": 25} # dict
# Set types
unique = {1, 2, 3} # set
frozen = frozenset([1, 2, 3]) # frozenset
# None
result = None # NoneType
Type Conversion
# Implicit conversion
x = 10 # int
y = 3.14 # float
z = x + y # float (13.14)
# Explicit conversion
s = "42"
n = int(s) # string to int
f = float(s) # string to float
l = list("hello") # string to list: ["h","e","l","l","o"]
Multiple Assignment
# Assign multiple variables
a, b, c = 1, 2, 3
# Same value
x = y = z = 0
# Unpack a list
colors = ["red", "green", "blue"]
r, g, b = colors
Scope
# Global vs Local
x = 10 # global
def my_func():
y = 20 # local
print(x) # can read global
print(y)
my_func()
print(x) # OK
# print(y) # Error: y is not defined
Summary
- Python has several built-in data types: int, float, str, bool, list, tuple, dict, set
- Type conversion is done with int(), float(), str(), list(), etc.
- Multiple variables can be assigned in one line
- Variables inside functions are local by default
YouTip