Python variable

The target

In this article, you’ll learn about Python variables and how to use them effectively.

What are variables in Python

When you develop a program, you need to manage a lot of values. To store values, you can use variables.

In Python, a variable is a label that you can assign a value to. Variables are always associated with values. Such as:

Message = 'Hello world! 'print(message) message =' Bye! ' print(message)Copy the code

Output:

Hello world! Bye bye!Copy the code

In this case, message is a variable. It saves the string ‘Hello world! ‘. The hello world () function displays hello world. To the screen.

The next line of the assignment string Good Bye! Go to the variable message and print its value to the screen.

The variable message can hold different values at different times. Its value can change throughout the program.

Create a variable

To define a variable, you can use the following syntax:

Variable name = valueCopy the code

= is the assignment operator. In this syntax, you assign a value to a variable name.

The value can be a number, a string, etc., you can assign a value to a variable.

Here we define a variable called counter and assign the number 1 to it:

counter = 1
Copy the code

Naming variables

There are a few rules to follow when naming variables. If you don’t, you get an error.

Here are the variable rules you should keep in mind:

  • The variable name can contain only letters, digits, and underscores (_). They can start with a letter or underscore (_) instead of a number.
  • Variable names cannot contain Spaces. To separate words in variables, use underscores, such as sorted_list.
  • Variable names cannot be the same as keywords, reserved words, and built-in functions in Python.

The following guidelines can help you define good variable names:

  • Variable names should be concise and descriptive. For example, the active_user variable is more descriptive than au.
  • Use an underscore (_) to separate multiple words in a variable name.
  • Avoid using the letter L and capital O, as they look like the numbers 1 and 0.

conclusion

  • A variable is a label that you can assign a value to. The value of a variable can change throughout the program.
  • useVariable name = valueCreate a variable.
  • Variable names should be as concise and descriptive as possible. In addition, they should follow the Python variable naming conventions.