Python Variables
1. Variable Assignment:
You assign a value to a variable using the equal (=
) operator. The variable name comes on the left, and the value comes on the right.
# Variable assignment
x = 5
name = "John"
2. Variable Names:
Variable names can consist of letters (both uppercase and lowercase), numbers, and underscores. They cannot start with a number. Python follows a case-sensitive naming convention, so myVar
and myvar
are considered different variables.
my_var = 10
count = 3
3. Data Types:
Python is dynamically typed, which means you don't need to declare the data type of a variable explicitly. The interpreter infers the data type based on the assigned value.
age = 25 # Integer
height = 5.9 # Float
message = "Hello, World!" # String
4. Reassignment:
You can change the value of a variable by assigning a new value to it.
x = 5
x = x + 1 # Incrementing x
5. Multiple Assignments:
You can assign values to multiple variables in a single line.
a, b, c = 1, 2, 3
6. Constants:
Although Python doesn't have a built-in constant type, it is a convention to use uppercase names for constants to indicate that the value should not be changed.
PI = 3.14
7. Type Function:
You can use the type()
function to determine the type of a variable.
x = 10
print(type(x)) # Output: <class 'int'>
8. None Type:
Python has a special None
type that represents the absence of a value or a null value.
result = None
Variables are a fundamental concept in programming, allowing you to store and manipulate data as your program runs. Understanding how to use variables effectively is crucial for writing expressive and functional Python code.