Say "Hello World" and Learn How to Print

Simple text printing.
This assignment is due on Thursday, January 14
7 exercises
4.0 possible points
Create a subfolder named 0001-hello-world inside your compciv-2016/exercises folder.
Table of contents

The Checklist

In your compciv-2016 Git repository create a subfolder and name it:

     exercises/0001-hello-world

The folder structure will look like this (not including any subfolders such as `tempdata/`:

        compciv-2016
        └── exercises
            └── 0001-hello-world
               ├── a.py
               ├── b.py
               ├── c.py
               ├── d.py
               ├── e.py
               ├── f.py
               ├── g.py
    
a.py 1.0 points Print "hello world"
b.py 0.5 points Deliberately crash the program with a `NameError`
c.py 0.5 points Print a string literal that itself contains quotation marks
d.py 0.5 points Print a string literal that itself contains both kinds of quotation marks
e.py 0.5 points Print the number of characters in the Gettysburg Address
f.py 0.5 points Crash a program with a SyntaxError
g.py 0.5 points Deliberately cause an IndentationError

Background information

This is a series of exercises that involve Python's humble print() function, including writing and executing the classic "hello world" statement.

To reiterate Dennis Ritchie and Brian Kernighan wisdom:

"The only way to learn a new programming language is by writing programs in it. The first program to write is the same for all languages:

Print the words

         hello, world

This is the basic hurdle; to leap over it you have to be able to create the program text somewhere, compile it successfully, load it, run it, and find out where your output went. With these mechanical details mastered, everything else is comparatively easy."

There's some surprising nuance that the "hello world" program provides even when approaching a modern language like Python.

So I'll use this first set of simple exercises to demonstrate the general process of interacting with Python, writing a script, then pushing it to Github.

Set up your Github repo

This will easily be one of the most annoying parts of the class. It's not about smarts or skills – it's mostly: let me get you set up, followed by just go through the motions for now.

Read the guide here:

Using no-frills Git and Github from the command-line

Create the 0001-hello-world subfolder

Let's assume your Git repo is set up on your computer at: ~/Desktop/compciv-2016.

Using Sublime Text, you can open that folder (because it is, after all, just a file folder) as a project. Then right-click on the project-panel to create folders as you please.

Or (and this is recommended…eventually) you can do it from the command-line. Pop open the Terminal:

Then use cd to change into the target directory. Use the Tab key as much as possible to autocomplete the file name:

$ cd ~/Desktop/compciv-2016

(Do not copy the $ – I use that to indicate that we are in the system shell, not in ipython)

The compciv-2016 folder should contain a exercises subfolder. If not, you can create one like this:

$ mkdir exercises

Then to make the directory for the homework:

$ mkdir exercises/0001-hello-world

Now, change into that directory: we want to be able to run scripts like this:

(Note: Unless you've created a.py, this command will fail…)

$ python a.py

Not like this (i.e from above/outside the subdirectory):

$ python exercises/0001-hello-world/a.py

Test things out in interactive Python

The details and instructions for the rest of these exercises are in bottom remainder of this page. Let's just do the very first one: a.py.

It asks us to create a script that simply prints out:

hello world

Pretend we don't know how to do even that, nevermind how to actually write a script, and then "execute" it.

So let's jump into the interactive Python shell – which you can invoke with:

$ ipython

Don't mix up the Python shell with your normal system shell

Jumping into ipython should bring up a deluge of text:

Python 3.5.1 (default, Dec 17 2015, 20:05:34) 
Type "copyright", "credits" or "license" for more information.

IPython 4.0.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: 

And so maybe it seems obvious that you're in Python land instead of your system shell. But it's easy to forget, especially since some of the commands (such as ls) are shared between them.

When writing out instructions, I will indicate that I'm on the Python shell with a prompt that uses triple-angled brackets:

>>> print("hi")
hi

That second hi indicates that the print("hi") command was successful.

So let's fulfill the requirements of a.py:

>>> print("hello world")
hello world

That seems to fit the requirement of: the output to screen should look like:

hello world

Creating our first Python script: a.py

We know our simple program works. Now we need to save the code as an actual file, i.e.

compciv-2016/exercises/0001-hello-world/a.py

Or, if you were to open it in a file tree:

compciv-2016
  |__exercises
       |____0001-hello-world
              |______ a.py

If you're uncomfortable with creating directories and files via command-line, go ahead and do it via the Sublime Text panel (right click in the 0001-hello-world folder to bring up the pop-up menu).

Then enter the Python code and save the file:

print("hello world")

Did it work?

OK, jump back into your Terminal and command-prompt.

Change into the 0001-hello-world/ subdirectory – again, if you're on OSX and you put your compciv-2016/ folder on your Desktop, this should do it – again, use Tab key as much as possible to autocomplete. If nothing happens when you double-tap, it probably means you aren't where you think you are…:

$ cd ~/Desktop/compciv-2016/exercises/0001-hello-world

Now run the a.py script via the Python interpreter:

$ python a.py

The output should be as expected:

hello world

Push your changes to your Github repo

Finally, invoke the usual cycle of git commands to add, commit, and push that new file to your Github repo:

(throw in a git status at any point to have a better grasp of what's going on)

$ git add --all
$ git commit -m 'a.py'
$ git push 

If the command goes through, visit your compciv-2016 repo and confirm the addition. After awhile, you'll accept that Git pretty much works like clockwork.

Note: in newer versions of Git, it shouldn't matter if you're in compciv-2016/ or compciv-2016/exercises/0001-hello-py/ when running the Git commands. If you're having problems, it shouldn't hurt to jump back into the compciv-2016 directory. Using the cd command with double dots, .., will move you up/"back" a directory. Run the pwd command to see where you currently are.

The Exercises

0001-hello-world/a.py » Print "hello world"

0001-hello-world/a.py
Print "hello world"
1.0 points

The easiest and most ubiquitous and most important program in computer science.

Expectations

When you run a.py from the command-line:

0001-hello-world $ python a.py
  • The program's output to screen should be:
    hello world
Some takeaways from this exercise:
  • You know how to call the Python interpreter from your system’s shell/command-line.

  • You know how to execute a function: in this case, the print() function.

  • You’re acquainted with the concept of string literals – not all text is meant to be translated into a computer command. Quotation marks delimit text that is meant for humans, e.g. "hello world" – and text that is meant to be directly interpreted by the computer (e.g. print())

  • You know how to print text to screen. If you’re new to programming, word of warning: unlike consumer software, your programs do not by default talk to you or let you know what’s going on (at least, not until it’s too late).

  • You know how to tell the Python interpeter to read a text file and turn it into commands that control your computer. This is an often overlooked but incredible first step.

0001-hello-world/b.py » Deliberately crash the program with a `NameError`

0001-hello-world/b.py
Deliberately crash the program with a `NameError`
0.5 points

Errors happen. Fixing them with confidence requires not panicking.

You already know how to print out the string literal, "hello".

Try to print "hello" (or any string of characters) without quotes and see the error message that comes up.

For this exercise, write a script that successfully prints "hello", then crashes due to a NameError in the second line.

Expectations

When you run b.py from the command-line:

0001-hello-world $ python b.py
  • The program's output to screen should be:
    hello
  • The program should crash because of a NameError with an error message, similar to:
    NameError: name 'world' is not defined
Some takeaways from this exercise:
  • Errors aren’t so bad. Try to see where something you actually wrote in the code is quoted in the error message.

  • If a text word is unquoted, e.g. world , the Python interpreter will interpret it as an actual command, function, object – i.e. it won’t interpret world as just some piece of text to print or otherwise manipulate.

  • Jumping ahead of ourselves: if world had been brought to existence (e.g. declared as a variable, which we will cover later), then the Python interpreter would know what to do with it. However, without such direction, the Python interpreter will shut the show down.

  • Why is the interpreter (and computers, in general) so picky? As you get better at programming, you’ll learn to appreciate programs that crash as soon and as nosily as possible, and fear the programs that are “silent but deadly.”

0001-hello-world/c.py » Print a string literal that itself contains quotation marks

0001-hello-world/c.py
Print a string literal that itself contains quotation marks
0.5 points

Inevitably, sometimes what we want to print contains quotation marks. Write a program that prints this on a single line:

Bob says, "Hello!"

Remember that single-quotes can be used to delimit a string literal. Try it out in ipython:

>>> print('he says to "go already"')
he says to "go already"
Expectations

When you run c.py from the command-line:

0001-hello-world $ python c.py
  • The program's output to screen should be:
    Bob says, "Hello!"
Some takeaways from this exercise:
  • Either single- or double-quotes can be used to delimit a string. Just be consistent.

0001-hello-world/d.py » Print a string literal that itself contains both kinds of quotation marks

0001-hello-world/d.py
Print a string literal that itself contains both kinds of quotation marks
0.5 points

Inevitably, the string literal we want to print contains both kinds of quotation marks. Use the escape character – i.e. the backslash \ – to construct a proper string.

Here’s an example you can try in ipython:

>>> print("He says \"Yo\" to your dad")
He says "Yo" to your dad

Now write a program that prints this:

Susan's water buffalo looked at me and said, "Goodbye!"

Expectations

When you run d.py from the command-line:

0001-hello-world $ python d.py
  • The program's output to screen should be:
    Susan's water buffalo looked at me and said, "Goodbye!"
    
Some takeaways from this exercise:
  • The backslash character is one of our first encounters with a metacharacter, a character that represents something more than just a text character.

  • A backslash affects the character that immediately follows it.

  • Referring to the backslash as an escape character (aka an escape sequence), can be thought of as: the presence of a backslash before an otherwise special character – e.g. a quotation mark – let’s that character “escape” into a more ordinary meaning, i.e. a quotation mark no longer delimits string literals – it is just a literal text character itself.

0001-hello-world/e.py » Print the number of characters in the Gettysburg Address

0001-hello-world/e.py
Print the number of characters in the Gettysburg Address
0.5 points

You’re well acquainted with the print() function by now. Let’s throw in the len() function, which similarly takes in a literal string as an argument and returns its number of characters:

>>> len("Hey")
3

Note: there is a difference between a function returning a value and printing something to screen. Try saving the above code to a script, executing, and seeing the output. It’s not yet time to ditch print() just yet…

Apparently there are more than one version of Abe’s famous speech; use the version found at ourdocuments.gov. Copy everything from "Four score" to "perish from the earth." (including the closing period mark). The text that you copy should also have line breaks/newline characters between the paragraphs.

Expectations

When you run e.py from the command-line:

0001-hello-world $ python e.py
  • The program's output to screen should be:
    1308
  • The program must call the len() function at least once.

Some takeaways from this exercise:
  • Newline characters count as text characters

  • Python strings can be multi-line as long as they are properly delimited by quotation marks. Good thing President Lincoln didn’t use such marks in the text.

  • It is possible to call a function on the result of another function, e.g.

    print(len("hello world"))

0001-hello-world/f.py » Crash a program with a SyntaxError

0001-hello-world/f.py
Crash a program with a SyntaxError
0.5 points

Write a program that crashes due to a SyntaxError due to missing parentheses in a function call.

Expectations

When you run f.py from the command-line:

0001-hello-world $ python f.py
  • The program should not output anything to screen.
  • The program should crash because of a SyntaxError with an error message, similar to:
    SyntaxError: invalid syntax
Some takeaways from this exercise:
  • In order to call a function, such as print and len, you must include parentheses after the function’s name.

0001-hello-world/g.py » Deliberately cause an IndentationError

0001-hello-world/g.py
Deliberately cause an IndentationError
0.5 points

Write a program that crashes because of an IndentationError

Expectations

When you run g.py from the command-line:

0001-hello-world $ python g.py
  • The program should not output anything to screen.
  • The program should crash because of a IndentationError with an error message, similar to:
    IndentationError: unexpected indent
Some takeaways from this exercise:
  • We haven’t really seen why yet, but indentation is an extremely important feature in Python syntax. At the very least, it keeps lines of code properly left-justified.