Computer Science 15-110, Fall 2010
Class Notes: Getting Started with Python
- Installation
- Hello World
- Comments
- Errors
- Syntax Errors (Compile-Time Errors)
- Runtime Errors ("Crash")
- Logical Errors (Compiles and Runs, but
is Wrong!)
- Python Shell vs Editing Window (in IDLE)
- Single Line Paste
- Multiline Paste Problem
- The Underscore (_) in the Shell
- Alt-P and Alt-N in the Shell
- Variables and Expressions
- Basic Console Input
- String with raw_input()
- Number with raw_input() (error!)
- Number with raw_input() and int()
- Strings and Numbers with input()
- Importing Modules
Getting Started with Python
- Installation
See http://www.python.org/
- Hello World
print "Hello World!"
- Comments
print "Hello World!" # This is a comment
# print "What will this line do?"
- Errors
- Syntax Errors (Compile-Time Errors)
print "Uh oh! # ERROR! missing close-quote
Python output:
SyntaxError: EOL while scanning string literal
- Runtime Errors ("Crash")
print 1/0 # ERROR! Division by zero!
Python output:
ZeroDivisionError: integer division or modulo by zero
- Logical Errors (Compiles and Runs, but is Wrong!)
print "2+2=5" # ERROR! Untrue!!!
Python output:
2+2=5
- Python Shell vs Editing Window (in IDLE)
- Single Line Paste
print "This works just fine
- Multiline Paste Problem
print "But this example demonstrates a problem"
print "with multiline paste in the Python Shell"
- The Underscore (_) in the Shell
print "This works in the shell, but not in the editing window!"
2 + 3
4 * _
- Alt-P and Alt-N in the Shell
print "Try pressing Alt-P and Alt-N a few times in the shell..."
- Variables and Expressions
x = 5
y = 3
sum = x + y
print x
print "+"
print y
print "="
print sum
Once again, but printing all on one line:
x = 5
y = 3
sum = x + y
print x,
print "+",
print y,
print "=",
print sum
Once again, but more concisely:
x = 5
y = 3
sum = x + y
print str(x) + " + " + str(y) + " = " + str(sum)
Yet again, but with multiple arguments to the print statement:
x = 5
y = 3
sum = x + y
print x, "+", y, "=", sum
- Basic Console Input
- String with raw_input()
name = raw_input("Enter your name: ")
print "Your name is: " + name
- Number with raw_input() (error!)
x = raw_input("Enter a number: ")
print "One half of " + str(x) + " = " + str(x/2) # Error!
- Number with raw_input() and int()
x = int(raw_input("Enter a number: "))
print "One half of " + str(x) + " = " + str(x/2)
- Strings and Numbers with input()
x = input("Try this with a string and then a number: ") # input() is not recommended!
print 2*x
- Importing Modules
Fails:
print math.sqrt(5)
Python output:
NameError: name 'math' is not defined
Works:
import math
print math.sqrt(5)
Python output:
2.2360679775
carpe diem -
carpe diem - carpe diem - carpe diem
- carpe diem - carpe diem -
carpe diem - carpe diem - carpe
diem