Summary: in this tutorial, you’ll learn about Python variables and how to use them effectively.
What is a variable in Python
When you develop a program, you need to manage values, a lot of them. To store values, you use variables.
In Python, a variable is a label that you can assign a value to it. And a variable always associates with a value. For example:
message = 'Hello, World!' print(message) message = 'Good Bye!' print(message)
Hello, World! Good Bye!
In this example, the message is a variable. It stores the string
'Hello, World!'. The print() shows the message
The next line assigns the variable
message another value, the string
'Good Bye!'. And then print its value on the screen.
message can various values at different times. And its value can change throughout the program.
To create a variable, you use the following syntax:
variable_name = value
The = sign is the assignment operator. In this syntax, you assign the value to the variable_name.
The value can be anything like a number, a string, etc., that you assign to the variable.
The following creates a variable named counter and assign one to it:
counter = 1
When you name a variable, you need to adhere to some rules. If you don’t, you’ll get an error.
The following are variable rules that you should keep in mind:
- 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
- Variable names cannot the same as keywords, reserved words, and built-in functions in Python.
The following variable guidelines help you define variables that’s easier to read and understand:
- Variable names should be concise and descriptive. For example, the
active_uservariable is more descriptive than the
- Use underscores (_) to separate multiple words in variables in variable names.
- Avoid using the letter
land the uppercase letter
Obecause they look like the number
- A variable is a label that you can assign a value to it. The value of a variable can change throughout the program.
- Use the
variable_name = valueto create a variable.
- The variable names should be concise and descriptive. Also, they should adhere to the Python variable naming rules.