Variables & Datatypes
Variables
A variable is a container which stores data values within the computer's memory. They have a name and address.
For example, if we have a box, we can place books, cloths, food or else anything in it. In this case, box is variable name and the contents that we place in it can be considered as data value.
Examples:
-----------------------------------------------------------------------
| color= "black" | Here we assigned string value "black" to the variable color |
| age= 37 | Here we assigned int value 37 to the variable age |
| has_car = False | Here we assigned Boolean value False to the variable has_car |
| pi = 3.14 | Here we assigned float value 3.14 to the variable pi |
------------------------------------------------------------------------
Always choose proper meaningful and descriptive variable names as a best practice. This will keep your code cleaner. Also, when you or someone revisits your code identifying certain variables will become easy.
Which variable names do you choose from below examples??
a = 'Rhash Algo' or website_name = 'Rhash Algo'
y = 2023 or year = 2023
Variable name rules:
It's always best to follow certain best standards in any programing language. Just like that, we do have certain variable name rules. So, let's see what they are now.
Should start with letter or underscore character.
Ex: age, _company, address, _salary etc.
Should only contain Alpha numeric and underscore.
Ex: a-z, A-Z, 0-9, _
Case-sensitive
Ex: age, AGE, Age all are different
Should not contain hyphens.
Ex: current-year, emp-salary, person-age all are invalid variable names.
Should not start with numeric.
Ex: 0age, 5name, 9_year all are invalid variable names.
Should not use Python reserved words.
------------------------------------
| False | await | else | import | pass |
| None | break | except | in | raise |
| True | class | finally | is | return |
| and | continue | for | lambda | try |
| as | def | from | nonlocal | while |
| assert | del | global | not | with |
| async | elif | if | or | yield |
------------------------------------
Legal Variable Names:
All the names below are legal names:
>>> myName = 'Rhash Algo'
>>> MyName = 'Rhash Algo'
>>> my_name = 'Rhash Algo'
>>> My_Name = 'Rhash Algo'
>>> MY_NAME = 'Rhash Algo'
Illegal Variable Names:
Below is the representation of illegal names.
>>> 1my_Name = 'Rhash Algo'
>>> my-name = 'Rhash Algo'
>>> my name = 'Rhash Algo'
Get Variable Type:
We can get the type of a variable by using the keyword type.
>>> type(x)
<class 'int'>
>>> x = 'Rhash Algo'
>>> type(x)
<class 'str'>
>>> x = 3.14
>>> type(x)
<class 'float'>
>>> x = {1:'One', 2:'Two'}
>>> type(x)
<class 'dict'>
Variable Techniques:
If there is a need of creating variable with more than one word, it's not readable if all the words are in the same case or format. So, to solve this problem, there are different techniques that can be followed to create variables.
Camel Case: Each word, except that first, starts with a Capital Letter.
myOrgName = 'Rhash Algo'
Snake Case: Each word separated by an underscore.
my_org_name = 'Rhash Algo'
Pascal Case: Each word stats with a capital letter.
MyOrgName = 'Rhash Algo'
Unpacking:
If there is a collection like list, set, tuple with more than one value, in such cases all the objects within that collection can be assigned to multiple variables at the same time.
>>> name, age, salary, org = 'Rajesh', 37, 100000, 'Rhash Algo'
>>> print(name)
Rajesh
>>> print(age, salary, org)
37 100000 Rhash Algo
Multi-Variable Assignment:
There will be situations, where we need to assign same value to multiple variables at the same time. In such situations, there is no need to assign that value with multiple assignments. That can be accomplished with single assignment as below:
>>> a = b = c = d = 'RhashAlgo'
>>> print(a, b, c, d)
RhashAlgo RhashAlgo RhashAlgo RhashAlgo
Global Variables:
Without global Keyword:
A variable declared outside of the scope (Ex: Function, Class etc), is global to that scope.
>>> org = 'Rhash Algo'
>>>
>>> def fun():
... print(org)
...
>>> fun()
Rhash Algo
From above example, if the variable value is changed in the function, it won't effect the global scope.
>>> org = 'Rhash Algo'
>>>
>>> def fun():
... org = 'RHASH ALGO'
... print("Inside:", org)
...
>>> fun()
Inside: RHASH ALGO
>>> print("Outside:", org)
Outside: Rhash Algo
With global Keyword:
A variable declared with global keyword can be used in global scope. Check below example:
>>> org
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'org' is not defined
>>> def fun():
... global org
... org = 'Rhash Algo'
... print("Inside:", org)
...
>>> fun()
Inside: Rhash Algo
>>>
>>> print("Outside:", org)
Outside: Rhash Algo
Delete Variable:
We can delete a variable by using the del keyword. See below example:
>>> org = 'Rhash Algo'
>>>
>>> org
'Rhash Algo'
>>>
>>> del org
>>>
>>> org
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'org' is not defined
Data Types
Data Types are the classification or categorization of data items.
Convert Data:
To convert data from one datatype to other datatype, we can use built-in datatypes.
Examples:
# Convert from integer to float
int_to_float = float(15) #These codes converts the data value
print(int_to_float) #These codes will print the converted data value
print(type(int_to_float)) #These codes will print the data type
# Convert from float to integer
float_to_int = int(23.56)
print(float_to_int)
print(type(float_to_int))
#Convert from integer to string
int_to_string = str(51)
print(int_to_string)
print(type(int_to_string))
#Convert from string to integer
string_to_integer = int("6589")
print(string_to_integer)
print(type(string_to_integer))
Output
15.0
<class 'float'>
23
<class 'int'>
51
<class 'str'>
6589
<class 'int'>
Please find below table for more details on different data types in Python.