Python Variables
In Python, variables are used to store and manipulate data. They act as placeholders that can hold different types of values, such as numbers, strings, lists, or objects. Variables allow you to refer to the data by a name instead of using the actual value.
Creating Variables
Here’s how you can define and use variables in Python:
1 |
variable_name = value |
Variables have a name and a value. To create a variable, you just need to give it a name, then connect the name with the value you need to store using the equal sign =.
The = is the assignment operator. In this syntax, you assign a value to the variable_name.
Rules for creating variables in Python:
- Variable names can contain only letters, numbers, and underscores (
_
). They can start with a letter or an underscore (_
), not with a number. - Variable names cannot contain spaces. To separate words in variables, you use underscores for example
city_name
. - Variable names cannot be the same as keywords, reserved words, and built-in functions in Python.
The following guidelines help you define good variable names:
- Variable names should be concise and descriptive. For example, the
active_user
variable is more descriptive than theau
. - Use underscores (_) to separate multiple words in the variable names.
- Avoid using the letter
l
and the uppercase letterO
because they look like the number1
and0
.
Here are some the example of variable creation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
# Variable assignment x = 10 # Assigns the integer value 10 to variable x name = "John" # Assigns the string "John" to variable name pi = 3.14 # Assigns the float value 3.14 to variable pi # Variable usage y = x + 5 # Adds 5 to the value of x and assigns it to y greeting = "Hello, " + name # Concatenates the string with the value of name # Variable reassignment x = 20 # Reassigns the value of x to 20 # Multiple assignments a = b = c = 0 # Assigns the value 0 to variables a, b, and c # Dynamic typing age = 25 # age is an integer age = "twenty-five" # age is now a string # Constants (convention) MAX_VALUE = 100 # A constant variable with a value of 100 (uppercase naming convention) |
In Python, variables are dynamically typed, meaning you can assign different types of values to the same variable. They can also be reassigned with different values throughout the program.
It’s important to note that Python is a case-sensitive language, so x
and X
would be treated as different variables. Also, the names of variables should follow certain rules, such as starting with a letter or underscore, and can include letters, numbers, and underscores. However, they cannot be Python keywords or reserved words.