DEV Community

Cover image for Python Variables
Rhythm Saha
Rhythm Saha

Posted on

Python Variables

Today let's discuss about variables in Python, what they are and how to use them.

What are variables

Variables are a kind of containers for storing data values. If you are familier with mathematics, then you have used variables there also. Similarly we also use variables in programming. But unlike mathematics you can change the value of a variable.

Python is not statically typed. We do not need to declare variables before using them or declare their type. A variable is created the moment we first assign a value to it. A variable is a name given to a memory location. It is the basic unit of storage in a program.

  • The value stored in a variable can be changed during program execution.
  • A variable is only a name given to a memory location, all the operations done on the variable effects that memory location.

Rules for creating variables in Python:

  • A variable name must start with a letter or the underscore character.
  • A variable name cannot start with a number.
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).
  • Variable names are case-sensitive (name, Name and NAME are three different variables).
  • The reserved words(keywords) cannot be used naming the variable.

The code

age = 45
salary = 1456.8
name = "John"

print(age)
print(salary)
print(name)
Enter fullscreen mode Exit fullscreen mode

output:

45
1456.8
John
Enter fullscreen mode Exit fullscreen mode

Declare & re-declare variables

We can declare the variable by simply following the main rules of variable declaration. The re-declaration variables means we can change or update the value of the previously declared variable. We won't be able to work with the previous value of the variable after re-declaration

Let's see how to declare and re-declare variable and print them

# declaring the var
Number = 100

# display
print("Before declare: ", Number)

# re-declare the var
Number = 120.3

print("After re-declare:", Number)
Enter fullscreen mode Exit fullscreen mode

Output:

Before declare:  100
After re-declare: 120.3
Enter fullscreen mode Exit fullscreen mode

If you like the content and want to get updates on more post like that please follow me @rhythmsaha

here are my social profiles

Top comments (0)