27 February

Notes on Python

Use Python 2.7 from http://python.org/

  1. Run IDLE (Python GUI)
  2. You get a window called “Python Shell” with “>>>” prompt.
  3. File → New Window
  4. In new window, File → Save and give it a filename that ends with .py (this will enable syntax coloring).
  5. Type your code into the .py file, save
  6. Run → Run Module (F5) to run it, interact in Shell window.
print "Hello world."
# Lines that start with a "#" are called comments.
# You can type whatever you want there, python ignores them.

Variables

Named location to store data. Names cannot have spaces in them. They are case-sensitive (upper/lower). Names can have numbers, but cannot start with numbers —

It’s okay to have underscore character instead of a space: quiz_3 amount_to_pay

x = 14        # evaluate right side of equal sign,
y = x * 2     # put that value in the variable on the left.
x = x - 4
# At this point, x holds 10 and y holds 28.

Output

print "Testing!"  # Quotes indicate a string of characters (text)
print "x+1"       # Variables, arithmetic not evaluated inside quotes
print x+1         # Performs variable lookup and addition.

print "The answer is", y  # Combine multiple parts on one line.

Input

name = raw_input("Your name:")  # Prompt in quotes and parentheses.
  # Result of what user typed assigned to variable on the left.
print "Your name is", name

# raw_input returns a string of characters (text).
# If you want a number, convert it using int() or float().
#  int for integer (whole numbers)
#  float for floating-point (decimal numbers)

score = int(raw_input("Enter score:"))
print "Double that score is", score*2

If shell window appears messed up, not responding, try control-C a few times.

Conditions

# Python has True and False (Boolean values).
#  3 < 4   produces True
#  3 == 4  produces False (are these equal?)

if y < 30:      # colon required
    print "That's small."   # only happens if y < 30.
    y = y + 10

if y < 30:
    print "This does not happen."
else:
    print "This does happen, because y is now big."

Extended example

temp = float(raw_input("Enter temperature:"))
if temp < 40:
    print "That's cold!"
else:
    if temp > 90:
        print "That's hot."
    else:
        print "That's comfortable."

Loops

# Greatest common divisor of two numbers.
# (Euclid's algorithm)

a = int(raw_input("Enter an integer:"))
b = int(raw_input("Enter another integer:"))

while a != b:       # "!=" means "does not equal"
    if a < b:       # Repeat indented parts as long as a != b
        b = b - a
    else:
        a = a - b

print "The GCD is", a

Class exercise

hours = int(raw_input("How many hours? "))

REG_RATE = 20
OT_RATE = 30
FULL_WEEK = 40

if hours > FULL_WEEK:
    print "You worked overtime."
    print "You earned", (FULL_WEEK * REG_RATE +
                         (hours - FULL_WEEK) * OT_RATE)
else:
    print "You earned", hours * REG_RATE

 

©2012 Christopher League · some rights reserved · CC by-sa