The FizzWife Project: Variables and Functions with a side order of Parameters

February 19, 2011 under The FizzWife Project

  >> [0] Introduction
  >> [1] Hello World
  >> [2] Variables and Functions with a Side Order of Parameters

After completing the “Hello, World!” exercise, Dena was ready to move onto the basics; variables and functions. In writing her “Hello, World!” program, she was introduced to her first function; Python’s print() function. The print() function simply directs supplied input to an output – sys.stdout (aka: the console) in our case.

As she was currently accustomed to directly passing a string literal to print(), I began by describing a few common data types:

  • strings: a series of characters (Ex: “Hello, World!”)
  • integers: whole numbers (Ex: 42)
  • floats: decimal numbers (ex: 3.14)

With her new-found knowledge of a few basic data types under her belt, variables were the next topic on the agenda. I have a habit of using analogies, and my description of variables would not be an exception. To convey the concept, I likened variables to labelled jars, thinking that it may be easier to understand rather than focusing too much on memory addressing. Jars contain a single item and that item can change over time. This led to an improved “Hello, World!” program:

message = "Hello, World!"
print(message)            # displays "Hello, World!"

The realization of the power of variables was unleashed!

message = "Hello, World!"
print(message)            # displays "Hello, World!"
message = "Hi, World!"
print(message)            # displays "Hi, World!"

Strings are fine and dandy, but numbers make the world go ’round. Keeping things simple with whole numbers, I asked her to create a variable to hold her age (actual ages have been changed to protect the innocent):

age = "22"
print(age)             # displays "22"

Hmmm, it seems ok, but is it really? We can find out by pretending it’s her birthday and incrementing her age by one year, as birthdays tend to do.

age = "22" + 1
age = age + 1
print(age)             # TypeError: Can't convert 'int' object to str implicitly

Oh noes! Now the idea of types mentioned way back at the beginning is making sense. A string of characters – two “2” characters beside eachother – can’t be added to the actual number 1 to produce any meaningful output. Would the result be a string; an integer? Answer; it would be nothing because it’s not possible. Dena takes another stab at it:

age = 22
age = age + 1
print(age)             # displays 23

Ah, that’s more like it. Describing data types to non-programmers during their first programming attempts may initially feel like a lost cause. At this point, the only differentiating factor between strings and integers in her mind is either the presense of absence of quotation marks around a value. But Dena’s a quick learner, and she begins to understand what’s going on under the hood. I ask her to display the sentence:

My name is [name] and I am [age] years old.

After rolling up her sleeves, she types out:

name = "Dena"
age = 22
message = "My name is " + name + " and I am " + age + " years old."
print(message)    # TypeError: Can't convert 'int' object to str implicitly

WTMFH?!?! (I’ll leave it to the reader to figure out what that means). There’s that error again. She’s unsure why printing her age, which is an integer, was totally doable before, but now it isn’t when she’s using it to build her sentence (which is a string). As soon as the expletive was out of her mouth, she realised that her problem was attempting to mix data types. What she didn’t know was how to convert variables data types from one type to another. And so, I explained Python’s standard str() function, and that its job is to cast variables from their data type to a string representation. So she put str() to good use:

name = "Dena"
age = 22
message = "My name is " + name + " and I am " + str(age) + " years old."
print(message)    # displays "My name is Dena and I am 22 years old."

Success!

Through the past couple of lessons, Dena’s been using a few of Python’s built-in functions, like print() and str(). She knows what the do, but hasn’t learned what they are yet. I briefly mentioned that functions are just like the functions that she saw in math class in high school; the function takes some variables (parameters) and produces a result. Using str() as an example, I explained the passed in parameter (her age variable) and str() gave her back a result (string representation of her age variable’s value). Her eyes glazed a little, but I assured her that it will all make sense soon, and she’ll even be creating her very own functions. But first, there’s one more data type that she should know about. Perhaps she can make a List of things that she’s learned thus far…

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
comments: 0 »

The FizzWife Project: Hello, World!

January 27, 2011 under The FizzWife Project

Before Dena writes her FizzBuzz implementation, I felt it necessary to explain how a computer actually works and what is involved in the creation of software using a canonical “Hello World” program as an example. I spent the first hour covering the major components within a computer, how they work together and how software makes it all tick. While drawing maniacally on a whiteboard, Dena witnessed my best attempt at describing the hardware’s inner workings of:

  • CPUs and how various architectures differ
  • storage, both primary (ex: RAM) and secondary (ex: hard disks)

After thoroughly confusing and then (hopefully) un-confusing her, the time had come for me to make sense of it all by proceeding to explain how software consists of instructions and how those instructions are executed by the hardware. At some point, I ended up broaching the subject of bits, bytes and binary arithmetic, which eventually led to talk of ASCII character tables.

At this point, she assured me that – after some additional explanation – she was indeed following along. It would seem to me that people who don’t often have to think in terms of systems might have trouble grasping this deluge of techno mumbo-jumbo within the span of an hour, so I feared she was merely humouring me. But she insisted she understood, so I’ll chalk it up more to her being a quick learner and less of me being a decent teacher.

With her newly-acquired knowledge of what those “ones and zeroes” actually mean, I then went on to the basics of software and how “in the old days”, programmers created software by feeding computers punch cards which represented the binary data and instructions that it could understand. This brought us to the first example program; “Hello World” writing in machine code:

01001000 01100101 01101100 01101100 01101111 00100000 01010111 01101111 01110010 01101100 01100100 00100001 00100000

Dena either had a look of terror, disgust or some combination thereof when she saw this. I assured her that software development had come a long way since this sort of programming was the norm, and this would be the only time she’d see something like it.

Next up was the language of the CPUs; Assembly. Harking back to the previous 60 minutes, Dena was made aware that the processors of the various architectures each had their own “readable” language that programmers could use to write software. And so “Hello World” written in x86 Assembly was ready for viewing:

       .MODEL Small
       .STACK 100h
       .DATA
   msg db 'Hello, world!$'
     .CODE
   start:
     mov ah, 09h
     lea dx, msg
     int 21h
     mov ax,4C00h
     int 21h
   end start

While “English” was apparent in this code, I sensed that she was thinking that she bit off more than she could chew by (willfully, I must add) signing up for this experiment. Fears were cast aside when I mentioned that technology evolves quickly and high-level programming languages from COBOL and Fortran, all the way to C/C++, Java, C#, Haskell and [drumroll] Python would make this all worth while. I explained how modern compilers and linkers are special software that take readable code and turn it into machine code that computers can understand. Often, I’d turn to examples that she could relate to in ways such as:

You know at work when you launch Microsoft Word? Well, Microsoft developers wrote a bunch of code (probably in C++) to enable you the user to do all sorts of things like letting you change fonts and their sizes, set margins, print, etc. That code was compiled by a C++ compiler that they use to become that winword.exe file on your computer so that you can simply click on Word’s shortcut and magic happens.

Relating it all in that manner appeared to cement the understanding. Without delving into functions just yet, Dena wrote her first program in a high level programming language. In a style that’s clearly all her own, she wrote a “Hello World” program in Python:

print("Hello, Bitches!")

Some experimentation followed, where she attempted to add some indentation. Her incorrect stabs at it looked like:

        print("Hello, Bitches!")

and:

print        ("Hello, Bitches!")

and:

print(        "Hello, Bitches!")

Eventually, she realized what works:

print("        Hello, Bitches!")

Slightly unsure of herself and why only the last attempt at indentation worked, I commended her first programming victory and that her experimentation conveniently leads us to the next lesson: Variables and Functions with a side order of Parameters.

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
comments: 0 »

The FizzWife Project

January 17, 2011 under The FizzWife Project

Welcome to The FizzWife Project!

The goal of the experiment is to teach my wife Dena, a law clerk with little technical/scientific background, enough about the bare essentials of computer programming so that she is able to successfully implement FizzBuzz on her own.

FizzBuzz, of course, is a problem that Jeff Atwood (Internet) famously summarized as a test of programming ability (and not programming proficiency). FizzBuzz boils down to the following problem statement:

Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

The problem is trivial for experienced programmers, but may present a challenge to non-programmers such as Dena.

A note to all coders out there: please don’t post your own solutions to FizzBuzz in the comments; I will delete them.

The impetus for this experiment actually had little influence from yours truly. In August, Dena and I visited her brother in Kotzebue, Alaska. For the long trip, I packed some books (GASP! real dead-tree versions) to pass the time, and one of those books was Coders at Work. At various points during the trip, Dena – completely of her own volition – picked up and read some of Coders at Work; its conversational nature (and lack of any actual code) proved interesting to her. So much so, that she approached me with interest in learning something relating to what the interviewees in Coders at Work spoke about. I didn’t think she was serious, but she continued to broach the subject even after we returned.

My dilemma was to determine a project or a set of projects that would help her gain understanding of the bare essentials, while at the same time keeping her interest high. The project had to avoid dependencies on computer science-y things like data structures and algorithms, engineering topics like methodologies/paradigms/architectures, and any sort of APIs. Robert “Uncle Bob” Martin recently highlighted that programming, regardless of the language and environment boils down to three things; sequence, selection and iteration. And I think FizzBuzz, while being simple, is an excellent example of these three principles. I also settled on Python as the language she’ll use, to avoid strongly typed languages for the time being and the benefit of using IDLE for REPL purposes. Immediate feedback is a good thing! Also, I feel Python’s syntax is easy for a beginner to understand.

Join Dena and I as she’s introduced to the essence of programming, with the goal of her creating her own FizzBuzz implementation. I’ll post updates on her progress and code snippets, so stay tuned!

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
comments: 0 »

smokin' hash

November 29, 2007 under .NET, C++, MD5, PHP, Python

No, this post will make no mention of bottle tokes.

For the remaining freelance gig in my spare time pipeline (which hopefully is winding down), an ecommerce site, I had to create simple user management system. Obviously, I’m not going to store users’ passwords as plain text in the database, but rather as a hash – an MD5 hash to be exact. Unlike the old days where you had to implement the MD5 algorithm yourself, modern programming environments have this conveniently part of some specific standard library. From PHP, hashing a password (or any other string data) is easily accomplished like this:

$plain_text = "ChrisBellini.com";
$md5_text = md5($plain_text);
// hash is '56d1df360dce2f5025c71fa7697af642'

That hashed value is then stored in the database and I can use it to compare during logins. Easy peasy.

Sometimes, though, I’d like to verify what a hashed string really is. What does “12345” look like after passing through MD5? If you can do that in your head, then you can probably move objects with your mind. For those of us lowly creatures who can’t, though, a simple way to determine this would be nice. I’m a .NET guy in my day job, so a quick console app should suffice. Using .NET’s MD5 library with C# is trivial.

using System.Security.Cryptography;

// ...

string plain_text = "ChrisBellini.com";
UTF8Encoding objEnc = new UTF8Encoding();
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
byte [] arrHashBytes = md5Hasher.ComputeHash(objEnc.GetBytes(plain_text));
// hash is '56-D1-DF-36-0D-CE-2F-50-25-C7-1F-A7-69-7A-F6-42'

That would do the trick, but what if I’m on my Linux computer? I could use Mono, but still… It sure would be nice to be able to do this quickly on any operating system. Enter Python.

import hashlib
 
plain_text = "ChrisBellini.com"
md5_text = hashlib.md5(plain_text).hexdigest()
# hash is '56d1df360dce2f5025c71fa7697af642'

Pop this into Python’s interactive interpreter, Idle, and you’ve got yourself some lovely hash.

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
comments: 0 »

onFrustrate

November 6, 2007 under Internet Explorer, Javascript, Programming

The onChange event for HTML form elements is fired when the value of that element actually changes in Firefox/Seamonkey, Opera, Safari and any other other modern Web browser. It just makes sense. Yet for some lame reason with Internet Explorer, onChange is only fired once the focus on said form element is lost, effectively making onChange act like some freakish onChange+onBlur hybrid. WTF? I’m just wondering what the design reason that the Internet Explorer team at Microsoft came up with could be, is all.

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
comments: 2 »

set @my_balance = select sum(savings_balance) from client_accounts where savings_balance > 0.00

July 25, 2007 under ASP.NET, C++, IIS

Today’s Daily WTF post was one of their funny screenshot articles and one of them struck me as being quite familiar:

IIS Error Message on a Diebold ATM

Die-hard readers of my blog may be thinking that based on the Diebold logo in the picture, that I’m reminded of one of my rants against slow Diebold ABMs. It’s not. That “Object reference not set to an instance of an object” ASP.NET error is the one that makes me shudder – more so, since this is a banking application.

Sometimes this is caused by trying to access variables and object beyond the current scope, but Visual Studio can notice these more often than not during a build. Where I really get nabbed is when trying to access a null object. Sure, sometimes it’s just a slight oversight on my part and I try to access an objects methods and properties without actually instantiating it first. Hey, it happens. Yet, often I find that an object doesn’t instantiate and I don’t find until much later….like runtime later. So I’m now conditioned to try to catch everything:

   MyCoolClass myobject = null;

   try
   {
      myobject = new MyCoolClass();
      myobject.someVoidMethod(SOME_CONSTANT);
   }
   catch (Exception ex)
   {
      Response.Write(ex.Message.ToString());
   }
   finally
   {
      myobject = null;
   }

That’s my two cents, anyway 😉

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
comments: 0 »

visual studio – lessons learned

Note to self:

If you’ve created a page that is correct from a business logic point-of-view, but may not make Visual Studio‘s visual designer happy, don’t open the file in the visual designer. The visual designer wants to correct your “shoddy” HTML. The visual designer thinks that it knows you. It doesn’t. It wants to kill you, and charm your spouse and children so that they forget that you ever existed. Well, maybe not entirely. Regardless, whatever you do, don’t lose your head and think that you can use your VB or C# code-behind to load up some placeholder controls with your own HTML. That’s kids’ talk – crazy talk. Keep it together, man. Pure and simple – don’t view the page in the visual designer. Code view? Yes. Visual designer? No.

That is all 🙂

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
comments: 0 »

coding the painful way for all to hear

February 22, 2007 under Programming, speech recognition, Vista, VoiceCode

Last summer, I posted about a cool open-source project from the National Research Council of Canada, known as Voice Code, that allows developers to code by talking. From the demos that I’ve watched, VoiceCode performs very well, and shows promise. However, Windows Vista includes speech recognition functionality, and doesn’t appear to be on par with VoiceCode in terms of recognition accuracy, as evidenced by this poor soul who attempted to create a simple Perl script with his voice.

It took that guy over ten minutes to “write” simple Perl code to read the contents of a file and print them to standard output! Now I know that it’s not completely fair to compare VoiceCode (aimed at software development tasks) to Vista’s speech recognition capabilities (aimed at general computer use and word processing and the like). But that script was not an example of advanced programming techniques and methodologies – there were no classes, functions, ADT definitions or elaborate syntax.

I guess sometimes, you don’t get what you pay for.

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
comments: 1 »

the python programming language and its love of "whitespace"…eeeew

November 23, 2006 under porn, Programming, Python

A couple of weeks ago, I rebuilt our desktop computer; the ol’ format and reinstall everything shuffle. I like to do it a couple of times a year; usually coinciding with when my annual anti virus subscription expires. It is, however, dreadfully boring downloading and reinstalling the latest versions of the software that I use all over again.

I’ve written a few Python scripts to automate various tasks, so I needed to get a Python interpreter installed on my fresh installation of Windows. After reinstalling a lot of software in a short amount of time, my brain switched to autopilot and I entered python.com in Firefox’s address bar. I hit ENTER and averted my gaze to the TV. When I turned back to look at the monitor, I noticed that there was some “hot oral and anal action” on my screen; two things that aren’t typically associated with Python programming, unless you’re shouting at your computer because the buggy Python script that you’re writing is a pain in the ass. I then noticed the “.com” that I mistakenly entered in the URL and promptly changed it to the proper python.org. I bet python.com gets many visitors who were originally looking for python.org. Yet I wonder if any people looking for python.com accidentally visit python.org and become convinced that writing code would put their to hands to…ahem…better use. I’m glad that porn sites were too late to register clever domain names for other scripting languages’ web sites like Perl; they could’ve had fun with that one 😉

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
comments: 0 »

quick calc

November 2, 2006 under Firefox, Google, Hacks, Python, Ruby

Often, I need to do some quick arithmetic involving multiple operations and don’t have a good calculator handy. There’s a calculator application on my cell phone, but I’m an atrociously slow cell phone typer. Most simple calculator apps, like calc.exe in Windows, are fine for single operations like 2+2 or 67 * 1.14, but for multiple-operation expressions, those simple apps won’t cut it without needing to resort to some copy ‘n’ pasting or [gasp] manual jotting with a writing utensil.

When I’m in front of a computer and I need to quickly calculate an arithmetic expression to figure out sales tax, find averages, multiply numbers too large for my brain to deal with, etc, writing a script or a total application would be overkill. Here are the cross-platform solutions that I find myself resorting to:

Python (python.org)
Python's IDLE
Python’s interpreter is convenient. It allows you to enter any mathematical express and it will evaluate it as if it were a line in a Python script. You could even assign values to variables or other data structures, use loops, conditions, and create functions like you would in any ol’ script.

Ruby (ruby-lang.org)
Ruby's IRB
Ruby’s interpreter has nearly identical features to Python’s interpreter, except that the language is Ruby instead of Python…duh 😉

Mozilla Firefox JavaScript Error Console (mozilla.org/firefox/)
In Firefox, selecting “Error Console” from the Tools menu item will launch the JavaScript Error Console window. The Error Console is useful for debugging JavaScript in Web applications. However, much like Python’s and Ruby’s interpreter, it too can quickly evaluate arithmetic expressions. Its main shortcoming, when compared to the aforementioned Python and Ruby interpreters, is that can only evaluate one line at a time. So you cannot store data in variables, since once you click the evaluate button, your variables are destroyed.
Firefox's JavaScript Error Console

Google (google.com)
Google’s powerful searching abilities are one thing, but did you know that it can also perform calculations (Ex: (99*66)2), unit conversions (Ex: 120 kilometres in miles) and even unit+currency conversion (Ex: help the in laws figure out Canadian gas prices ).

Instacalc (instacalc.com)
I’ve just recently come across this website and haven’t explored all of the features yet. However, it looks very promising. Using AJAX to display answers as you type in your expression is a nice touch.

For Windows users, there’s also the Power Calculator that’s part of the suite of Windows XP PowerToys. I keep it bound to the Calculator key on my keyboard.

better calculators + me = happy

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
comments: 1 »