Preamble

This software is iPython Notebook. From the command line, change to the directory where your Notebooks (.ipynb) are located and type

ipython notebook

A Notebook contains "cells". Edit a cell by double clicking on it.

Some of the cells, like this one, contains text. The text is formatted using a language called "Markdown." It's similar to what's used in Wikipedia. You can find out more by going to the Help menu above.

Other cells, like the one below, contain Python code and can be run.

Both types of cells are "run" using the "play" button, above.


In [1]:
print("Hello world")


Hello world

Rule 3

The best way to improve your programming and problem skills is to practice.


In [ ]:
#Input the hours worked
#Input the hourly pay
#Calculate the gross pay as hours worked multiplied by pay rate
#Display the gross pay

Input, Processing, and Output

Typically, a computer performs a three-step process

  1. Retrieve input
    • Examples: keyboard input, text file, database
  2. Perform some process on the input
    • Examples: mathematical calculation, summarize
  3. Produce output
    • Example: a number, a report, write to file

We'll talk about output first, as that's the most straightforward and we did this in tutorial last week.

Output

  • The print function displays output on the screen.
  • A function is a collection of lines of code that is referred to by the function name
  • "Calling" a function causes all the lines of code inside it to run

  • Here is an example of a function. Don't worry about the details now. We'll be talking about them more in a couple of weeks.


In [2]:
def first_function():
    print("\"Beware the Jabberwock, my son!")
    print("The jaws that bite, the claws that catch!")
    print("Beware the Jubjub bird, and shun")
    print("The frumious Bandersnatch!\"")

first_function()


"Beware the Jabberwock, my son!
The jaws that bite, the claws that catch!
Beware the Jubjub bird, and shun
The frumious Bandersnatch!"

The print function outputs strings and variables. So let's look at those now.

Strings

  • A string is a sequence of characters that is use as data
  • A string literal is a string that appears in the actual code of a program

I usually say just "string"

String Delimiters

  • Must be enclosed in single (‘) or double (“) quotations marks
  • Can also be enclosed in triple quotes (‘’’ or “””)
    • Use with strings that span multiple lines, or contain both single and double quotes

Recommended style for Python is double quotation marks


In [ ]:
"This is a string literal"
'This is also a string literal'

"""He took his vorpal sword in hand:
Long time the manxome foe he sought --
So rested he by the Tumtum tree,
And stood awhile in thought.
"""

Things to Notice

The above code doesn't do anything. We've just declared some strings.

The triple quotation string helps with Rule 2.

Rule 2

A program is a human-readable essay on problem solving that also happens to execute on a computer.

Variables

  • A variable is a container that has a label and can hold data.
  • An assignment statement has the following general form
    • variable = expression
    • The left hand side creates the container and gives it a label.
    • The equal sign (=) puts the value on the right hand side into the container.

In [ ]:
# Varible assignment
# Let age be equal to 25
# Let 25 be assigned to age
age = 25


# Comparison
# Is age equal to 25?
age == 25
# Evaluates to True or False
  • A variable name cannot be enclosed in quotation marks.

In [ ]:
"age" = 25
  • Can be passed into a function.

In [3]:
age = 25
print(age)


25
  • A variable can be used only after a value has been assigned.

In [4]:
print(temperature)


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-4-bc88277184f9> in <module>()
----> 1 print(temperature)

NameError: name 'temperature' is not defined

In [ ]:
temperature = 74.5
print(tmperature)

In [5]:
# This program demonstrates a variable
room = 503
print('I am staying in room number')
print(room)


I am staying in room number
503

In [6]:
room = 503
# Using print () is proper Python 3 Syntax
# It's acceptable in Python 2
print('I am staying in room number', room)

# Usual way in Python 2 is without ()
# This is not legal in Python 3
print 'I am staying in room number', room

print('I am staying in room number ' + str(room))

# This gives a type error
# print('I am staying in room number ' + room)

print('I am staying in room number %s') % room

print('I am staying in room number'),
# In Python 3
# print('I am staying in room number', end="")
print(room)


('I am staying in room number', 503)
I am staying in room number 503
I am staying in room number 503
I am staying in room number 503
I am staying in room number 503

Comments

  • Notes of explanation within a program

    • Begin with a # character
    • Ignored by Python interpreter
    • Intended for people
  • Meant to help with Rule 2


In [ ]:
# This is a Python comment
# It's actually pretty similar to a hashtag
  • In general, comments should provide rationale

    • Design decisions or explain why code is a particular way
  • Should NOT repeat code

    • Increases work when both must be kept in sync

Variable Naming Rules

  • Cannot be a Python keyword
  • Cannot contain spaces
  • First character must be a letter or an underscore
  • Subsequent characters may use letters, digits, or underscores
  • Case sensitive

Variable name should reflect its use

Recommended style for Python is to use nouns separated by underscores

  • called snake case

In [ ]:
# Are these variable names legal or illegal?
units_per_day
daysOfWeek
3dGraph
June1997
Mixture%3

Rule 4

A foolish consistency is the hobgoblin of little minds.

Input

  • There are a number of ways to specify input to a program.
    • As an argument on the command line
    • In a file
    • From the keyboard
  • Let's start with the last one.
    • variable = input(prompt) or variable = raw_input(prompt)
    • input() is a function
    • prompt is the string to be displayed on the screen
    • variable holds the data input from the keyboard

In [7]:
name = raw_input('What is your name? ') # For Python 3, use input()
print(name)


What is your name? Guido van Rossum
Guido van Rossum

Exercise: Name and Age

Write a program that asks the user for their first name, last name, and age. Print out the names on one line. Print out the age on the next line. Include labels on your output.


In [ ]:

Processing

This middle step involves manipulating the input in some way before outputting.

Exercise: Jacob Two-Two

Write a program that takes a string as input and prints it out twice.


In [8]:
# A program that repeats a user-inputed string twice

jacob_said = raw_input("What did you say?")
jacob_said = jacob_said + " " + jacob_said
print(jacob_said)


What did you say?Cheese, please!
Cheese, please! Cheese, please!

A lot of computer processing involves math, because computers are good with numbers. They're less good with strings.

Math Operators

  • Addition (+)
  • Subtraction (-)
  • Multiplication (*)
  • Division (/)

  • Integer division (//)

  • Remainder or modulo (%)
  • Exponent (**)

Order of Operations Matter

BEDMAS

  • Brackets
  • Exponents
  • Division and Multiplication
  • Addition and Subtraction

What do the follow expressions evaluate to?

6 * 3 + 7 * 4

5 + 3 / 4

5 - 2 * 3 ** 4


In [ ]:

Exercise: Calculate Pay

Calculate and display the gross pay for an hourly paid employee


In [ ]:
#Input the hours worked
#Input the hourly pay
#Calculate the gross pay as hours worked multiplied by pay rate
#Display the gross pay

Exercise: Total Purchase

A customer in a store is purchasing five items. Write a program that asks for the price of each item, and then displays the subtotal of the sale, the amount of sales tax, and the total. Assume that the sales tax is 13%.


In [ ]: