Variables in python

Simran Gopal
2 min readMay 21, 2021

What are variables?
Variables are containers for storing data values. They can be created instantaneously by assigning a value to the variable name
eg. var1=5 here ‘var1’ is the variable name and 5 is the value assigned to ‘var1’. We can use print() function to print the variable values but only typing the variable name works too. eg print(var1) can be just written as var1 to get the value of var1.

What are variable types?
Variables do not need to be declared with any particular type, but a type is assigned as soon as the variable is created. We can test the type using
print(type(var1))
There are 4 types in python- int (integers like 1,2748,etc), float (decimal numbers like 2.45,8.3,etc), string (consists of characters like a-z, etc), boolean (True and False)
If we use ‘ ’ to assign the variable
eg. num=‘5’
then no matter what is in the ‘ ’- python will assign it as a string.
But we can change type after they have been set. We will use the int() function to convert it into integer so we can say
num=int(num)
This was pretty straight forward.

But what about string to Boolean conversion?
For string to boolean any string that is not an empty string (‘’) will be a True but any empty string will be False.

And what about int and float to boolean?
Any variable with value 0 will be converted to False. If the variable has any value other than 0 the boolean value will be true.

--

--