# 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!"```

```   1 # The Area of a Rectangle
2
3 # Ingredients:
4
5 width = 20
6 height = 30
7
8 # Instructions:
9
10 area = width * height
11 print area
```

`width * height`

`20 * 30`

`600`

#### 反馈

```radius = 30

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

`input`

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

#### 流程

```   1 temperature = input("What is the temperature of the spam?")
2
3 if temperature > 50:
4     print "The salad is properly cooked."
5 else:
6     print "Cook the salad some more."
```

```   1 # Area calculation program
2
3 print "Welcome to the Area calculation program"
4 print "---------------------------------------"
5 print
6
7 # Print out the menu:
8 print "Please select a shape:"
9 print "1 Rectangle"
10 print "2 Circle"
11
12 #Get the user's choice:
13 shape = input("> ")
14
15 #Calculate the area:
16 if shape == 1:
17     height = input("Please enter the height: ")
18     width = input("Please enter the width: ")
19     area = height *width
20     print "The area is ", area
21 else:
23     area = 3.14 * (radius**2)
24     print "The area is ", area
```

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

#### 循环

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

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

```   1 for number in range(1, 100):
2     print "Hello, world!"
3     print "Just", 100 - number, "more to go..."
4
5 print "Hello, world"
6 print "That was the last one... Phew!"
```

```   1 # Spam-cooking program
2
3 # Fetch the function sleep
4 from time import sleep
5
6 print "Please start cooking the spam. (I'll be back in 3 minutes.)"
7
8 # Wait for 3 minutes (that is, 3*60 seconds)...
9 sleep(180)
10
11 print "I'm baaack :)"
12
13 # How hot is hot enough?
14 hot_enough = 50
15
16 temperature = input("How hot is the spam?")
17 while temperature < hot_enouth:
18     print "Not hot enough... Cook it a bit more..."
19     sleep(30)
20     temperature = input("OK, How hot is it now?")
21
22 print "It's hot enough - You're done!"
```

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

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

```   1 number = input("What is the number?")
2
3 floor = 0
4
5 while floor <= number:
6     floor = floor + 1
7
8 floor = floor - 1
9
10 print "The floor of ", number, "is ", floor
```

```   1 def floor(number):
2     result = 0
3     while result <= number:
4         result = result + 1
5         result = result - 1
6         return result
```

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

```   1 x = 2.7
2 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。

#### 深入函数

```   1 def hello(who):
2     print "Hello, ", who
3
4 hello("world")
5 # Prints out "Hello, world"
```

```   1 # The *wrong* way of doing it
2 age = 0
3
4 def setAge(a):
5     age = a
6
7 setAge(100)
8 print age
9 # Prints "0"
```

```   1 # The correct, but not-so-good way of doing it
2 age=0
3
4 def setAge(a):
5     global age
6
7 setAge(100)
8 print age
9
10 # Prints "100"
```

```   1 def square(x):
2 return x*x
```

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

`[3, 6, 78, 93]`

```   1 # Calculate all the primes below 1000
2 # (Not the best way to do it, but...)
3
4 result = [1]
5 candidates = range(3, 1000)
6 base = 2
7 product = base
8
9 while candidates:
10     while product < 1000:
11         if product in candidates:
12             candidates.remove(product)
13         product = product+base
14     result.append(base)
15     base = candidates[0]
16     product = base
17     del candidates[0]
18     result.append(base)
19     print result
```

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

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

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

```   1 class Oven:
2
3     def insertSpam(self, spam):
4         self.spam = spam
5
6     def getSpam(self):
7         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答案

```   1 def euclid(a, b):
2     while b:
3         a, b = b, a%b
4     return a
```