Main Menu: PYTHON PROGRAMMING
Before We Begin
In this pre-requisite chapter, you'll learn how to install Python on your Windows system. You'll learn to work with Python using the Command Prompt, fondly called the CMD, and will also learn how to create your first Python Program. We'll also discuss the various coding conventions used throughout the different examples all over this blog...
1.1: Installing Python
Installing Python is not too much of a hassle, but if not done properly it could prove to be troublesome when working on live projects. Now, there are many different Python versions available, and these versions are currently being supported in two streams: Python 2.x and Python 3.x. Naturally, Python 3.x came later, however since Python's 2.x (namely 2.7's) is highly popular and was already in use by most organizations, support is available for both Python 2.x and Python 3.x.

For the sake of this blog, we will install and develop programs in Python 3.x. There are few differences in syntax and functionality in Python 2.x and Python 3.x and I will do my best to address this wherever necessary.

Go to Python Downloads Page, and then click on the yellow button "Download Python 3.x.x (At the time of writing this blog, we have Python 3.7.2). This should download an executable file "Python-3.7.2.exe." Open the file by right-clicking and selecting "Run as administrator". When it opens, click on "Customize Installation", select all the checkboxes and then click "Next".

The window then moves on to Advanced Options. Here, change your install location to C:/Program Files/Python37 (You will have to manually create the folder Python37 in C:/Program Files). After setting the installation location, click on "Install".

The installation might take a few minutes.

After this is done, go to the install location C:/Program Files/Python37 and check if the folder has been populated. Rename the application file named Python to Python37. This will prove to be a smart step in the future when you work with multiple versions of Python on the same machine.

The next step is to add Python to your computer's Windows Shell PATH system variable. You cannot execute any programs if this is not done. Go to "Control Panel", click on "System and Security", then on "System", and finally on "Advanced System Settings".

A small window - System Properties - should pop up. Go the the tab "Advanced", and then click on "Environment Variables". In the box for System Variables, click on "New". Fill in the Variable name as "PATH", and the Variable value as "c:\Program Files\Python37; c:\Program Files\Python37\Scripts."

Click on "Okay", and you have successfully installed Python 3.7.x on your system.
1.2: Using Python from the Command Line
Programming in Python can be carried out either using an Integrated Development Environment (IDE) or a Command Line Interface (CLI). The CLI in this case would be the command prompt or CMD on your machine. Type "CMD" in your Windows search bar, and the black-screen window-of-death should open up.

The CMD's default library is usually C:/ or C:/Users/Your_User_Name. Since you have installed Python in C:/Program Files/Python37 this shouldn't worry you at all. Just type python37 and the Python 3.7.2 terminal should load for you as shown below:


C:\Users\Kevin>python37
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>_                 
            

Let's start with some very basic stuff. In the few lines of code below, we have created variables and assigned integer values to these variables. In the third line, we add the two variables and assign the result of the addition to a new variable. Finally, the result is printed by simply typing the variable name.


>>> a = 1       # Hit enter to go to next line
>>> b = 2       # Hit enter
>>> c = a + b   # Hit enter
>>> c           # Hit enter
3
>>>                 
            

In most professional (and personal) projects, you may need to develop Python programs that are stored outside of C:/ drive. At the moment, Python has been installed in your C:/ drive, and it has created a "virtual environment" where all resources required to interpret and execute your Python programs are stored. However, Python allows you to create virtual environments outside of C:/ drive, from where you can run Python and create and execute your Python programs.

Let's say for example, you want to develop your Python project and store it in a folder in your D:/ drive. Let's name this folder pythonTest. This folder will be called your working directory. The path to this working directory will be 'D:/pythonTest'.

Using the commands shown below, you can create your working directory, and install a Python virual environment inside it.


>>> import os                       # This is an example of us importing packages into our Python program
>>> os.mkdir('D:/pythonTest')       # This will create a folder 'pythonTest' in your D:/ drive
>>> quit()                          # Close the Python 3.7.2 terminal and return to the CMD

C:\Users\Kevin>                 
            

Now that you have created a new directory (a new folder) for your project, it is time to create a virtual environment. Once you are back in the CMD, enter the following command:


C:\Users\Kevin>python37 -m venv D:/pythonTest

C:\Users\Kevin>            
            

If you now check the folder D:/pythonTest, you'll see that it is populated with Python 'Lib', 'Scripts', and 'Include' folders. You can now launch the Python shell from within this directory.

The first step is to change the directory for your computer's CMD. And once you are inside working directory, launch Python and follow the commands given in the snippet below:


C:\Users\Kevin>cd /d D:/pythonTest   

D:\pythonTest>python37
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> os.getcwd()    # Get the location of your current working directory
'D:\pythonTest'
>>>           
            

And voila! Your Python virtual environment is ready!
1.3: Conventions used in this blog
Coding conventions are a set of recommended guidelines for any programming language. These guidelines ensure that programmers make use of specific programming styles, methods, or practices for a particular project they undertake.

In a real-world project, conventions play a very important role, as they ensure that programmers make their code readable and maintainable, and follow a pre-defined standard. This makes the code easy to modify, especially for those who might join the project after the original code developer has moved on.

All code that you will encounter in this blog shall follow the following convention, so that you may be able to follow what is being shared without difficulty, and recognize specific important pieces of information on your own:

1: Naming Conventions
Professional software developers follow different naming conventions for their code. We shall follow the "camel case" style of naming any program, package, class, method, or variable.

The camel case style of naming is as follows:

    i. All names given to any program, package, class, method, or variable, must sufficiently hint towards the reasoning for that particular program, package, class, method, or variable. For example:
      a) A variable holding a number divisible by 5 must be named as 'numberDivisibleByFive'.
      b) A method that calculates the factorial of a number must be named as 'calculateFactorial'.

    ii. The name given to each program, package, class, method, or variable will consist of more than one word, without spaces or underscores in between. The first word will be all in lower-case, while those following the first word shall have their first initial in upper-case. For example:
      a) A variable 'numberDivisibleByFive'.
      b) A method 'calculateFactorial'.

    iii. The name of any program, package, class, method, or variable shall not begin with a number. For example:
      a) Use 'tenMultipliedByNumber' instead of '10MultipliedByNumber'.
      b) Use 'twentyFourHourClock' instead of '24HourClock'.

2: Displaying Code
Each chapter will be filled with a number of examples, which we shall analyze thoroughly.

    i. So that there is clarity of content, all code shall be enclosed within special code windows and displayed as below: All words in bold and followed by '#' are comments:
    
    # An Integer number can be either positive, negative, or a zero (0). Let's look at the examples below:
                                    
    a = 5       # Here, we have assigned values to two Integer variables. Let us under-
    b = 4       # stand this: Python implicitly considers a variable assigned a number
                # value as Integer, unless explicitly stated.
                                    
    print('The value of A: ' + str(a))    # The 'print()' function is among the most basic functions in Python.
    print('The value of B: ' + str(b))    # It outputs the value of any variable and string within it's parenthesis.
    print('\n')                           # In this case, it would be 'The value of A: 5', as you will see on
                                          # running this code. Let's ignore the 'str(a)' part for now, though if you've
                                          # worked with similar programming languages before, you should know what it is and how it works.
                                    
    # Integer addition:
    A_plus_B = a + b
    print('A + B = ' + str(A_plus_B))
                                    
    # Integer subtraction:
    A_minus_B = a - b
    print('A - B = ' + str(A_minus_B))
                                    
    # Integer multiplication:
    A_into_B = a * b
    print('A x B = ' + str(A_into_B))
                                    
    # Integer 'true' division:
    A_by_B = a / b
    print('A / B = ' + str(A_by_B))                                                  
                                

    ii. Any single lines of code being analyzed shall be displayed as below:
    
    listOfNames = ['Kevin', 'Diana', 'Annet']
                                

    iii. Special keywords and names that have been picked up from code, but need to be analyzed in an explanation shall be highlighted and displayed in the following manner:

    "The private keyword is an access-specifier that allows users to define which objects or parts of their program might be access or manipulate..."
1.4: Your First Python Program
Okay, now that you have created a working directory in your D:/ drive, let's create a Python file and launch it from within working directory.

In your Windows search bar, type IDLE and open it. IDLE was downloaded along with Python and is a special Python shell that allows you to develop Python programs instead of launching Python from your computer's CMD. Once IDLE opens, go to "File > New File". A new notepad-like file will open.

Type the following lines in the notepad:


# Import the Package 'os'
import os
# Import the Package 'datetime'
import datetime
# Get the path for your Current Working Directory in which your program is running
workingDirectory = os.getcwd()
# Print a string of characters
print('I am a Python programmer now!')
# Print a message about your Current Working Directory
print('We are inside ', os.getcwd())
# Get today's date
todaysDate = datetime.datetime.now()
# Print today's date
print('Today\'s date is: ', todaysDate)         
            

Save the notepad inside D:/pythonTest as "myFirstProgram.py" and close the file.

Now, once this is done, there are three ways to run the program.

The first way is to run the program through IDLE Editor. After saving the notedpad in D:/pythonTest, go to the directory, and right-click on the file 'myFirstProgram' and select 'Edit with IDLE (3.7)'. The file will open in the IDLE Editor. Now, press F5 on your keyboard or go to 'Run > Run Module'. This causes the IDLE Python shell to open and display the following output:


Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 
=================== RESTART: D:\pythonTest\myFirstProgram.py ===================
I am a Python programmer now!
We are inside  D:\pythonTest
Today's date is:  2019-01-06 15:55:04.178478
>>> 
            

The second way is to run it through the Python shell through CMD. Once again, open CMD and change the directory to D:/pythonTest as shown in section 1.2. After that, launch the Python37 shell, and type the following command:


>>> exec(open("myFirstProgram.py").read())
            

Here is what you will see on your screen:


D:\pythonTest>python37
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> exec(open("myFirstProgram.py").read())
I am a Python programmer now!
We are inside  D:\pythonTest
Today's date is:  2019-01-06 16:05:01.684709
>>>
            

Another way to do that without entering the Python shell is to simply change your CMD directory to D:/pythonTest, and then type the following command:


C:\Users\Kevin>cd /d D:/pythonTest

D:\pythonTest001>python37 myFirstProgram.py
I am a Python programmer now!
We are inside  D:\pythonTest
Today's date is:  2019-01-06 16:12:09.573689
            

The third way to run your program is again through IDLE's Python Shell. Open IDLE (3.7) through your Windows search bar, and type the following lines:


>>> import os                                  # Hit enter to go to next line
>>> os.chdir('D:/pythonTest')                  # Hit enter    
>>> exec(open("myFirstProgram.py").read())     # Hit enter 
            

You will see the following output:


I am a Python programmer now!
We are inside  D:\pythonTest
Today's date is:  2019-01-06 16:30:36.489819
            

And just like that, you have now created your First Python Program myFirstProgram.py and learned three ways to execute it!