Variables are containers for storing data values.
Unlike many other programming languages, Python has no command for declaring a variable. A variable is created when you assign a value to it.
Creating Variables
Example:
name = "John"
age = 25
print(name)
print(age)
Output:
John
25
Variable Names
A variable can have a short name or a more descriptive name.
Example:
x = 5
name = "John"
user_age = 25
Rules for Variable Names
A variable name:
- Must start with a letter or the underscore character (
_) - Cannot start with a number
- Can only contain letters, numbers, and underscores
- Is case-sensitive
Valid variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Invalid variable names:
2myvar = "John"
my-var = "John"
my var = "John"
Assigning Multiple Values
Python allows you to assign values to multiple variables in one line.
Example:
x, y, z = "Apple", "Banana", "Cherry"
print(x)
print(y)
print(z)
Output:
Apple
Banana
Cherry
One Value to Multiple Variables
You can assign the same value to multiple variables.
Example:
x = y = z = "Python"
print(x)
print(y)
print(z)
Output:
Python
Python
Python
Unpacking a Collection
You can extract values from a list into variables.
Example:
fruits = ["Apple", "Banana", "Cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
Output:
Apple
Banana
Cherry
Output Variables
Use the print() function to display variables.
Example:
name = "John"
print(name)
You can also combine text and variables:
name = "John"
print("My name is", name)
Output:
My name is John
Variable Types
Python automatically determines the data type of a variable.
Example:
name = "John" # String
age = 25 # Integer
price = 99.99 # Float
is_active = True # Boolean
Change Variable Type
A variable can change its type after being created.
Example:
x = 5
x = "John"
print(x)
Output:
John
Case-Sensitive Variables
Variable names are case-sensitive.
Example:
name = "John"
Name = "Peter"
print(name)
print(Name)
Output:
John
Peter
Here, name and Name are treated as different variables.
Summary
- Variables are used to store data.
- Variables are created when a value is assigned.
- Python does not require variable declaration.
- Variable names are case-sensitive.
- Multiple values can be assigned in one line.
- A variable can change its data type during execution.