Python Variables
Python Variables – A Brief Overview
What Are Variables?
Variables store data that can be referenced and manipulated. Python uses dynamic typing, meaning variables don’t need explicit type declarations.
Rules for Naming Variables
- Can contain letters, digits, and underscores (_), but cannot start with a digit.
- Case-sensitive (
myVar
and myvar
are different).
- Cannot use Python keywords (e.g.,
if
, class
).
Assigning Values
Basic Assignment:
x = 5
name = "John"
Multiple Assignments:
a, b, c = 1, 2, 3
Same Value to Multiple Variables:
x = y = z = 10
Type Casting
Convert between data types using:
int()
, float()
, str()
Example:
n = int("10")
f = float(5)
s = str(25)
Checking Variable Type
Use type(variable)
to check data type.
Scope of Variables
Local Variables: Exist inside functions only.
def f():
a = "I am local"
print(a)
Global Variables: Accessible throughout the program using global
keyword.
a = "I am global"
def f():
global a
a = "Modified globally"
print(a)
Object References
- Variables reference objects, not store them directly.
- Changing a variable’s value creates a new reference.
Deleting Variables
Use del variable_name
to remove a variable.
x = 10
del x
Practical Examples
Swapping Variables:
a, b = b, a
Counting Characters in a String:
word = "Python"
length = len(word)
print("Length of the word:", length)
Python Variables – Summary
- Variables store data and are dynamically typed.
- Follow naming rules and use
int()
, float()
, and