Review

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

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)

Examples

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)

File Comments and Triple Quotes

  • 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
    • 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
block
Neat, huh?
  • Triple quoted strings 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 file you turn in from now on:

''' 
CIS-15 Exercise or project number 
Your Name
Miscellaneous 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

Variables

  • 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 vars.py 
10
Traceback (most recent call last):
  File "vars.py", 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
https://www.youtube.com/watch?v=QM9Bynjh2Lk
  • 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='')
Helloworld
>>> 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]
5
  • 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 https://docs.python.org/3/tutorial/datastructures.html

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 command.

Last week you noticed that the ex50 program doesn't work in Python 3.6. It's because the web package is deprecated (it's no longer supported or maintained). It's been replaced by the Flask package (which is better). Here's how to install Flask into your workspace.

you:~/workspace $ sudo pip3.6 install Flask 
[expect a lot of output!]
  • Notice that the pip version is specific to the Python version.
    • If you ran pip alone it would install Flask for Python 2
    • If you ran pip3 alone it would install Flask for Python 3.4 in your workspace (wrong!)
  • You must prepend the command with sudo because you're installing Flask globally which requires superuser permissions
    • A better way to do this is with virtualenv we'll talk about that later

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__)
 
@app.route('/')
def index() :
    return "<h1>Hello, webapp World!</h1>"
 
if __name__ == '__main__' :
    app.run(host='0.0.0.0', port=8080)

Run your program by executing it from the command line:

$ python3.6 ./demo.py 
 * Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)

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