Variables in Python
In Python, a variable is a named reference to a value stored in memory. Variables are used to store data which can be
manipulated and referenced throughout the program. Here's a brief overview of variables in Python:
. Variable Naming:
- Variable names can contain letters (a-z, A-Z), digits (0-9), and underscores (_).
- They must begin with a letter or an underscore.
- Python is case-sensitive, so `my_variable` and `My_Variable` are different variables.
Assigning Values to Variables:
- You can assign a value to a variable using the assignment operator `=`.
- Python automatically determines the data type of the variable based on the assigned value.
Data Types:
- Python is dynamically typed, meaning you don't have to explicitly declare the type of a variable.
- Common data types include integers, floats, strings, lists, tuples, dictionaries, etc.
**Example**:
```python
# Assigning values to variables
name = "John"
age = 25
height = 5.11
is_student = True
# Printing variables
print("Name:", name)
print("Age:", age)
print("Height:", height)
print("Is Student:", is_student)
```
Variable Reassignment:
- You can change the value of a variable by assigning it a new value.
```python
x=5
print(x) # Output: 5
x = 10
print(x) # Output: 10
```
Scope:
- The scope of a variable determines where in the code it can be accessed.
- Variables defined within a function are usually local to that function, while variables defined outside of any
function (at the module level) are considered global and can be accessed from any function within that module.
Constants:
- Although Python doesn't have built-in constants, developers often use variables in ALL_CAPS to indicate that a
variable should be treated as a constant (i.e., its value should not change).
```python
PI = 3.14159
GRAVITY = 9.8
```
Variables are fundamental to programming in Python, and understanding how they work is crucial for writing
effective and efficient code.