Last week you made your first program. Here are some of the key concepts that you learned:

  • Syntax
    • The print statement starts with the word print
    • What to print is enclosed with ( and )
    • Text to print is quoted with quote marks or ticks “Text” or 'text'
  • Sequential execution. Programs operate in order:
print ('Hello 1')
print ('Hello 2')
print ('Hello 3')

Executes from top to bottom, therefore outputs:

Hello 1
Hello 2
Hello 3
  • Comments
    • Code after a # is ignored by Python
    • The # can appear anywhere in a line

The Python REPL

  • The Python interpreter lets you run one command at a time
    • So you can “try” your Python statements before you put them in your program
  • Single command mode is called the Read-Evaluate-Print Loop or REPL
  • Starting the REPL is just like starting a Python program, except you don't specify the program.
matera:~/environment $ python3.6
Python 3.6.2 (default, Nov  2 2017, 19:34:31) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux
Type "help", "copyright", "credits" or "license" for more information.
  • The »> prompt is where you enter Python commands.
  • In class you'll see me use the REPL to demonstrate new commands

For example, running the print command in the REPL looks like this:

>>> print ('Hello World') 
Hello World
  • The REPL prints the return value of the command. (That's the “P” in REPL)
    • Normally return values are not printed in python programs
    • You'll learn more about return values later
  • Entering literals in the REPL repeats the literal

Example: literals in REPL

>>> 'Hello World' 
'Hello World'
>>> 10
>>> math.pi
>>> None

Literals and Data Types

  • In programming a literal is a plain old value written in a program.
    • Numbers
    • Strings
    • Special values

Here is an example of literals in Python

print (10)             # The integer 10 is a literal 
print (1.2)            # The floating point number 1.2 is a literal 
print ('Hello World')  # The string 'Hello World' is a literal 
print (True)           # The special values True and False are literals 
print (None)           # In Python, None is a special value and a literal 
  • Literals have a data type. The data type describes what the literal is.
  • The data type determines how the value can be used
  • The type() function in Python tells you the datatype of a literal or a variable.

Try this using the Python command line:

$ python3.6 
Python 3.6.2 (default, Aug 27 2017, 23:19:08) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> type (10)
<class 'int'>
>>> type (10.1)
<class 'float'>
>>> type(True)
<class 'bool'>
>>> type (None)
<class 'NoneType'>

Mathematical Operations

  • Computers are good at math!
    • They don't get bored and almost never make mistakes.
  • Math and other operations may be affected by the data type
  • Here are some key operations:
Symbol Meaning Example(s)
+ Addition (for numerical types)
Concatenation (for string types)
1 + 2 == 3
“foo” + “bar” == “foobar”
- Subtraction 2 - 1 == 1
/ Division 12 / 4 == 3
* Multiplication 5 * 5 == 25
% Modulus (a.k.a. the remainder) 12 % 10 == 2
24 % 10 == 4
< Less than (comparison) 2 < 3 == True
3 < 2 == False
> Greater than (comparison) 2 > 3 == False
3 > 2 == True
Less than or equal 2 ⇐ 2 == True
>= Greater than or equal 2 >= 2 == True
== Equal to 5 == 5 == True
  • Order of operations
    • What is the result of this operation?
print (3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)
  • Python, like most programming languages, uses an order of operations called PEDMAS
    • Parenthesis (this is done first)
    • Exponents
    • Multiplication
    • Division
    • Addition
    • Subtraction (this is done last)


Here's an example program that uses mathematical operators

print ('My favorite number is:', 4)
print ('Two times my favorite number is:', 4 * 2)
print ('Two plus my favorite number is:', 4 + 2)

Examine the code above and notice the number four appears three times. The number four is hard coded into this program. Which means that if I have a new favorite number (say six) I have to change my program in three places. Here's a better version of the program:

favorite = 4
print ('My favorite number is:', favorite)
print ('Two times my favorite number is:', favorite * 2)
print ('Two plus my favorite number is:', favorite + 2)

Now if I want to change my favorite number I can do it in just one place:

favorite = 6
print ('My favorite number is:', favorite)
print ('Two times my favorite number is:', favorite * 2)
print ('Two plus my favorite number is:', favorite + 2)

The comparison operators produce either 'True' or 'False'. Here's some examples of how to use the comparison operators:

secret = 7 
print ('Is the secret number less than 5?', secret < 5)
print ('Is the secret number greater than or equal to 5?', secret >= 5)
print ('Is the secret number equal to seven?', secret == 7)

Triple Quotes and Docstrings

  • The strongest type of quote in Python is the triple quote.
  • Triple quotes have three copies of the tick ''' or the quote “”“.
  • They can span multiple lines
  • They're used to make descriptive comments of files an functions called docstrings
    • We'll talk about functions in a few weeks.

Here's an example of a triple quote:

>>> print ('''This is a 
... triple quote
... block
... Neat, huh?
... ''')
This is a 
triple quote
Neat, huh?
  • Docstrings can appear in a place where they do nothing
    • The start of a file or function
  • They are used for documentation

You should place a header like this at the top of every Python file you turn in:

CIS-15 Exercise or project number 
Your Name
The Date
Other interesting comments...
  • The block will help me identify what you're turning in.
  • It's considered good style for programs because it helps people that read your code
    • The most likely person you'll help is yourself


  • A variable is like a box.
    • It has a name (written on the outside of the box)
    • It has contents (inside the box)
  • Variables are how programs use computer memory
  • Variables are assigned using the equal sign
name = value
  • Variables must be assigned before they're used
var1 = 10 
print (var1)  # Okay, var1 was assigned above
print (var2)  # Error, var2 has not been assigned anywhere

If you run the above program, Python produces the following output:

$ python3.6 
Traceback (most recent call last):
  File "", line 3, in <module>
    print (var2)  # Error, var2 has not been assigned anywhere
NameError: name 'var2' is not defined
  • Variable also have a data type
    • Variables receive a data type when they're assigned
    • The data type can change if you reassign the variable
    • The above property makes Python what's known as a dynamically typed programming languag
  • The data type determines what can be done with the variable
  • Mixing data types in operations is usually not allowed

Follow this example on the Python command line that shows how variables assume a data type:

$ python3.6 
Python 3.6.2 (default, Aug 27 2017, 23:19:08) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> myvar = 10
>>> type (myvar)
<class 'int'>
>>> myvar = True 
>>> type (myvar)
<class 'bool'>
>>> type (myvar)
<class 'NoneType'>

The type of myvar changes depending on what value is inside. This is different than C, C++ and Java. In those languages the data type of a variable can never change.

Variables and Printing

  • Printing the contents of a variable is easy in Python
  • However, there's many ways to do it.
  • The simple way you've seen in this lesson already:
myvar = 3 
print ('The number of counting shall be', myvar)
print ('Thou shalst not count to', myvar + 1) 
print ('And', myvar + 2, 'is right out!')

Run the code above and you'll see:

The number of counting shall be 3
Thou shalst not count to 4
And 5 is right out!

Study Break

Take a study break and smile. The quotes in the above program come from Monty Python
  • There are other (many, sadly many) ways to print variables in Python
  • The format string or f-string is the latest (and greatest)
  • f-strings look like regular quotes but start with an f
    • Example: f”This is an f-string“

A program using f-strings:

print ('Mary had a little lamb.')
print (f'Mary had a little lamb.') # Exactly the same as above
  • f-strings make printing variables more convenient
  • When you want the value of a variable printed place it inside of braces { and }

A program using variables and f-strings:

done = 4
todo = 10
print (f"I've finished {done}/{todo} tasks.")
  • You can use single quotes ' and double quotes with f-strings

Advanced Printing

  • Notice that the print function automatically adds spaces between the strings and the variables
  • This is a convenience to the programmer
  • But, it can be annoying too.

Execute the code to see how the sep argument changes the separator.

>>> print ('Hello', 'world')    
Hello world
>>> print ('Hello', 'world', sep='')
>>> print ('Hello', 'world', sep=', ')
Hello, world
  • Experienced programmers will also notice that Python adds line endings in each print statement.
  • Again, that's a help to the novice and most of the time it's what you want
  • That behavior can be controlled with the end argument.

See for yourself with this program:

print ('1...')
print ('2...')
print ('3...')
print ('kaboom!')
# Now with end
print ('1', end='...')
print ('2', end='...')
print ('3', end='...\n')
print ('kaboom!')

Here's a challenge: Can you write a print statement that prints the progress message with the done and todo variables without an f-string?

Python 2/3 Compatibility

  • The f-string is new to Python 3.6 and doesn't exist in Python 2 or earlier versions of Python 3
  • In Python 3 the print statement must have parenthesis ( and )
  • Python 2's print statement is much more limited than Python 3's print function.
    • It doesn't support sep or end

You can use Python 3's print function in your Python 2 programs by placing this line at the top of your file:

from __future__ import print_function 

List and Dictionary Variables

Advanced Topic

The content in this section is about data structures that will be familiar to programmers. The material will appear again in weeks 10 and 11.
  • Python has built in list and dictionary types
    • This makes most simple data structures simple
    • Python is garbage collected so you don't need to allocate or free data
  • List and dictionary elements can hold any Python object
    • Including other lists, dictionaries, functions and modules
  • Lists are resizeable at any time

Follow the below commands to declare and use a list:

>>> mylist = []
>>> type(mylist)
<class 'list'>
>>> print(mylist)
>>> mylist.append('first element')
>>> mylist.append(0)
>>> mylist.append(1.1)
>>> print (mylist)
['first element', 0, 1.1]

Each list element has its own type:

>>> type(mylist[0])
<class 'str'>
>>> type(mylist[1])
<class 'int'>
>>> type(mylist[2])
<class 'float'>

List elements have to be created before they can be assigned. Try running this program:

mylist = []
mylist.append(1)   # okay, now mylist[0] exists 
mylist[1] = 2      # error, mylist[1] is out of bounds

Running the above program produces this output:

IndexError: list assignment index out of range
  • List literals are surrounded by square brackets [ and ]

Here's an example of assignment using a list literal:

>>> mylist = [ 'Mary', 'had', 'a', 'little', 'lamb' ] 
>>> print (mylist)
['Mary', 'had', 'a', 'little', 'lamb']
  • Lists can be sliced
  • A slice is a sublist
    • Slices can be used as a value
    • Slices can also be assigned

Here's an example of list slicing:

mylist = [ 'Mary', 'had', 'a', 'little', 'lamb' ] 
print (mylist[1:2])  # prints elements 1 to 2-1 (['had'])
print (mylist[2:4])  # prints elements 2 to 4-1 (['a', 'little']) 
mylist[0:2] = ['Mike', 'has'] 
mylist[3:5] = ['Python', 'class'] 
print (mylist)  # prints ['Mike', 'has', 'a', 'Python', 'class']
  • List iteration is easy in Python with a for loop.
  • You can quickly operate on a list using a list comprehension which is cool.

The program below shows a list comprehension.

>>> fib = [1, 1, 2, 3, 5, 8, 13] 
>>> [x+1 for x in fib]
[2, 2, 3, 4, 6, 9, 14]
  • Dictionaries are similar to map types in Java and C++
  • Like list dictionaries can hold any mixture of types
  • Dictionaries can be expressed as literals too
>>> dict = {}
>>> print (dict)
>>> dict = {'cis15' : 'Intro to Python', 'cis191' : 'Linux Administration', 'cis75' : 'Computer Security'}                
>>> dict['cis15']
'Intro to Python'
  • Dictionaries are accessed like lists, with square brackets [ and ]
  • Dictionary keys can be different types
>>> dict = {'cis15' : 'Intro to Python', 'cis191' : 'Linux Administration', 'cis75' : 'Computer Security', 0 : 5}
>>> dict['cis15']
'Intro to Python'
>>> dict[0]
  • Notice that accessing the dict looks a lot like accessing an array!
    • The dict happens to have an integer key

Further Reading

For complete information about lists and dictionaries read the Python documentation

Installing Software with Pip

  • There's a lot of software written in Python!
  • Very little is installed on your system automatically.
  • Before you try to write something yourself you should look to see if it's been written already
  • All of the packages listed here can be installed using the pip and pip-3.6 commands.

It's easy to make cloud applications in Python using Flask. Here's how to install Flask into your workspace.

$ pip-3.6 install --user Flask 
Collecting Flask
  Using cached Flask-0.12.2-py2.py3-none-any.whl
Collecting Jinja2>=2.4 (from Flask)
  Using cached Jinja2-2.10-py2.py3-none-any.whl
Collecting click>=2.0 (from Flask)
  Using cached click-6.7-py2.py3-none-any.whl
Collecting itsdangerous>=0.21 (from Flask)
  Using cached itsdangerous-0.24.tar.gz
Collecting Werkzeug>=0.7 (from Flask)
  Using cached Werkzeug-0.14.1-py2.py3-none-any.whl
Collecting MarkupSafe>=0.23 (from Jinja2>=2.4->Flask)
  Using cached MarkupSafe-1.0.tar.gz
Installing collected packages: MarkupSafe, Jinja2, click, itsdangerous, Werkzeug, Flask
  Running install for MarkupSafe ... done
  Running install for itsdangerous ... done
Successfully installed Flask-0.12.2 Jinja2-2.10 MarkupSafe-1.0 Werkzeug-0.14.1 click-6.7 itsdangerous-0.24
  • Notice that the pip version is specific to the Python version.
    • If you ran pip alone it would install Flask for Python 2
    • When you run pip-3.6 it installs Flask for Python 3.6 in your workspace (correct!)
  • The –user flag tells pip to install the packages without administrator permissions
    • This makes mistakes less likely and less severe.

With Flask installed you can now recreate your web application. Copy and paste this code into a file:

from flask import Flask 
app = Flask(__name__)
def index() :
    return "<h1>Hello, webapp World!</h1>"
if __name__ == '__main__' :'', port=8080, debug=True)

Run your program by executing it from the command line:

$ python3.6 ./                                               
 * Running on (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 647-591-211

If everything works you should be able to preview your app on your custom URL or in the preview window of Cloud9 IDE