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.

Setup

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 python.org 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
www.python.org (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 python.org 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")
else:
    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")
else:
    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):
    try:
        int(value.strip())
        return True
    except ValueError:
        print("Could not convert input value to an integer.")
    except:
        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))
else:
    #Invalid input - Cease processing
    print ("Processing halted due to invalid input.")

Thanks for reading, until the next time…

Codecademy.com – JavaScript Course Impressions

In my day to day job we use JavaScript in anger (or at least have to deal with it) on a sporadic basis. We dive into T-SQL, C# (either for server side logic in web applications or for desktop applications) and other parts of web development (CSS and HTML) on a rapidly spinning merry-go-round of coding fun. The variation is great but getting some solid exposure time is also nice to have. JavaScript in particular, as a pillar of web development (alongside HTML and CSS), is something that I’ve wanted to spend more time on (even though I have a solid grounding now); so I’ve decided to slowly edge my way towards a Microsoft Certification. Namely, the MCSD: Web Applications Certification.

This ties in nicely to a personal goal of mine to test out codecademy.com; just to take it for a spin more than anything else. So, I’ve signed up in order to run through the beginner JavaScript course; just to give my impressions on it (and to see if anything can be gleaned – Start with the basics and work on up!).

Although the content is basic, I actually found it pretty well laid out; I can imagine somebody new to coding finding this fairly easy to follow which is fantastic. The interface is clean and simple.

The basics of throwing dialogs are covered early on (confirm and prompt – I haven’t seen alert yet however), along with a simple discussion on datatypes (numbers, strings and booleans as you’d expected). The classic debugging aid that is console.log is also discussed (always a bit of a go to I find!).

Beyond simple mathematical operations and string manipulation techniques I came across the first thing, that is always on the periphery of my mind and can easily catch you unawares (that differs slightly to the C# world so all the more easy to get it wrong); the equality operators. In order to compare that something is of equal value and equal type ‘!==’ and ‘===’ must be used, a subtlety worth remembering and easy to trip up on when the old noggin’ is not switched on.

Comparison Operator Differences.

Comparison Operator Differences.

The full w3schools documentation relating to this can be found here:

JavaScript Comparison Operators

Also, I tried to throw the site out a few times by leaving some humdinger code in place; all handled well in every instance:

Does It Catch Mistakes?

Does It Catch Mistakes?

Does Not Compute!

Does Not Compute!

I did, in some areas, go out of my way to code the examples slightly differently to how it was specified (looking to get the same result of course in all cases) and, for the most part, it seemed quite resilient to this (including the use of functions not specifically mentioned in the examples).

The little section regarding comments was a joy to behold. I’m well known for writing a tonne of comments; pretty sure everyone hates trawling through them (what can I say, it’s a habit!). This is certainly what comments often boil down to however:

What Code Comments Are Really About!

What Code Comments Are Really About!

You also get offered up the classic programming golden nugget; the piece of knowledge no one can do without – The origin of the term debugging! Always a classic!

Lastly, I actually quite like working with zero intellisense. It’s always useful to get that little nudge in the back; a prod to say ‘hey you, switch on and get your act in gear. I’m not going to auto-complete everything for you and let you tab your way to glory!’. I’ve actually sat down in the past and done rudimentary C# programming and very basic websites using notepad alone; well worth doing in my opinion.

It’s been an interesting side-line at any rate so I’ll continue on for now. I’ll plan to move on to the w3schools Certification as a middle ground, before MCSD Certification, so more to follow shortly.

Cheerio!