Hello World! An Invitation to Computer Science
Lecture Slides
Introduction to Programming in Python
Thursday April 3, 2008
- high-level languages v. assembly languages
- there are 1000s of 3rd generation languages
- the import of C
- programming paradigms
How are high-level programs executed?
- parsing, mapping to discrete fragments,
eventual conversion to machine code
- interpreters and translators ("compilers")
- analogies with natural language
What is Python?
- imperative scripting language, with O-O features
(and some functional features)
- interpreted (executed via virtual machine)
- indentation effects computation!
- designed for readable and to be similar to pseudocode
- many features which we will not discuss in this course
Identifiers
- case sensitivity
- readability, consistency, convention
- reserved words
Expressions
- literals: integers, floats, True/False, strings
- identifiers (must be assigned values first!)
- combinations of simpler expressions
using operators (and parentheses)
- order of operations: what you might expect (PEMDAS)
(parentheses can make more readable)
- spaces optional in expressions
(but can also make more readable)
9.0 / 5.0 v. 9 / 5
Statements
- output using print in its various forms
- simple assignment
- input assignment
- while loops
Accumulator pattern
def factorial():
n = input("Enter value for n: ")
product = 1
i = 2
while i <= n:
product = product * i
i = i + 1
print "The factorial of", n, "is", product
Real computers are finite
- numbers usually represented in one fixed-width register
- advantage: arithmetic in hardware - very fast!
- disadvantage: overflow errors
- Python and Scheme use mixed-representation:
hardware for small values
software for larger values
Another example
def sumDigits():
n = input("Enter value for n: ")
sum = 0
x = n
while x > 0:
sum = sum + (x % 10)
x = x / 10
print "Sum of digits in ", n, "is", sum