A variable in Python is a name that is used to refer to memory location. It is a way to store data that can be used and manipulated throughout your program.
Note: Python supports unlimited variable length, we keep the maximum length to 79 characters.
Declaring Variables
In Python, you don’t need to explicitly declare the type of a variable. You just assign a value to it, and Python automatically knows what type it is.
Example:
# Assigning an integer to a variable
age = 25
print(age) # Output: 25
# Assigning a floating point number to a variable
height = 5.9
print(height) # Output: 5.9
# Assigning a string to a variable
name = "Alice"
print(name) # Output: Alice
# Assigning a boolean to a variable
is_student = True
print(is_student) # Output: True
Variable Naming Rules
- Variable names must start with a letter (a-z, A-Z) or an underscore (_).
- The rest of the name can contain letters, numbers, or underscores.
- Variable names are case-sensitive (
age
andAge
are different).
Example of Valid and Invalid Variable Names:
# Valid variable names
my_var = 10
_var = 20
var123 = 30
# Invalid variable names
123var = 40 # Starts with a number
my-var = 50 # Contains a hyphen
my var = 60 # Contains a space
Changing the Value of a Variable
You can change the value of a variable at any time in your program.
number = 10
print(number) # Output: 10
number = 20
print(number) # Output: 20
Multiple Assignments:
You can assign values to multiple variables in a single line.
a = b = c = 1 #single value to multiple variables a,b = 1, 2 #multiple value to multiple variable a,b = b,a #value of a and b is swapped
Using Variables in Expressions
You can use variables in expressions just like you use literal values.
x = 10
y = 5
# Adding variables
result = x + y
print(result) # Output: 15
# Subtracting variables
result = x - y
print(result) # Output: 5
# Multiplying variables
result = x * y
print(result) # Output: 50
# Dividing variables
result = x / y
print(result) # Output: 2.0
Variable Scope and Lifetime:
- Local Variable
def func(): x=8 print(x) func() print(x) #error will be shown
- Global Variable
x = 8 def fun(): print(x) #Calling variable 'x' inside func() func() print(x) #Calling variable 'x' outside func()
Variables are fundamental in programming, allowing you to store and manipulate data dynamically. In Python, declaring and using variables is straightforward due to its dynamic typing. Remember to follow the variable naming rules and use them appropriately within your code to keep it clean and readable.