# 2005-10-21 编程艺术简介

#### 编程是什么？

```1/4杯酸橙汁
1/4杯低钠大豆酱油
1/4杯水
1大汤匙植物油
3/4茶匙小茴香
1/2茶匙牛至
1/4茶匙热胡椒粉
2片丁香、大蒜，捣碎```

```1份（12盎司）罐装少钠午餐肉火腿切成条状
1个洋葱，切片

12个樱桃西红柿，切半```

`把腌泡汁装在有合适盖子的广口瓶里摇匀。用塑料袋装上火腿，泼上腌泡汁，封住袋口。在电冰箱里腌制30分钟。从塑料袋里取出火腿；准备2大汤匙腌泡汁，在煮锅里煮一下。加上火腿、洋葱、绿色的胡椒。烧3到4分钟直到火腿熟了为止……`

#### Hello……

`print "Hello, world!"`

```print "Hello, world!"
print "Goodbye, world!"```

```# The Area of a Rectangle

# Ingredients:

width = 20
height = 30

# Instructions:

area = width * height
print area```

`width * height`

`20 * 30`

`600`

#### 反馈

```radius = 30

```radius = input("What is the radius?")

`input`

```foo = input
bar = input()```

#### 流程

```temperature = input("What is the temperature of the spam?")

if temperature > 50:
print "The salad is properly cooked."
else:
print "Cook the salad some more."```

```# Area calculation program

print "Welcome to the Area calculation program"
print "---------------------------------------"
print

print "1 Rectangle"
print "2 Circle"

#Get the user's choice:
shape = input("> ")

#Calculate the area:
if shape == 1:
height = input("Please enter the height: ")
width = input("Please enter the width: ")
area = height *width
print "The area is ", area
else:
print "The area is ", area```

```if foo == 1:
# Do something...
elif foo == 2:
# Do something else...
elif foo == 3:
# If all else fails...```

#### 循环

python有两种循环类型：while循环和for循环。for循环大概是最简单的。举个例子：

```for food in "spam", "eggs", "tomatoes":
print "I love", food```

```for number in range(1, 100):
print "Hello, world!"
print "Just", 100 - number, "more to go..."

print "Hello, world"
print "That was the last one... Phew!"```

```# Spam-cooking program

# Fetch the function sleep
from time import sleep

print "Please start cooking the spam. (I'll be back in 3 minutes.)"

# Wait for 3 minutes (that is, 3*60 seconds)...
sleep(180)

print "I'm baaack :)"

# How hot is hot enough?
hot_enough = 50

temperature = input("How hot is the spam?")
while temperature < hot_enouth:
print "Not hot enough... Cook it a bit more..."
sleep(30)
temperature = input("OK, How hot is it now?")

print "It's hot enough - You're done!"```

1. 有些有用的函数被存储在模块中而且可以被导入。此例中我们从python自带的time模块中导入了函数sleep（它休止给定的多少秒的时间）。（做你自己的模块当然也是可能的……）

#### 大一点的程序 - 抽象化

```number = input("What is the number?")

floor = 0

while floor <= number:
floor = floor + 1

floor = floor - 1

print "The floor of ", number, "is ", floor```

```def floor(number):
result = 0
while result <= number:
result = result + 1
result = result - 1
return result```

1. 函数用关键字def定义，函数名紧随其后并且要用括号把需要的参数括起来。 2. 如果要求函数返回一个值，要使用关键字return来处理（它同时也自动结束函数定义）。

```x = 2.7
y = floor(2.7)```

```def sum(x, y):
return x + y```

1. 假设两个数，a和b，a大于b 2. 重复以下步骤直到b变成0： 1. a变为b的值 2. b变成没有改变值之前的a除以没有改变值之前的b的余数 3. 返回a的最后一个值

* 使用a和b作为函数的参数 * 简单的设定a大于b * x除以z的余数用表达式 x % z 来计算 * 两个变量可以象这样一起赋值：x, y = y, y+1。这里x被赋以值y（这意味着，y的值此前已经指定）而且y被递增了1。

#### 深入函数

```def hello(who):
print "Hello, ", who

hello("world")
# Prints out "Hello, world"```

```# The *wrong* way of doing it
age = 0

def setAge(a):
age = a

setAge(100)
print age
# Prints "0"```

```# The correct, but not-so-good way of doing it
age=0

def setAge(a):
global age

setAge(100)
print age

# Prints "100"

def square(x):
return x*x

==== 更多类型－数据结构 ====

{{{
[3, 6, 78, 93]```

```# Calculate all the primes below 1000
# (Not the best way to do it, but...)

result = [1]
candidates = range(3, 1000)
base = 2
product = base

while candidates:
while product < 1000:
if product in candidates:
candidates.remove(product)
product = product+base
result.append(base)
base = candidates[0]
product = base
del candidates[0]
result.append(base)
print result```

```food = [“spam”, “spam”, “eggs”, “sausages”, “spam”]
print food[2:4]

# Prints “['eggs', 'sausages']”```

#### 继续抽象－对象和面向对象编程

```class Oven:

def insertSpam(self, spam):
self.spam = spam

def getSpam(self):
return self.spam```

`myOven = Oven()`

myOven包含了一个Oven对象，通常叫做Oven类的一个实例。假设我们也构造好了 一个Spam类，那么我们可象这样做：

```mySpam = Spam()
myOven.insertSpam(mySpam)```

myOven.spam现在将包含mySpam。怎么回事？因为，我们调用一个对象的某个方法 时，第一个参数，通常称为self，总是包含对象本身。（巧妙，哈！）这样，self.spam =spam这一行设置当前Oven对象的spam属性的值为参数spam。注意它们是两个不同的事物，尽管在这个例子中它们都被称为spam。

#### 练习3答案

```def euclid(a, b):
while b:
a, b = b, a%b
return a```