# 斯坦福编程范式 CS107_24

# Python

Python 是典型的脚本语言 (Scripting language), 它也是面向对象的、函数的 。Python 是动态的,C 和 C 不是,C 和 C 使用大量时间进行编译,在运行时只有非常少的类型信息。Scheme 和 Python 都保持运行时,存在的每一个数据段的类型信息,你实际上可以查询数据类型,只要你想。

和 Scheme 相似

>1 + 2 + 3 + 4
10
>"Hello"
"Hello"

Python 使用 list 的一些操作

>>> seq = [0, 1, 2, 3, 5, 6]
>>> seq[4:4] = [4]
>>> seq
[0, 1, 2, 3, 4, 5, 6]

它在处理一些句法的时候更加的优雅,相较于 C 或 JAVA。Python 中以方括号括起来的被称为列表,以圆括号括起来的被称为数组,数组不想列表那样可以随意改变,它是只读的。

>>> seq = (1, 2, 3, 5, 6)
>>> seq[4] = 14
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

# 写函数

我们想要构造一个 gatherDivisors 函数,实现如下功能:传入的数被特定的数来除并得到正整数,比如 24 可以分别被 24,12,8,6,4,2,1 除,得到 1,2,3,4,6,8,12,24.

>>>gatherDivisors(24)
[1,2,3,4,6,8,12,24]

下面来实现这个函数。

def gatherDivisors(number):
    divisors = []
    for div in range(1,number+1):
        if number%div == 0:
            divisors.append(div)
	return divisors

我们将这个函数写在 divisors.py 文件中,在控制台中,如果我们想要使用,就需要用到

import divisors

但是这个时候如果我们使用 gatherDivisors(24) 仍然会报错,因为导入这个包不代表着那里面所有预定义的东西突然连接到当前环境下,所以如果你需要调用 gatherDivisors ,有两种方法:

"""第一种方法"""
import divisors
divisors.gatherDivisors(24)
"""第二种方法"""
from divisors import gatherDivisors
gatherDivisors(24)

# 字典

字典是 python 中一个重要的数据结构。字典是完全支持哈希表的。字典是 python 中很容易最有延展性的。

>>>student = {}
{}
>>>student['name'] = "Linda"
{'name':'Linda'}
>>>student['gpa'] = 3.98
{'name':'Linda','gpa':3.98}
>>> student['name']
'Linda'
>>> student['gpa'] = 4.5
>>> student
{'name': 'Linda', 'gpa': 4.5}