Variables in Python

In this blogs, we will be working with variables

Variables are memory location which stores values. Variables are treated differently in Python than in C and Java programming languages. Considered a below statement

b = 10

When the above statement is executed, it will allocate memory location with a name ‘b’ and will hold a value 10. Use id() built in function to find memory address which is allocated to variable b

b = 10
print(id(b))

Output

140730477905872

In this way, for every variable that is created, there will be a memory location allocated to store value. Now if we change the value of the variable, a new memory location is allocated.

b = 90

In the above statement, previous value of the variable b was 10 and then it has been changed to 90. In this case, a new memory location is allocated with a value of 90. Below is the code which uses id() function to check memory addresses.

b = 10
print(id(b))
b = 90
print(id(b))

Output

140730477905872
140730477908432

It shows two memory addresses for two different values with the same name

Rules for variables name

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)

Advertisement

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s