Fighting The Python

A random spin-off for today, but thankfully a much, much shorter post for anyone who bled from their eyeballs when reading my last post! The focus for today is Python; what you’ll read about here is my initial insights. Looking at the clock, this equates to about just under an hour of reading and learning; so don’t expect to see anything too advanced or perhaps even technically perfect (sound the ‘possibly wrong on the internet alarms now please, if you will’).

What is Python?

Everyone, I’m sure, just wants to say it’s a big-ass snake; and of course it is! Programming language wise however, Python is designed to be a very easy to read, terse, dynamically typed language which allows for rapid development. I’m familiar with it from a procedural/scripting sense but Python does support an object-orientated paradigm (something I haven’t looked into as of the time of writing).

So, some re-iteration here but bear with me; the key takeaway points are:

  • Dynamically typed.
  • Standard files use the .py extension.
  • Whitespace sensitive (uses indentation, like F#, to control flow).
  • Similar ethos to F#, easy to read and terse.
  • Allows for rapid development cycles.
  • Information that I’ve gathered so far touts this as a great starter programming language.


You’ve got a few options for getting started. There appears to be multiple online interpreters where you can go and code in Python without downloading any resources:

Python Online Interpreters (Google)

Codecademy also has a course on offer which you can review, which I used as a primer for writing this post (the first few sections at least). The site also has, based on an initial nosey around, some solid looking documentation along with downloads for the latest versions of Python:

Codecademy Python Course (Downloads/Documentation)

As I’m a Windows/Visual Studio kind of guy (something I should probably step away from occasionally to properly fly the ‘Random Coding Journeys’ banner in future!) the examples you’ll see next are formed using the Python Visual Studio templates (for creating a Python Command Line Application).

On debugging the application for the first time you will be prompted to download an interpreter; CPython is the option I selected, but there were various options to peruse so if you try this yourself have a good root around. After one, simple, installation I was away and debugging.

Python VS Interpreter.

Python VS Interpreter.

Python Command Line.

Python Command Line.

So, without further ado, let’s get to some coding!

The Basics

As Python is dynamically typed, as stated before, to get up and running you simply declare a variable name, followed by the equals (‘=’) operator, then a value to start working with data as follows:

language = "Python"

Python then uses a type inference system (much akin to F# again) as you would expect.

Single-line comments are defined using #, with multi-line comments requiring content to be wrapped inside triple double quotes:

#A single-line comment
language = "Python"

A multi-line comment
intNumber = 10

A super-fast blast through the documentation on the site and codecademy illustrates that the +, -, *, / and % operators all function as you would expect. The ** syntactic rule is used for exponential operations. The input/print functions can be used read in/output information to the console respectively. The def keyword is used to define functions (parameters can be supplied using parentheses). In a slight syntactic twist to what I’m used to, colons are used at the end of if, elif, else, try and except statements before any newlines/indentation:

#Classic Hello World - Just in case you really, really wanted to see it!
print ("Hello World")

print (5 + 5)       #Addition (10)
print (10 - 5)      #Subtraction (5)
print (5 * 5)       #Multiplication (25)
print (10 / 5)      #Division (2.0)
print (10 % 4)      #Modulo/Modulus (2)
print (10 ** 2)     #Exponential (100) 

#Get a number input from the user
intValue = input("Enter any number: ")

#No checking on ints here - Completely unsafe cast (gulp!)

#Notice the use of colons here. Stardard ==, <, >, etc operators are fine. Can also define an 'in' statement (if, elif and else supported)
if int(intValue) <= 8:
    print("intValue less than or equal to 9")
elif int(intValue) in (9, 10, 11):
    print("intValue in 9, 10, 11")
    print("intValue is greater than or equal to 12")

#Retrieve another input from the user
intValueTwo = input("Enter another number: ")

#Illustrate some other decision making constructs. 'or' and 'and' are substituted (when compared to C#) for && and ||
if int(intValueTwo) == 0 or int(intValueTwo) == 1:
    print("intValueTwo is 0 or 1")
elif int(intValue) > 10 and int(intValueTwo) == 2:
    print("intValue is greater than 10 and intValueTwo is equal to 2")
    print("Some other condition")

Sample Application

To finish this post off here’s an incredibly rudimentary code sample that’s designed to calculate the hypotenuse of a right-angled triangle (with the lengths of the two shorter sides of the triangle provided):

A basic example of using python: Pythagoras' Theorem (and a multi-line comment!)
#Import math helpers as required
from math import sqrt, floor

#Create a function up front to parse the input to an integer (that's all I'm allowing for now). Basically to demonstrate very simple error handling
def intTryParse(value):
        return True
    except ValueError:
        print("Could not convert input value to an integer.")
        print("Unknown error occurred whilst processing the input.")
    return False

#Create a function to calculate the third side (assuming we have a right angled triangle!) of a triangle based on the two side lengths provided
def calculateTrianglesThirdSide(firstSideLen, secondSideLen):
    return floor(sqrt((firstSideLen ** 2) + (secondSideLen ** 2))) #Use floor to round, ok with the slight inaccuracy (I just wanted to use more helper functions)

#print to the console - We're here and we are alive!
print ("Pythagoras Example (calculate Hypotenuse)\r\n=========================\r\n")

#Get string based input from the user for the first two sides of the triangle
sideOne = input("How long is the first shortest side of the triangle: ")
SideTwo = input("How long is the second shortest side of the triangle: ")

#Only proceed if both values provided are integers
if intTryParse(sideOne) and intTryParse(SideTwo):
    #Both values provided for the first two sides parse correctly (strip space from the values)
    sideOneInt = int(sideOne.strip())
    sideTwoInt = int(SideTwo.strip())

    #Calculate the remaining side using the values provided (output to the console)
    print (calculateTrianglesThirdSide(sideOneInt, sideTwoInt))
    #Invalid input - Cease processing
    print ("Processing halted due to invalid input.")

Thanks for reading, until the next time…

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s