DEV Community

Phúc Dương Minh
Phúc Dương Minh

Posted on • Edited on

Python: All You should know about variable

What is variable

As you know, when you do math, variable symbolize to unknow number of the expression; but in programming, variable references to any value. In Python you can assign variable like this example:

a = 9
b = 18
Enter fullscreen mode Exit fullscreen mode

Variable naming rules

There are the variable naming rule:

  • You can use any letter from a to z and A to Z.
  • You can use character "_" and number for variable name.
  • You can't use any special character like !, @, #, $, %, ^, & , etc.
  • You can't use space character " ".
  • First character must be lowercase.

Ex:

height = 9
width = 18
Enter fullscreen mode Exit fullscreen mode

Note:
You must not use keys in Python (like for, while, def, from, class, in, if, else, etc) for variables name.

Dynamic typing

If you already know other programming languague like C# or C/C++, when you declaration variables, you need to declaration data type; but with Python, you don't need to declaration data type and when you change the data of this variable, it'll change data type if the new data different than the previous data.


a = 'apple'
print(a)

a = 1
print(a)
Enter fullscreen mode Exit fullscreen mode

apple
1

Shared reference

As I mentioned above, variable reference to the data and an object, so you can write an variable reference to another variable. Each variable have their own memory loaction, so if you write an variable reference to another variable, they'll have the same memory location.


b = a
print(b)

b = 'banana'
print(a)
Enter fullscreen mode Exit fullscreen mode

1
banana

Some built-in functions for variables in Python

There are some built-in functions for variable but I tell you two functions here:

  • id: You can use id to see memory location of the variable.
  • type: you can use type to see data type of the variable.
print(id(a))
print(type(a))
Enter fullscreen mode Exit fullscreen mode

If you know more about variable in Python, you can tell it in the comments and lets guess what is the topic of the nest post in this series. ✨

Top comments (0)