Introduction
Variables are used to store data that can be used and manipulated throughout a program. In Python, variables do not require explicit declaration to reserve memory space. The declaration happens automatically when a value is assigned to a variable.
Variable Naming Rules
- Must start with a letter or an underscore (_): The first character cannot be a digit.
- Can contain letters, digits, and underscores: After the first character, variable names can include any combination of these characters.
- Case-sensitive:
age
,Age
, andAGE
are three different variables. - Cannot be a reserved keyword: Python has reserved words that cannot be used as variable names (e.g.,
False
,class
,return
,is
,and
).
Examples:
name = "John"
_age = 25
salary1 = 50000
Assigning Values to Variables
In Python, you can assign values to variables using the =
operator.
Examples:
x = 5
y = "Hello"
is_active = True
Multiple Assignments
You can assign values to multiple variables in one line.
Examples:
a, b, c = 1, 2, 3
name, age, city = "Alice", 30, "New York"
You can also assign the same value to multiple variables.
Example:
x = y = z = 10
Variable Types
Python variables can store different types of data, such as numbers, strings, and booleans. Python automatically assigns the appropriate type based on the value.
Examples:
-
Integer:
age = 25
-
Float:
salary = 45000.50
-
String:
name = "John"
-
Boolean:
is_active = True
Type Casting
You can change the type of a variable using type casting. Python provides built-in functions for type casting: int()
, float()
, str()
, etc.
Examples:
# Integer to float
x = 5
y = float(x) # y will be 5.0
# Float to integer
a = 10.5
b = int(a) # b will be 10
# Integer to string
num = 100
num_str = str(num) # num_str will be "100"
Checking Variable Type
You can check the type of a variable using the type()
function.
Example:
x = 5
print(type(x)) # Output: <class 'int'>
y = "Hello"
print(type(y)) # Output: <class 'str'>
Conclusion
Variables are fundamental in Python programming, allowing you to store and manipulate data. Understanding how to name variables, assign values, and check types is crucial for writing effective Python programs. By following the rules and practices outlined in this chapter, you can use variables efficiently in your Python projects.