Table of Contents


Differences between Python 3 and Python 2?

To run code using a particular version of Python, it has to be installed onto the host first.

To run a particular or legacy version of python in CLI, such as PowerShell type py to start python, then use the switch indicator (-) followed by the version number.
PS >py -2
the number after the switch (-) indicates the version of Python to use.

To know the differences between the two (2) versions. Importing modules in Python 2 is indicated by two (2) underscores on either side of a modules name. e.g.
Python 3 -
import builtins

Python 2 -
import __builtins__

Within functions modules are also separated by double underscores
Python 3 -

Python 2 -

When calling functions in Python 3 a bracket separates the internal call criteria. e.g.
Python 3 -
print("Hello World")

Python 2 -
print "Hello World"

Python running scripts

In computing, the word script is used to refer to a file containing a logical sequence of orders or a batch processing file. This is usually a simple program, stored in a plain text file. Scripts are always processed by some kind of interpreter, which is responsible for executing each command sequentially.

When you try to run Python scripts, a multi-step process begins. In this process the interpreter will:

1) Process the statements of your script in a sequential fashion

2) Compile the source code to an intermediate format known as bytecode
This bytecode is a translation of the code into a lower-level language that’s platform-independent. Its purpose is to optimize code execution. So, the next time the interpreter runs your code, it’ll bypass this compilation step. Strictly speaking, this code optimization is only for modules (imported files), not for executable scripts.

3) Ship off the code for execution
At this point, something known as a Python Virtual Machine (PVM) comes into action. The PVM is the runtime engine of Python. It is a cycle that iterates over the instructions of your bytecode to run them one by one. The PVM is not an isolated component of Python. It’s just part of the Python system you’ve installed on your machine. Technically, the PVM is the last step of what is called the Python interpreter.

The whole process to run Python scripts is known as the Python Execution Model.

Running Python Scripts in Windows

Run a Python script under Windows with either software; Command Prompt or PowerShell.

Windows users must pass the path of the program as an argument to the Python interpreter. Such as follows:
PS> C:\Python27\python.exe C:\Users\User_name\Desktop\

Or simply use the shortened command below as

PS> python C:\Users\User_name\Desktop\

Run a Python Script Under Mac, Linux, BSD, Unix, etc

You can then run a program by invoking the Python interpreter manually as follows:

Running Python Script within the default Python shell

using exec(), which is a built-in function that supports the dynamic execution of Python code. This statement opens, reads its content, and sends it to exec(), which finally runs the code.


Avoiding Frustration

For the purpose of this course, Python is run across PowerShell. This means the host operating system can be any device that PowerShell is sitting on top of. PowerShell versions two (2) to five (5) are only on Windows Operating systems while PowerShell Core 6.0 is available for macOS and certain Linux distributions. See chapter for Host Shell versions.

This chapter outlines the varies ways to avoid the common frustrations when using Python 3 for the first time as well as explain how to get started using basic functions in Python 3 Interpreter running on a PowerShell shell as well as on many other Operating system shells that Python is running on.

Knowing the underlying framework of the operating systems shell will allow the user to be able to import these commands into Python. As Python Interpreter sits on an existing shell, it can inherit all the commands from the underlying shell by using an import module function, "import os". Import os allows python to encapsulate underlying PowerShell/UNIX/Bash commands to use in its CLI Environment.

PowerShell users will note that os is the class and system() is the method. Dir is an unix command which is an alias for Get-ChildItem and will output the same result.

import os

To import commands using a macOS/Apple device follow the official Python steps on this URL Using Python on Mac

Clearing Screen

Another example to avoid frustration in Python is being able to clear the screen and demonstrate the importing underlying os commands. Note if using in Linux distributions the command may be "clear" instead of "cls", "cls" is an alias for clear in PowerShell.

import os

A return code of 0 will be output advising the screen has been cleared.

Alternatively keep pressing Enter Key until all previous output text is off the screen. Use whichever you find convenient.

Command History

To get the last command used you can copy and paste it from the shell using the mouse to highlight the text and pressing the CTRL – C Keys together on your keyboard.
You may also copy and paste entire scripts into the Shell.
Next Line
As Python is a basic CLI when run without an IDE/ISE. To enter an carriage return or enter key to get to a new line when writing a script, use the "" keys together. This will allow you to type on the next line.

Continuing long commands

There are multiple ways to continue a long statement,
1). A long statement:

>>> def print_something():
print 'This is a really long line,', \
'but we can make it across multiple lines.'

2). Using parenthesis " ( " or " ) " :

>>> def print_something():
print ('Wow, this also works?',
'I never knew!')

3). Using the slash character " \ " :

>>> x = 10
>>> if x == 10 or x > 0 or \
x < 100:
print 'True'

Loops and Indentation

One of the biggest differences between Python and most other popular programming languages is the disuse Of parenthesis ( { } ) and the substitution with colon character ( : ) to indicate loop starts. As there's no parenthesis To close a loop, the indentation (whitespace) indicates the internal loop block. Four (4) whitespace characters as indicated By a spacebar ( ) represent the internal loop. To close the loop requires the user to hit enter to the next line which will Then signify the start of the next loop. If nothing is required you may press enter (Carriage Return) again to close the loop Block and execute the statement. The reason this rule exists is the programming languages author Guido's desire to create An easy to read, simply designed programming language.

In the example below a simple loop condition was started with no brackets ( ( ) ) stating that one (1) is less then (<) two (2). The colon (:) indicates the start of the loop which would traditionally be represented by an open parenthesis start ( { ). An Enter Key (Carriage return) indicates that line is complete which will bring the cursor down to the second CLI line. Four whitespaces Then indicate the loop block ( ) then the result or return command is entered to match the output of the condition. Pressing Enter again for a new carriage return which would specify the start of the next loop block line. I this second loop line is to have Another loop block command it can be entered again by moving up four (4) whitespaces to enter a new Loop to start with another colon (character). Otherwise to close the loop an Enter carriage return is used to then run the command.


Python unlike PowerShell or C# that access the .NET Framework for classes, doesn't have a large repository of native modules, classes, data types or functions built into the programming language or IDLE shell. Instead Python relies on the parent company "Python Software Foundation" to extend Pythons native capability with ongoing updates to the programming language and through modules officially, and through community created third party modules unofficially.

Modules are contained code that is either developed by Python org or contributed as open source by public users that extend the capability of Python to achieve many new features. Modules can be local or online files that are downloaded and installed into the host shell that then loads the code into the environment runtime for use in that interactive session. Once the session is closed and the runtime is stopped the modules are then removed from memory and will need to be imported again.

There are 2 types of modules, local modules which are packaged with the python installation and can be loaded to runtime anytime by the shell, and online modules which require a package installer software to connect to the package repository and download the files for installation at runtime, then the user may import.

Finding current locally installed modules

To find the list of native installed modules you may use any of the commands below.
Import pip
sorted(["%s==%s" % (i.key, i.version) for i in pip.get_installed_distributions()])
Or you may use the even better commands below to find the modules/variables loaded
 will give you the list of in scope variables:
 will give you a dictionary of local variables
 will give you a dictionary of global variables

Then to find all functions and variables in a module use the dir() function with the module encapsulated with single quotation marks

Or the function can be nested.

Or you may use pip pythons package manager tool to find the modules installed locally.

Import pip
sorted(["%s==%s" % (i.key, i.version) for i in pip.get_installed_distributions()])

Find all available modules for import

• In the standard Python interpreter which is what you are using with PowerShell, you can type

• In ipython you can type "import + [Tab key]".
• At the command-line For Linux, you can use pydoc modules.
• At the Command-Line for Windows,
py -m pydoc modules

• In a script, call pkgutil.iter_modules().

Online Modules using PIP The PIP repository looks back to the python online repository for all python developer and user developed modules when attempting to locate a module. Users themselves may upload their own python modules for other users to find using PIP.

To start using downloading and using modules from the web repository you will have to run pip (the native python package installer module installed and compiled with the latest python3 releases. To do so type "py -m pip install ModuleName" in Powershell running as administrator, and replace modulename with the name of module you would like to download.

e.g. will install the readline module on the current host environment session at the CLI execution
py -m pip install readline

command line switch -m allows modules to be located using the Python module namespace for execution as scripts. a module located using -m is executed just as if its filename had been provided on the command line.

The py starts Python, the -m switch/parameter stands for modify, pip is to use the default package manager/installer software pip, install is the swtich to install the software and readline is the name of the module we want to install on our environment locally from the internet.

If the module is not available then an error will appear that the module cannot be downloaded and the installation will fail. On successful install the below the below screenshot output will appear with no error.

Pip will also need to be upgraded if not already as the above screenshot shows an output that pip package manager is out of date. In PowerShell run this command
python -m pip install --upgrade pip
to update pip.

Python built-in functions

Python 3 includes many inbuilt functions as part of the Python programming language. The below table outlines some of the many common built in functions used in Python administration and the description of the commands that can be used.

Function Description
abs() Returns the absolute value of a number
all() Returns True if all items in an iterable object are true
any() Returns True if any item in an iterable object is true
ascii() Returns a readable version of an object. Replaces none-ascii characters with escape character
bin() Returns the binary version of a number
bool() Returns the boolean value of the specified object
bytearray() Returns an array of bytes
bytes() Returns a bytes object
callable() Returns True if the specified object is callable, otherwise False
chr() Returns a character from the specified Unicode code.
classmethod() Converts a method into a class method
compile() Returns the specified source as an object, ready to be executed
complex() Returns a complex number
delattr() Deletes the specified attribute (property or method) from the specified object
dict() Returns a dictionary (Array)
dir() Returns a list of the specified object's properties and methods
divmod() Returns the quotient and the remainder when argument1 is divided by argument2
enumerate() Takes a collection (e.g. a tuple) and returns it as an enumerate object
eval() Evaluates and executes an expression
exec() Executes the specified code (or object)
filter() Use a filter function to exclude items in an iterable object
float() Returns a floating point number
format() Formats a specified value
frozenset() Returns a frozenset object
getattr() Returns the value of the specified attribute (property or method)
globals() Returns the current global symbol table as a dictionary
hasattr() Returns True if the specified object has the specified attribute (property/method)/td>
hash() Returns the hash value of a specified object
help() Executes the built-in help system
hex() Converts a number into a hexadecimal value
id() Returns the id of an object
input() Allowing user input
int() Returns an integer number
isinstance() Returns True if a specified object is an instance of a specified object
iter() Returns an iterator object
len() Returns the length of an object
list() Returns a list
locals() Returns an updated dictionary of the current local symbol table
map() Returns the specified iterator with the specified function applied to each item
max() Returns the largest item in an iterable
memoryview() Returns a memory view object
min() Returns the smallest item in an iterable
next() Returns the next item in an iterable
object() Returns a new object
oct() Converts a number into an octal
open() Opens a file and returns a file object
ord() Convert an integer representing the Unicode of the specified character
pow() Returns the value of x to the power of y
print() Prints to the standard output device
property() Gets, sets, deletes a property
range() Returns a sequence of numbers, starting from 0 and increments by 1 (by default)
repr() Returns a readable version of an object
reversed() Returns a reversed iterator
round() Rounds a numbers
set() Returns a new set object
setattr() Sets an attribute (property/method) of an object
slice() Returns a slice object
sorted() Returns a sorted list
@staticmethod() Converts a method into a static method
str() Returns a string object
sum() Sums the items of an iterator
tuple() Returns a tuple
type() Returns the type of an object
vars() Returns the __dict__ property of an object
zip() Returns an iterator, from two or more iterators

Visit next page to learn about - Profiles