Module 0.1 - Getting Started: Examples

0.1.0 - Comments

A comment is a note in a program that is designed to be read by human beings. It is not interpreted at all by the computer and will not run anything.

# This is a comment
       # This is also a comment (but not a good one)

print('Good evening.') # This is a comment too
  • In Python, comments being with the # character and run until the end of the line
  • Python completely ignores all comments

To illustrate: Illustrating features of comments

The above program is, as far as Python is concerned:

print('Good evening.')

Comments can be inserted in various places in a program. Let’s run code with comments and look at the output:

# Comments begin with a # symbol and run until the end of the line
       # There can be spaces before the #, but this is less readable
print('Good evening.') # if a comment is after code, the code will run
Good evening.

The output is the same as if there were no comments at all.

Exercise 0.1.1

Exercise 0.1.1

Create a module0.1 folder (if you haven’t already). Write up the above code in comments.py.

Sometimes one needs a comment to spill over multiple lines, such as:

# I wrote this program at midnight
20 seconds before the deadline
print('Good night.')

There is an error on the second line of this code: a # is missing.

0.1.1 - Whitespace

Consider the following program:

print    (   'Hello World!'   )

Notice the spaces inserted in various places.

Consider this variation:

   print('Hello World!')

(There are three spaces before the print statement)

Running this program produces an error - spaces at the beginning of a line (“indentation”) are how Python logically groups code, and improper indentation can cause errors.

Finally look at:

print('Hello      World!')

(Six spaces between Hello and World!)

Exercise 0.1.2

Exercise 0.1.2

Write up the above as whitespace_test_3.py. Try to run the program. What is printed out? Modify the program so there are seven spaces between Hello and World!.

Let’s point out a few things: - Some kinds of whitespace, even if ill-advised, are permitted. - Consistent style makes your code more readable. - The beginning of each line of code must be properly indented. This is why there was an error with the line that was indented before print. - The extra spaces in between Hello and World! in the third example are acceptable, if it is your goal to print them. Printing accepts whatever spaces in the text you provide.

0.1.2 - Strings

A string in Python is a sequence of letters, digits, or symbols (such as & or @) surrounded by either:

  • A pair of double quotes, as in “Hello world!”
  • A pair of single quotes, as in: ‘Hello world!’

Note:

  • Whichever kind of quote (single or double) you use to start a string must be used to end the string.
  • The ending quote must be on the same line as the starting quote.
  • There are special techniques to handle long strings that you want to print over several lines.
  • This might raise some questions:
    • Is it possible to print on a single line using multiple print statements?
    • How does one print a quotation mark?

Python is very particular about code that appears on a single line. Be careful: your text editor can wrap displayed text to a new line if it extends past the edge of your screen, but Python still recognizes this as a single line. Looking at the line numbers in your editor can help you understand when this happens.

print('Here is a very very long line of code to demonstrate what happens when a text editor wraps around')
print('Here is the true next line')

First, note that we can use single or double quotes for different strings in the same program:

print('George')
print("Washington")

Exercise 0.1.3

Exercise 0.1.3

Confirm that George and Washington get printed on two lines by writing the above in print_two_lines.py.

A print statement prints the string within parentheses and then goes to the next line of output, which is why we see Washington on the next line after George.

To keep printing on the same line:

print('George', end=' ')
print('Washington')

Exercise 0.1.4

Exercise 0.1.4

Confirm that this prints on one line by writing the above in string_example_2.py.

The print function, by default, inserts a new line after it has printed the text we give it. Specifying a different end replaces that new line with whatever is specified:

print('something', end=' ')

In the case above, this is a single blank space, but it could be anything (or nothing) at all. Note the comma between the string to print and the word end.

Now we will use a single string containing the instruction to print on several lines:

print('George\nWashington')

Notice the \n inside of the string George\nWashington.

Exercise 0.1.5

Exercise 0.1.5

Write up the above in string_example_3.py. You should see George and Washington printed on separate lines. Change the string (still use only one print statement) to add a blank line between George and Washington.

Strings can include escape sequences, which begin with the backslash, \. Escape sequences are used to print “special characters.” A special character can be something like \n, which represents a new line. A special character can also be \', which represents a literal quotation mark rather than telling Python where a string starts or begins.

print('My friend\'s friend')

Another way is to use double quotes to delimit a string that contains single quotes, or vice versa:

print('My friend\'s friend')
print("baked me an apple pie")
print('and I said "thank you."')

How does one print a backslash? By using a double backslash (a backslash escaped by another backslash.)

print('The backslash character, \\, is printed like this.')

Exercise 0.1.6

Exercise 0.1.6

Write a program called escape_practice.py that prints out:

"   " \\\
"   "  \
"""""  \
"   "  \
"   " \\\

Another use of the backslash is to make long strings:

  • Sometimes we need to type in a very long string
  • The following does not work:
print('The woods are lovely, dark and deep
But I have promises to keep
And miles to go before I sleep
And miles to go before I sleep.')

Exercise 0.1.7

Exercise 0.1.7

Write a program called string_example_4.py with the program above, and run it. What is the error in the output?

To spread a single string over multiple lines, use triple quotes such as:

print('''The woods are lovely, dark and deep
But I have promises to keep
And miles to go before I sleep
And miles to go before I sleep.''')

(You can also use triple double quotes, """.)

Exercise 0.1.8

Exercise 0.1.8

Write a Python program called a_poem.py that prints a short poem over more than one line using a single print statement. This can be any poem of your selection.

Empty strings:

  • It is possible to have a string with nothing in it, such as:
print('')
  • Notice that there are no letters, digits, or anything in between the two single quotes.
  • This is called an empty string.
  • Empty strings are useful (we will see later) when we want to combine strings to make a longer string.

0.1.3 - Case Sensitivity

What would happen if we used uppercase P instead of lowercase p in print ?

Print('Hello World!')

Exercise 0.1.9

Exercise 0.1.9

Write up the above program in case_error.py and run it. What is the error you get? Fix the error.

What if we changed the case inside of a string?

print('helLo wOrLd!')

Exercise 0.1.10

Exercise 0.1.10

Write up the above program in string_example_6.py and run it to see if it works.

Python is case sensitive, but strings are like data inside of programs, which means they can take on any value we give them.

  • The two strings 'Hello World!' and 'helLo wOrLd!' are fine as two different strings, if that is our intention.
  • Python only has one print function and does not recognize Print (with an uppercase P).

0.1.4 - A Peek At The Future

We will occasionally jump ahead and present an example of a program that does something advanced, just so you get a feel for what’s coming. With these examples, we’ll only ask you to type up the program and run the program.

And then we’ll point out a few features, just so that you get acquainted with features that you’ll eventually encounter.

import tkinter as tk

window = tk.Tk()
canvas = tk.Canvas(master=window, width=500, height=400)
canvas.pack()

for i in range(1, 10):
    fontSize = i * 20
    fontStr = 'Times ' + str(fontSize) + ' italic bold'
    startx = 200 + 10 * i
    starty = 20 + i * 20
    canvas.create_text(startx, starty, text="Hello", font=fontStr, fill='grey')

window.mainloop()

Exercise 0.1.11

Exercise 0.1.11

Write up the above program in hello_gui.py,being careful to type it in exactly as shown above, paying attention to every keystroke. Run it to get something like:

gui display output

If something went wrong with the typing, you can instead download hello_gui.py but only after giving the typing a good try. Now let’s point out a few features of the program, and we’ll focus on the middle section:

code features

By showing you bits and pieces of advanced code, you’ll be ready to absorb these concepts when we work through them.

One of the most important things to observe about is that some code is indented:

indentation

0.1.5 - A Reminder About Computer Skills

As you complete Module 1 and ready that for submission you might want to review:

  • Did you make your module0.1 folder? Did you ensure that the m in module0.1 is lowercase and that there’s no space between module and 1 ?
  • Are your Python programs from this module in that folder?
  • Do you recall how to make a zip? If it’s a bit hazy, please make sure to review from the material about computer skills.
  • Finally, make sure you understand the instructions for how to submit your work.

End-Of-Module Problems

Full credit is 100 pts (complete at least three problems). There is no extra credit.

Problem 0.1.1 (40 pts)

Problem 0.1.1 (40 pts)

Write a program that prints the following to the console:

DC's weather is beautiful.

Submit as escape_quote.py.

Problem 0.1.2 (40 pts)

Problem 0.1.2 (40 pts)

Write a program that prints the following to the console:

"How do I get to the river?" She asked.

Submit as escape_double_quote.py.

Problem 0.1.3 (40 pts)

Problem 0.1.3 (40 pts)

The following program intends to print:

The orange line doesn't go to Cleveland Park!
You could use the "virtual tunnel" at Farragut.
print('The orange line doesn't go to Cleveland Park!\nYou could use the "virtual tunnel" at Farragut.')

Fix the error(s). Submit as print_errors.py

Problem 0.1.4 (40 pts)

Problem 0.1.4 (40 pts)

The following program intends to print:

Hello,
   world
      !
print("Hello,")
   print("world")
   print(   "!")

Fix the error(s). Submit as whitespace.py

Be careful that you reproduce the desired output, including spaces, exactly.