Today, we will discuss what are variables, datatypes, and comments, and why we need them.
Simply put, a variable is a container that stores a value (such as a number) and a datatype specifies what type of value it [the value] is. In other programming languages, it also means to define what kind of value should a variable store.
There are three main kinds of datatypes in Python:
String
Integer
Float (Floating-point)
A string is a set of characters (numbers, symbols, and letters) that is inside quotation marks. For example, "Hello World!" is a String. No other datatype can store these many characters in such a variety.
An integer, as the name suggests, is a number that is either positive, negative, or zero. For example, 0, 4, and -2 are all integers. The range of integers is around two billion in both directions (approximately -2000000000 and 2000000000).
A float is a decimal version of an integer that is also a number that is either positive, negative, or zero. If an integer is specified as a float, a ".0" is added to the number. For example, 5 turns into 5.0. The range of float is around 10^(308)
To create a variable in Python, we use the syntax variable_name = variable_value.
Let us try an example. In the IDLE shell, open a new file and type the following code:
number=5
Now save the file and run it. This is the output:
Of course, the reason there is no output is because we did not print anything. All we did was create a new variable with the name "number." To see what the variable contains, we add a new line of code:
print(number)
The output would now be like this:
As we can see, the value of the variable has been printed out.
If we wish to say something like Number: 5, then we need to add, or concatenate, a string to a number. But because a number cannot be combined to a string directly, we need to use the str() method:
There are more conversion methods in Python as well: str(), int(), and float(), and they can be used on any of the String, Integer, and Float datatypes.
A comment is a string that is ignored by the compiler (IDLE, in this case) and is mainly for human use and not for the purpose of the compiler. To create a comment in Python, we use a # before the sentence. If the sentence is too big, we use ''' marks (three single quotes). An example:
However, if we removed the comment syntax, we get:
This is a Syntax error. It means that Python does not understand what this piece of code does. Most of time, We get Runtime errors, where the error is in what the code is doing and not the code syntax. For example, forgetting to use a comment symbol (like here) is a syntax error. But misspelling the name of the variable is a Runtime error:
This error, also known as a Traceback, says that the name (variable) "numbder" is not defined. Python cannot find a variable named numbder, so it gave this error.
Variables are useful to store different types of values and Comments are useful for describing what does the code do.