Date post: | 21-Dec-2015 |
Category: |
Documents |
View: | 223 times |
Download: | 1 times |
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 + 412>>> 4 ** 216>>> 6 / 23>>> 1 / 20 gotcha that begs an introduction to types
Common Types
• sampling of types– int signed integer, 32 bits, ±2,147,483,647– long arbitrarily long ends with L– float 64 bit double precision, like 1.23 or 7.8e-28
– str delimit in ' or "– bool 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
delimitedword = "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 SweatJuly 8, 2008"""
Math Operations
• () parens for grouping• + - unary plus, minus• ** exponentiation• * / % mult-style ops• + - add, subtract
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, lastNameword = "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 variablesAssignment statement uses =
hours = 35rate = 25.50pay = hours * rateprint pay
Printing ResultsIncreasingly better ways to print pay
hours = 35rate = 25.50pay = hours * rateprint payorprint "Your pay is", payorprint "Your pay is $" + str(pay)orprint "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 inputage = input("Age? ")
• string inputname = 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 lowercasenot, 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
Using Modules
import math
def circleArea(radius):
area = math.pi * radius ** 2
return area
http://docs.python.org/modindex.htmlmath, random, re, os, …
Importing Modules
import mathprint math.pix = math.sqrt(9)
vs.
from math import pi, sqrtprint pix = 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
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