To create a variable in Python, you simply use the assignment operator (=) to assign a value to a variable name. Python is dynamically typed, meaning you don't need to explicitly declare the variable's data type (like int
, string
, or float
). Python infers the type based on the value you assign.
Basic Syntax
The general syntax for creating a variable is:
variable_name = value
Examples
Here are some examples of creating variables with different data types:
-
Integer:
age = 30
-
String:
name = "Alice"
-
Float:
price = 99.99
-
Boolean:
is_valid = True
-
List:
numbers = [1, 2, 3, 4, 5]
-
Tuple:
coordinates = (10, 20)
-
Dictionary:
person = {"name": "Bob", "age": 40}
Variable Naming Rules
When naming variables in Python, follow these rules:
- Variable names must start with a letter (a-z, A-Z) or an underscore (_).
- The remaining characters can be letters, numbers, or underscores.
- Variable names are case-sensitive (
age
andAge
are different variables). - Avoid using Python keywords (like
if
,else
,for
,while
,def
,class
, etc.) as variable names.
Best Practices
- Use descriptive variable names to improve code readability. For example,
user_age
is better thana
. - Follow a consistent naming convention (e.g., snake_case for variables and functions).
- Avoid creating variables with the same name as built-in functions or modules.
In essence, creating a variable in Python is as simple as assigning a value to a name using the =
operator. Python handles the type inference automatically, making the process straightforward and flexible.