Python is a general purpose and very versatile language that’s easy to learn and can help you build almost anything you can imagine, from small command-line applications and utilities to big and complex machine learning applications for data science. In these examples we’ll go through the basics of Python in an interactive way.
First let’s define some variables and then we’ll check their type of variable.
The previous commands showcase the way we can define variables and how we can check their type of variable, for that we’re using the built-in type function of python.
No we will create a practical example, for this we will create a script that does the following:
- Ask for a name from the user
- Ask for their birth year
- Show a greeting with the name the user typed in
- Calculate and show their age based on the year they input and the current year
By default the
input function returns a
string value, since the next piece of data we need is the birth year, we need to explicitly convert it to an
integer using the built-in int function.
To calculate the age of the user first we need to get the current year, for that we need to import the
datetime module from the similarly named datetime library.
Now this can be confusing but it’s just that the library and the module have the same time, but that’s not the only module in that library, there are many others that we might use in later examples.
After the module is imported we just simply use the
now() function in conjunction with the
year function to get the current year.
After that we just substract the birth year from the current year to get the current age.
After that we’ll just print the greeting with the user’s age.
If you put all the code together you get something like the following.
Notice anything different? That’s right, we’re importing the
datetime module first, this is due to Python coding conventions, all imports should be on the top of the file.
With this we’ve created our first python script, stay tuned for more examples and lessons.