Python Variables
In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value.
- Unlike Java and many other languages, Python variables do not require explicit declaration of type.
- The type of the variable is inferred based on the value assigned.
x = 5
name = "Samantha"
print(x)
print(name)
Output
5 Samantha
Rules for Naming Variables
To use variables effectively, we must follow Python’s naming rules:
- Variable names can only contain letters, digits and underscores (_).
- A variable name cannot start with a digit.
- Variable names are case-sensitive like myVar and myvar are different.
- Avoid using Python keywords like if, else, for as variable names.
Below listed variable names are valid:
age = 21 _colour = "lilac" total_score = 90
Below listed variables names are invalid:
1name = "Error" # Starts with a digit class = 10 # 'class' is a reserved keyword user-name = "Doe" # Contains a hyphen
Assigning Values to Variables
Basic Assignment: Variables in Python are assigned values using the = operator.
x = 5 y = 3.14 z = "Hi"
Dynamic Typing: Python variables are dynamically typed, meaning the same variable can hold different types of values during execution.
x = 10 x = "Now a string"
Multiple Assignments
Assigning Same Value: Python allows assigning the same value to multiple variables in a single line, which can be useful for initializing variables with the same value.
a = b = c = 100
print(a, b, c)
Output
100 100 100
Assigning Different Values: We can assign different values to multiple variables simultaneously, making the code concise and easier to read.
0 Comments