DEV Community

Cover image for πŸš€ Understanding Variables in Python
Divya Dixit
Divya Dixit

Posted on

πŸš€ Understanding Variables in Python

So, in the last post, we added two numbers, 23 and 34. We gave these numbers to the computer as input, and then it processed them for calculation and gave us the output.
But what if we want to** store numbers** in the computer's memory for later use? This is where variables come into play!

However, we don’t always have to provide numbers or information directly for processing. Computers can also store data or information in their memory at a specific location with a*n address.*

Just like you live in a house that has an address, variables in a computer's memory also have a location and an address.

What is a Variable?

A variable is a name given to a value stored in the computer's memory. Think of it as a container that holds data, just like a box where you store things.

For example, if we want to store the numbers 23 and 34 in the computer’s memory as num1 and num2, the computer will store them at memory locations let them loc1 and loc2.

Now, instead of directly using 23 + 34, we can access these stored numbers anytime using their variable names:


num1 = 23
num2 = 34
print(num1 + num2)

This will fetch the values stored in num1 and num2, perform the addition, and give us the result as output.

Similarly, we can store information about ourselves, such as name, age, class, and city, in Python variables and retrieve them using the print() function.

For example:

name = "Brian"  
age = 23  
city = "Delhi"  

print(name, age, city)  
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Output:

Brian 23 Delhi

Here, we have stored values in variables and then displayed them using print().

That's how variables operate and we can use them in our programming to store some kind of data.

But while naming variables, we have to follow some rules, which are as follows:

βœ” Only letters, digits, and underscores () are allowed.
βœ” No spaces are allowed in variable names.
βœ” Cannot use Python keywords like print (we will discuss others later).
βœ” A variable must start with a letter or an underscore (
).
βœ” Special symbols like @, $, #, & are not allowed.

for example, 1num or num 1 are invalid but _num1 or num_1 are valid.

Top comments (0)