Creating Variables
Python uses dynamic typing, meaning you don't have to declare what type a variable is. Just assign a value and Python figures it out.
name = "Alice"
age = 25
price = 19.99
logged_in = False
Try it Yourself โ
Naming Rules
Variable names must start with a letter or underscore, followed by letters, numbers, or underscores. They cannot start with a number and cannot use Python keywords.
my_var = 10
_private = 20
var2 = 30
myVariableName = 40 # camelCase works too
Try it Yourself โ
Changing Values
Variables can be reassigned to different values, even different types, at any time.
x = 10
print(x)
x = "Now I'm a string"
print(x)
Try it Yourself โ
Multiple Assignment
You can assign values to multiple variables in one line. This is clean and convenient.
a, b, c = 1, 2, 3
print(a)
print(b)
print(c)
Try it Yourself โ
Swapping Variables
Swapping two variables is incredibly elegant in Python. No temporary variable needed.
x = 5
y = 10
x, y = y, x
print(x)
print(y)
Try it Yourself โ
Variables in Strings
Use f-strings to embed variable values directly into strings. Put an f before the opening quote and use curly braces around variable names.
name = "Bob"
age = 30
message = f"{name} is {age} years old"
print(message)
Try it Yourself โ
Deleting Variables
Use the del keyword to remove a variable entirely. After deletion, the variable no longer exists.
x = 100
print(x)
del x
print(x) # This will cause an error
Try it Yourself โ