Introduction To Programming With Python
Introduction To Programming With Python
Outline
Programming languages and Python Basic programs and numeric data Control statements Text processing What's next? / CSE 142 at UW
Languages
Some influential ones:
FORTRAN
science / engineering
COBOL
business data
LISP
logic and AI
BASIC
a simple language
Python
Created in 1991 by Guido van Rossum (now at Google)
Named for Monty Python
Used by:
Google, Yahoo!, Youtube Many Linux distributions Games and apps (e.g. Eve Online)
Installing Python
Windows: Download Python from http://www.python.org Install Python. Run Idle from the Start Menu. Mac OS X: Python is already installed. Open a terminal and run python or run Idle from Finder. Linux: Chances are you already have Python installed. To check, run python from the terminal. If not, install from your distribution's package system.
Note: For step by step installation instructions, see the course web site.
Interpreted Languages
interpreted
Not compiled like many other languages (Java, C, C++) Code is written and then directly executed by an interpreter Type commands into interpreter and see immediate results
Java:
Code
Compiler
Runtime Environment
Computer
Python:
Code
Interpreter
Computer
swallows.py
1 2 3 4 print "Hello, world!" print print "Suppose two swallows carry it together." print "African or European swallow?"
Comments
Syntax:
# comment text (one line)
swallows2.py
1 2 3 4 5 6 # Suzy Student, CSE 142, Fall 2097 # This program prints important messages. print "Hello, world!" print # blank line print "Suppose two swallows \"carry\" it together." print 'African or "European" swallows?'
10
Expressions
expression: A value or operation(s) to compute a value.
Example: 1 + 4 * 3
Arithmetic operators:
+ - * / ** % add, subtract/negate, multiply, divide exponentiate modulus, a.k.a. remainder
Integer division
When we divide integers with / , the quotient is an integer.
3 4 ) 14 12 2 35 / 5 is 7 84 / 10 is 8 52 27 ) 1425 135 75 54 21
Variables
variable: A named piece of memory that stores a value.
gpa
3.14
Exercise
This program's code is redundant. Improve it with variables:
print print print print print print print print "Subtotal:" 38 + 40 + 30 "Tax:" (38 + 40 + 30) * .09 "Tip:" (38 + 40 + 30) * .15 "Total:" 38 + 40 + 30 + (38 + 40 + 30) * .15 + (38 + 40 + 30) * .09
14
Data Types
type: A category or set of data values.
Constrains the operations that can be performed on the data Examples: integer, real number, text string
15
Parameters
parameter: A value supplied to a command as you run it.
Syntax: command ( value ) command ( value, value, ..., value )
Example:
print sqrt(25) print sqrt(15 + 10 * 10 + 6) x = 5 print sqrt(x + sqrt(16))
16
Math commands
Function name abs(value) ceil(value) cos(value) floor(value) log10(value) max(value1, value2) min(value1, value2) round(value) sin(value) sqrt(value) Description absolute value rounds up cosine, in radians rounds down logarithm, base 10 larger of two values smaller of two values nearest whole number sine, in radians square root Constant e pi Description 2.7182818... 3.1415926...
input
input : Reads a number from the user's keyboard.
You can store the result of input into a variable. Example:
age = input("How old are you? ") print "Your age is", age print "You have", 65 - age, "years until retirement"
Output:
How old are you? 53 Your age is 53 You have 12 years until retirement
Control Statements
if
if statement: Executes a set of commands only if a certain condition is True. Otherwise, the commands are skipped.
Syntax: if condition: statements Example: gpa = input("What is your GPA? ") if gpa > 2.0: print "Your application is accepted."
20
if/else
if/else statement: Executes one set of statements if a certain condition is True, and a second set if it is False.
Syntax: if condition: statements else: statements Example:
gpa = input("What is your GPA? ") if gpa > 2.0: print "Welcome to Mars University!" else: print "Your application is denied."
Logic
Operator == != < > <= >= Meaning equals does not equal less than greater than less than or equal to greater than or equal to Example 1 + 1 == 2 3.2 != 2.5 10 < 5 10 > 5 126 <= 100 5.0 >= 5.0 Result True True False True False True
22
for loops
for name in range(start, end): statements for name in range(start, end, step): statements Repeats for values start (inclusive) to end (exclusive)
>>> for i in range(2, 6): print i 2 3 4 5 >>> for i in range(15, 0, -5): print i, "squared is", (i * i) 15 squared is 225 10 squared is 100 5 squared is 25
23
Cumulative loops
Some loops incrementally compute a value. sometimes called a cumulative loop
sum = 0 for i in range(1, 11): sum = sum + (i * i) print "sum of first 10 squares is", sum Output: sum of first 10 squares is 385
24
Exercise
Write a program that reads a student's homework scores as input and computes the student's homework percentage.
This program computes your average homework grade. How many assignments were there? 3 Assignment 1 Points earned? 12 Points possible? 15 Assignment 2 Points earned? 10 Points possible? 20 Assignment 3 Points earned? 4 Points possible? 5 Your total score: 26 / 40 : 65 %
25
while
while loop: Executes as long as a condition is True. good for indefinite loops (repeat an unknown number of times) Syntax:
while condition: statements
Example:
number = 1 while number < 200: print number, number = number * 2
Output:
1 2 4 8 16 32 64 128
26
Random numbers
from random import * randint(min, max) Produces a random value between min and max (inclusive) Example: coinflip = randint(1, 2) if coinflip == 1: print "Heads" else: print "Tails"
27
Exercise
Write a program that plays a guessing game with the user:
Let's play a game. Try to guess my number from 1-100! Your guess? 40 Too low. Your guess? 85 Too high. Your guess? 68 Too high. Your guess? 51 Too low. Your guess? 57 Too low. Your guess? 63 Too high. Your guess? 61 You got it right in 7 guesses!
28
Text Processing
Strings
string: A sequence of text characters in a program.
Strings start and end with quote " or apostrophe ' characters. "hello" "This is a string" "This, too, is a string.
30
Indexes
Characters in a string are numbered with indexes :
name = "P. Diddy"
index character 0 P 1 . 2 3 D 4 i 5 d 6 d 7 y
31
String properties
len(string) str.lower(string) str.upper(string) Example:
name = "Martin Douglas Stepp" big_name = str.upper(name) print big_name, "has", len(big_name), "characters"
- number of characters in a string (including spaces) - lowercase version of a string - uppercase version of a string
Output:
MARTIN DOUGLAS STEPP has 20 characters
32
raw_input
raw_input : Reads a string of text from the user's keyboard.
Example: name = raw_input("Howdy. What's yer name? ") print name, "... what a silly name!" Output: Howdy. What's yer name? Paris Hilton Paris Hilton ... what a silly name!
33
Text processing
text processing: Examining, editing, formatting text.
Often uses loops that examine characters one by one.
chr(number)
35
Exercise
Write a program that "encrypts" a secret message by shifting the letters of the message by 1:
e.g. "Attack" when rotated by 1 becomes "buubdl"
36
What's Next?
Further programming
What do students learn next?
Arrays, data structures Objects and object-oriented programming Algorithms: searching, sorting, recursion, etc. Graphical user interfaces, drawing, event-driven programming
38
39
Student pictures
Around the 3rd week, we assign a graphical program Two parts:
draw a particular figure using loops and parameters draw any figure you want
figures posted on course web site and voted on by students
40
Critter simulation
Students write several small classes to represent animals in a simulation world Each student writes a custom "Husky" animal with their choice of behavior The best huskies compete in a tournament for prizes
41
Facebook integration
42
Links
Python for math teachers:
http://showmedo.com/videos/series?id=101
43