Variables in Python

This tutorial will teach you about Python variables and how to effectively use them.

When creating a program, you must manage a large number of values. Variables are used to store values.

A variable in Python is a label to which you can assign a value. And every variable has a value associated with it. As an example:

message = 'Hello, World!'
print(message)

message = 'Good Bye!'
print(message)

Output

Hello, World!

Good Bye!

The variable message is used in this example. It has the string ‘Hello, World!’ attached to it. Hello, World! is printed using the print() method.

The next line sets the message variable to the string ‘Goodbye!’ and prints its value to the screen.

At different times, the variable message can have different values. Its worth may fluctuate throughout the programme.

How to Create Variables in Python?

The following syntax is used to define a variable:

variable_name = value

The assignment operator is =. The variable name is given a value in this syntax.

The value can be any number, string, or other object that you set to the variable.

The following code creates a counter variable and assigns the value 1 to it:

counter = 1

Naming variables in Python

When naming a variable, there are some guidelines to follow. You’ll get an error if you don’t.

The following are some important variable rules to remember:

  • Only letters, digits, and underscores () are allowed in variable names. They must begin with a letter or an underscore () rather than a number.
  • Spaces are not allowed in variable names. You use underscores to separate words in variables, such as sorted list.
  • In Python, variable names can’t be the same as keywords, reserved words, or built-in functions.

The following guidelines can assist you in naming good variables:

  • The names of variables should be short and descriptive. The active user variable, for example, is more detailed than the au.
  • To separate numerous words in variable names, use underscores ( ).
  • The letter l and the uppercase letter O should be avoided since they resemble the numbers 1 and 0.
%d bloggers like this: