Transcript Python

Python
Crash Course
by Monica Sweat
Python Perspective
• is strongly typed, interpreted language
• is used to define scripts
(Don't even need to define a function proper.)
• is used to define functions
• can be used in object-oriented style
• is an up and coming real language in industry
Integrated Development Environment:
IDLE
• IDLE is provided with standard python
installation
• available for virtually any platform
• provides an editing window
• provides an interactive interpreter window
Starting Simply
can use IDLE / python as a calculator
>>> 3 + 4
12
>>> 4 ** 2
16
>>> 6 / 2
3
>>> 1 / 2
0
 gotcha that begs an
introduction to types
Common Types
• sampling of types
– int
– long
– float
28
– str
– bool
signed integer, 32 bits, ±2,147,483,647
arbitrarily long ends with L
64 bit double precision, like 1.23 or 7.8edelimit in ' or "
Booleans True and False
• type(x)
yields the type of the data stored currently in
variable x
str Type
• str is the type for strings in python
• they can be single quote or double quote
delimited
word = "can't"
• multiline strings can be triple quoted (that's 3
single quotes or 3 double quotes in a row)
poem = """Roses are red,
violets are blue."""
Comments (relates to strings)
• comments in python are single line and use
the # symbol
# This program written by George Burdell
• multiline comments can be faked by using the
triple quoted string trick
"""This program written by Monica Sweat
July 8, 2008"""
Math Operations
•
•
•
•
•
()
+
**
*
+
-
/
-
%
parens for grouping
unary plus, minus
exponentiation
mult-style ops
add, subtract
Simple Demo of Variables
>>> age = 18
>>> print age
18
>>> age = age + 1
>>> print age
19
Python Variables
• Python is case-sensitive
– variable names
– function names
– everything
• Camel case is a common style in python, java, etc.
firstName = 'George'
lastName = 'Burdell'
print firstName, lastName
word = "don't"
Python Variables
• [a-zA-Z][a-zA-Z0-9 _]*
• start with letter followed by letters and digits
• any length
• case matters
• do not have to be declared!
• python is strongly typed, but the "type" is bound to the
data and not the variable
Script Example
Complete script using variables
Assignment statement uses =
hours = 35
rate = 25.50
pay = hours * rate
print pay
Printing Results
Increasingly better ways to print pay
hours = 35
rate = 25.50
pay = hours * rate
print pay
or
print "Your pay is", pay
or
print "Your pay is $" + str(pay)
or
print "Your pay is $%.2f" % pay
Easy User Input
Use input for console input of a numeric value
hours = input("How many hours?
")
rate = input("Pay rate? ")
pay = hours * rate
print "Your pay is $%.2f" % pay
Getting Input from the User
• numeric input
age = input("Age? ")
• string input
name = raw_input("Name? ")
Type Conversion
• x = int(3.9)
• y = float(5)
• print "Answer: " + str(2 * 3)
(Useful if concatenating with a string)
• age = int(raw_input("Age? "))
(Useful if using raw_input to get all input from
the user.)
• average = float(sum)/float(total)
(Forces float division)
Conditionals
• if
• if/else
• if/elif/elif/elif/…/else
• all branches use colon :
• all bodies are indented
Python uses indentation to denote blocks.
Building Conditions
• relational operators as expected
<, >, <=, >=, ==, !=, <>
(assignment uses single equals sign)
• logical operators are lowercase
not, and, or
(! can be used for not)
• parentheses not necessary unless overriding
precedence
Conditionals
age = input("Age? ")
if age <= 12:
ticketPrice = 5
elif age >= 65:
ticketPrice = 7.5
else:
ticketPrice = 9
print ticketPrice
Defining a Function
def rectangleArea(length,
width):
area = length * width
return area
Using Modules
import math
def circleArea(radius):
area = math.pi * radius ** 2
return area
http://docs.python.org/modindex.html
math, random, re, os, …
Importing Modules
import math
print math.pi
x = math.sqrt(9)
vs.
from math import pi, sqrt
print pi
x = sqrt(9)
Python Sequences (arrays)
• python's answer to the array
• is dynamic
• behaves like a linked listed with indexing
names = ["Fred", "Wilma"]
names[0] = "Barney"
print names[0]
Python Sequences (arrays)
common operations (there are many)
names = names + ["Dino"]
or
names.append("Bambam")
for Loop
for-each style iterates through a sequence
syntax:
for item in sequence:
block-of-code
for flavor in ["chocolate", "vanilla"]:
print "I like", flavor
for Loop
def average(array):
sum = 0
count = 0
for num in array:
sum = sum + num
count = count + 1
return float(sum)/count
Counting-style for Loop
for loop with counting style using range:
for num in range(1, 5):
print num
Output:
1
2
3
4
Processing Array without/with range
for-each style to iterate through a sequence:
for flavor in ["chocolate", "vanilla"]:
print "I like", flavor
vs.
index-driven style processing a sequence:
flavors = ["chocolate", "vanilla", "mint"]
for index in range(len(flavors)):
print "I like", flavors[index]
range Function Details
• most commonly used to generate indices for iterating a sequence
• may have 1, 2, or 3 parameters
• stopping value is exclusive
>>> range(5)
(starts at 0 if one parameter)
[0, 1, 2, 3, 4]
>>> range(1995, 2000)
(stopping value exclusive)
[1995, 1996, 1997, 1998, 1999]
>>> range(0, 55, 5)
(3rd parameter is step value)
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
range Function to Generate Data
def summation(n):
total = 0
for num in range(n + 1):
total = total + num
return total
while Loop
number = 1
while number <= 5:
print number
number += 1
myro – Major Bonuses
• myro defined as a proper module
– programmer imports it as they would any module
– natural way to incorporate added functionality
• works with standard python
– all of standard python is available to the user
– other modules: math, random, os, etc are still
available
– materials for python still apply