This week you'll get more practice with variables and strings. You'll also learn how to make HTML documents using your web application.


  • Python is interesting because there are so many types of quotes
  • Here's a summary:
Name Example Notes
Single Quote 'Hello, world!' Good for general use.
Double Quote “Hello, world!” Good for general use.
Triple Quotes '''Hello, world!'''
“”“Hello World”“”
Needed for multiline strings
Format Strings f“Hello, my name is {name}” Variable interpolation is convenient. You can use double or single or triple quotes too.
Raw Strings r“Newline (\n) is literal” Raw strings don't change the text at all
  • Variable interpolation is when you put the name of a variable in braces in an f-string
    • For example f“The content of the variable foo is {foo}”
    • Variable interpolation is new in Python 3.6
    • That's why the “Run” button doesn't work in Cloud9 IDE


  • There are other ways in Python to make a formatted string
    • A formatted string mixes variables and text
    • They are very common in programming
  • The format function is similar to an f-string

Here are some examples of the format function:

>>> "Hello Mike.".format()
'Hello Mike.'
>>> "This does nothing".format()
'This does nothing'
>>> "Replace these brackets {}".format('with stuff')
'Replace these brackets with stuff'
>>> name = 'Mike'
>>> "Hello, my name is {}".format(name)
'Hello, my name is Mike'
>>> job = 'Nerd'
>>> """Hello, my name is {}
... and I'm a {}""".format(name, job)
"Hello, my name is Mike\nand I'm a Nerd"

Let's take a closer look at each example.

  • By itself format() does nothing.
>>> "Hello Mike.".format()
'Hello Mike.'
  • Format is a function
    • Functions take arguments
    • Arguments are enclosed in parenthesis ( and )
    • Arguments are separated by comas ,
      • The print function with no arguments:
        • print()
      • The print function with one argument:
        • print(“Hello”)
      • The print function with two arguments:
        • print(“The number is:”, 5)
  • Functions can have as many (or as few) arguments as they require.
  • The format function can use literal arguments
>>> "My name is {} and I like {}".format("Mike", "Python")
'My name is Mike and I like Python'
  • The format function often is used with variable arguments:
>>> name = 'Mike'
>>> like = 'Python' 
>>> "My name is {} and I like {}".format(name, like)
'My name is Mike and I like Python'
  • The format function can work on variables too!
  • The variables must contain a string.

Here's an example of formatting a string (it's very common to do this!)

>>> madlib = 'Sometimes, I like to {} with {}.'
>>> verb = 'jump'
>>> noun = 'potatoes' 
>>> madlib.format(verb, noun)
'Sometimes, I like to jump with potatoes.'
  • When you format the contents of a variable the original variable data is preserved
  • You can reuse the contents as much as you want
>>> madlib = 'Sometimes, I like to {} with {}.'
>>> madlib.format('run', 'chickens')
'Sometimes, I like to run with chickens.'
>>> madlib.format('program', 'Python')
'Sometimes, I like to program with Python.'
>>> madlib
'Sometimes, I like to {} with {}.'
  • An f-string is really just a cleaner way to use the format() function.
  • But you can't store an f-string in a variable the same way
>>> noun = 'run'
>>> verb = 'chickens'
>>> madlib = f'Sometimes, I like to {noun} with {verb}.'
>>> madlib
'Sometimes, I like to run with chickens.'
>>> noun = 'program'
>>> verb = 'Python'
>>> madlib
'Sometimes, I like to run with chickens.'
# The madlib didn't change!
  • Sometimes you need to put braces { and } into a format string
  • But the format string wants them.

Here's how you escape braces:

>>> f'{{ }}' 
'{ }'
>>> '{{ }}'.format()
'{ }'

Here's an example of when you would use the double brace to print correct CSS:

>>> '''body { padding-top: {}; }'''.format('1.5em')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: ' padding-top'

It's an error because Python tries to teat padding-top as a variable. To escape the braces you want to leave in double them like this:

>>> '''body {{ padding-top: {}; }}'''.format('1.5em')                                                                                                                                             
'body { padding-top: 1.5em; }'

Old-Style Formatting

The format() function was not always in Python. Formatting used to be done using the % (modulus) operator. There are still many programs that do it this way and it still works in Python 3. However, it's not as easy as the format() function and it's further use is discouraged. In programmer speak it's deprecated.

Here's an example of how to use the format (%) operator:

>>> 'I have %s bikes' % ('fast')
'I have fast bikes'
>>> 'Sometimes, I like to %s with %s' % ('format', 'strings')
'Sometimes, I like to format with strings'
  • Notice that instead of {} you see %s
  • The %s tells Python to look for a string.
  • If you want numbers you have to use other formatters
    • %d for an integer
    • %f for a floating point number
>>> 'I have %d bikes' % (2) 
'I have 2 bikes'
>>> 'I have %f bikes' % (2.5) 
'I have 2.500000 bikes'
  • The format strings come from the C programming language's printf() function.
  • It's very easy to make mistakes (too easy!)

Picking the wrong number type is a common mistake:

>>> 'Drive %d more miles.' % (3.7)
'Drive 3 more miles.'
# Oops! I asked for an integer but supplied a float

Some combination of format operators “explode” when you use them:

>>> 'Drive %d more miles.' % ("many")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not str

Prompting the User and Type Conversions

Most programs need input of some kind. This is a preview from next week to get you started with user input.

  • Python can read input from the command line with the input() function.

Example of input:

>>> foo = input()
Hello, computer
>>> foo
'Hello, computer'
  • The input function returns a string (even if the user types a number).
>>> foo = input()
>>> foo
>>> type(foo)
<class 'str'>
  • Returning a string can be a problem if you want to do math.
  • In Python you can turn a string into a number using int() and float()
  • Be careful, you will cause an error if you try to convert something that can't be converted.

This works:

>>> num = int(input())
>>> num
>>> type(num)
<class 'int'>

This is an error:

>>> num = int(input())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'twelve'
  • You can use the str(), int() and float() functions to convert variables or literals too.
  • Everything can be a str()
  • The numerical types have obvious restrictions.

Here's an example of doing type conversion on a variable:

>>> num = '12' # Not right! That's a string. 
>>> num = int(num)
>>> num
>>> type(num)
<class 'int'>

Advanced Formatting

  • The advantage of the format() function and f-strings is that they are easy!
  • Here are some useful features of the format() function.

You can use arguments in any order:

>>> "{1} is {0}".format('down', 'up')
'up is down'

You can reuse arguments:

>>> "{0}, {0} and {1}".format('up', 'away')
'up, up and away'

You can make arguments work similarly to an f-string:

>>> 'Hello, my name is {name}'.format(name='Mike')
'Hello, my name is Mike'

Introduction to HTML

  • HTML is the language of the web
  • HTML is the source code for web pages
  • HTML is easy!

HTML Tags and Attributes

  • The most basic element of HTML is a tag.
  • Tags have a name that's surrounded with < and >
  • Tags have a beginning tag and an end tag.
    • The tag applies to the stuff in between the beginning and end tags.

Here's a simple example:

<h1>This is the title of my page</h1>
<p>Here is a paragraph.</p> 
  • Many tags control how text is rendered
    • <h1>, <h2>, <h3>, <h4>, <h5> are for headings and subheadings.
    • <i> Makes the font italic.
    • <b> Makes the font bold.
    • <p> Makes text render in a paragraph.
    • <br> Make a line break (otherwise spaced don't matter in HTML).
    • There are many, many more!
  • The <a> tag is very special, it's where the web gets its name.
    • The <a> tag makes a hyperlink
    • It uses an attribute to tell the browser where to navigate.

The <a> tag works like this:

This is a link: <a href="">Google</a>
  • The <a> tag has the href attribute.
  • Attributes appear inside of the < and the >
  • They have the form
    • name=“value”
  • Single or double quotes are allowed
  • Attributes are optional for many tags and essential for some (like the <a> tag)

A Few Examples

  • Here are some useful things to do with HTML

You can make indented lists that are ordered (numbered) or unordered (bulleted)

<!-- This is an HTML comment --> 
<!-- The "ul" tag is for unordered list --> 
  <!-- Each bullet gets the "li" list item tag -->
  <li>A list item</li>
  <li>Another list item</li>
<!-- The "ol" tag is for ordered list --> 
  <li>The first item</li>
  <li>The second item</li>

It's often useful to make a table on a webpage to show organized data.

<table border="5">
  <!-- Table rows are surrounded by the tr tag -->
    <!-- Heading table cells are surrounded by th tags. -->
    <th>Heading 1</th>
    <th>Heading 2</th>
    <!-- Normal table cells are surrounded by td tags. -->
    <td>Row 1, Cell 1</td>
    <td>Row 1, Cell 2</td>
    <td>Row 2, Cell 1</td>
    <td>Row 2, Cell 2</td>

HTML Documents

  • Like any other kind of document HTML pages have some formatting to be complete
  • Browsers depend on some of the formatting tags to render the page properly
    • Having the right page title in the browser
    • Language and character set
    • Other settings…
  • HTML Document rules
    • HTML documents always should begin with the DOCTYPE tag (which doesn't have a closing tag)
    • All tags should be inside of <html> tags
    • There should be a <head> section for header elements
      • Character coding
      • Title
      • Scripts
      • Stylesheets
    • There should be a <body> section for contents

Here's an example of a complete HTML document.

<!DOCTYPE html>
    <meta charset="UTF-8">
    <title>Title of the document</title>
    <p><i>This is a grab line.</i></p>
    <p>This is the paragraph in my page.</p>

Documents and Templates

  • There's a lot of “overhead” in an HTML document
  • By replacing content with “holes” you can use Python's format function to make a generic page.

Here's an example of a program that creates an HTML page based on user input:
page_template = '''
<!DOCTYPE html>
    <meta charset="UTF-8">
title = input('Enter the title of the page: ')
text = input('Enter the text of the page: ')
line = input('Enter the grab line: ')
page = page_template.format(title=title, grab_line=line, content=text)
print (page)

Cascading Style Sheets (CSS)

  • HTML is a language for specifying content
  • HTML is not supposed to tell the browser what the text looks like
    • With a few exceptions like <b> and <i>
  • For changing colors and layout you need Cascading Style Sheets
  • CSS works on specified elements

Here's an example of CSS that applies to a <h1> tag:

h1 {
    background-color: lightblue;
    color: white;
    text-align: center;
  • The CSS rule specifies what of an <h1> tag should look like
  • CSS is specified in a <style> tag

Here's our HTML from before styled up a bit:

<!DOCTYPE html>
    <meta charset="UTF-8">
    <title>Title of the document</title>
	body {
	  background-color: lightblue;
	  font-family: arial;
    	  text-align: center;
	h1 { 
	  color: white;
    <p><i>This is a grab line.</i></p>
    <p>This is the paragraph in my page.</p>