Variables are an essential thing in all programming languages. They help us reuse multiple values more than just once.
One special thing about Python is the implicit type-inference. This means, that we do not have to assign a type to a variable by its declaration as in Java or C (although that is still possible, it's not required in Python). Basically, the compiler does the typing by itself.
Types in Python[]
Primitive Data Types[]
These following are called primitive, or, in other words, simple data types. Variables of these types can only hold one value.
- Integers
- Floats
- Strings
- Chars
- Complex numbers
Complex Data Types[]
- List
- Dictionary
Variable Name Rules[]
- Variable names can only be alphanumeric (i.e. can only contain letters and whole numbers).
- Variable names can only start with alphabetical letters or an underscore.
- Variable names can not be any of the Python keywords (i.e. you can not assign a variable with the name "if").
- Variable names are case-sensitive, so be sure that you're typing in the case you want.
Usage of variables[]
To assign a variable, we use this general Syntax:
variable_name = value
Now see some examples:
# declaring two strings
foo = 'foo'
bar = 'bar'
# declaring an integer
# note: automatically inferred as integers
i1 = 7
i2 = 42
# declaring two floating point numbers
d1 = 42.7
d2 = 7.42
# declaring two complex numbers
c1 = 7 + 42j
c2 = 42 + 7j
Reuse of variables[]
The main thing about variables is that we can use them more than just one time by calling them. This is done as in the following example:
# defining a variable
foo = 'awesome'
# ... and reuse it by
# printing it's value
print(foo) #in Python 3.X
# print foo #in Python 2.X