当前位置:   article > 正文

像科学家一样思考python_像计算机科学家一样思考python笔记

像计算机科学家一样思考python 笔记

[TOC]

#1 程序之道

##1.1 Python程序语言

- 有两种程序可以让高级语言转换为低级语言,分别是直译器和编译器.

- 有两种方式使用python的直译器:shell模式和脚本模式.

##1.8 形式语言和自然语言

- 自然语言是人们所说的语言。

- 形式语言是人们为特定的应用设计的语言

*程序语言是设计来呈现计算的形式语言*

语法规则分为两种,分别属于标记和结构。标记是程序语言的基本组件,就像字词、数字和化学元素一样;

结构是标记的排列方法。

> 当你阅读英文句子或者是形式语言的陈述,你必须理解句子的结构是什么,这种过程叫分析。

**歧义性:**自然语言充满了歧义

**冗赘性:**自然语言为了弥补歧义以及减少误解,使用了大量的赘词。

**字面性:**自然语言充满成语和隐喻。

***

#2 变量、表达式以及陈述(print)

##2.1 数值和型态

- 2是数值, "chess"是字符串.

```python

>>> print ‘chess‘

chess

>>> type(3.2)

```

##2.3 变量名称与关键字

- **变量名称**可以为任意长度,也可以同时包含字母与数字. 但是必须以字母开头

python有`31`个关键字

|and|del|from|not|while|

|:----|:---|:----|:---|:----|

|as|elif|global|or|with|

|assert|else|if|pass|yield|

|break|except|import|print|class|

|exec|in|raise|continue|finally|

|is|return|def|for|lambda|

|try|

##2.5 表达式求值

令人迷惑的是,求取表达式的值和打印一个数值不完全相等

```python

>>> message="oh, shit"

>>> message

‘oh, shit‘

>>> print message

oh, shit

>>>

```

##2.9 输入

Python有两个内建函数可以取得键盘的输入数据:

```python

>>> n=raw_input(‘请输入你的姓名:‘)

请输入你的姓名:lifeng

>>> print n

lifeng

>>> n=input(‘请输入一个数字表达式:‘)

请输入一个数字表达式:3*9

>>> print n

27

>>> n=raw_input(‘请输入一个表达式:‘)

请输入一个表达式:3*8

>>> print n

3*8

```

input输入的是表达式

***

#3 函数

## 3.1 函数的定义及用法

- 在程序设计的范畴内,函数是一个有名称的语句序列,用来执行所需的运算。

在python中,函数定义的语法为:

```python

def name(List of PARAMETERS):

STATEMENTS

```

##3.3 参数、自变量以及import语句

- 另一个接受一个以上自变量的内建函数是max

```python

>>> max(7,11,4,23,93)

93

```

- import关键字

我们可以使用import语句来将我们在脚本中定义的函数汇入直译式程序中。

我们先假设print_twice函数被定义在chap03.py中

```python

>>> from chap03 import *

>>> print_twice(‘lifeng‘)

lifeng lifeng

>>> print_twice(5)

5 5

>>>

```

***

#4 条件表达式

##4.2 布尔值与表达式

布尔值只有两种True和False

```python

>>> type(True)

>>> type(False)

>>> type(true)

Traceback (most recent call last):

File "", line 1, in

NameError: name ‘true‘ is not defined

```

##4.3 逻辑运算符

- 逻辑运算符有三个and、or、not

##4.4 条件执行

if语句

```python

if x > 0:

print "x is positive"

```

##4.10 类型转换

```python

>>> int(-2.33)

-2

>>> int(-2.5)

-2

>>> int(-2.6)

-2

>>> int(3.6)

3

>>> str(32)

‘32‘

>>> bool(1)

True

>>> bool("!no")

True

>>> bool("")

False

```

***

# 5 多效函数

## 5.1 返回值

有返回值的函数, 我们称之为多效函数(fruitful function)

##5.5 函数的型态

```python

>>> def funcccc():

... return "this is a function"

...

>>> type(funcccc)

>>>

```

##5.7 三引号字符串

```python

>>> print ‘‘‘mariy said:"you are so fool", maria replyed:"you know‘function‘"‘‘‘

mariy said:"you are so fool", maria replyed:"you know‘function‘"

>>> print ‘‘‘mariy said:"you are so fool",

... maria replyed:"you

... know‘function‘"‘‘‘

mariy said:"you are so fool",

maria replyed:"you

know‘function‘"

>>> print """mary you said:"you nothing", maria replyed:

... "so you know"."""

mary you said:"you nothing", maria replyed:

"so you know".

```

三引号字符串,可以在其中输入双引号以及单引号。

##5.8 使用doctest做单元测试

***

#6 重复

##6.1 多重指派

```python

a=5

b=a #a和b现在相等

a=3 #a和b现在不相等了

```

##6.2 更新变量

##6.3 while语句

```python

def coutdown(n):

while n > 0:

print n

n = n -1

print "Blastoff!"```

##6.9 封装与一般化

封装是将一段程序代码包裹进函数的过程,这让你可以充分利用函数的所有优点。

一般化就是加参数。

***

#7. 字符串

##7.1 复合数据型态

到目前为止我们已经看过五种型态: `int`、`float`、`bool`、`NoneType`、以及`str`.```python

>>> fruit="banana"

>>> letter=fruit[1]

>>> print letter

a

>>> len(fruit)

6

```

##7.3 走访以及for循环

```python

index=0

while index < len(fruit):

letter = fruit[index]

print letter

index += 1

```

##7.4 字符串切片

```

>>> s="Peter jackson, all you done is great"

>>> print s[0:5]

Peter

>>> print s[6:13]

jackson

```

如果你省略了第一个索引,切片将会在字符串的起点开始,如果你省略了第二个索引,切片将会以字符串的末端作为结束。

##7.5 字符串比较

比较运算符一样可以运用在字符串上,为了确认两个字符串是否相等。

```python

if word == "banana":

print "Yes, we have no bananas!"

if word < "banana":

print "Your word, " + word + ", comes before banana."

elif word > "banana":

print "Your word, " + word + ", comes after banana"

else:

print "Yes, we have no bananas"

```

##7.7 in运算符

```python

>>> ‘p‘ in ‘person‘

True

>>> ‘a‘ in ‘person‘

False

>>> ‘er‘ in ‘person‘

True

```

##7.10 选择性参数

```python

def find(string, ch, start=0)

```

##7.11 string模块

```python

>>> import string

>>> dir(string)

[‘Formatter‘, ‘Template‘, ‘_TemplateMetaclass‘, ‘__builtins__‘, ‘__doc__‘, ‘__file__‘, ‘__name__‘, ‘__package__‘, ‘_float‘, ‘_idmap‘, ‘_idmapL‘, ‘_int‘, ‘_long‘, ‘_multimap‘, ‘_re‘, ‘ascii_letters‘, ‘ascii_lowercase‘, ‘ascii_uppercase‘, ‘atof‘, ‘atof_error‘, ‘atoi‘, ‘atoi_error‘, ‘atol‘, ‘atol_error‘, ‘capitalize‘, ‘capwords‘, ‘center‘, ‘count‘, ‘digits‘, ‘expandtabs‘, ‘find‘, ‘hexdigits‘, ‘index‘, ‘index_error‘, ‘join‘, ‘joinfields‘, ‘letters‘, ‘ljust‘, ‘lower‘, ‘lowercase‘, ‘lstrip‘, ‘maketrans‘, ‘octdigits‘, ‘printable‘, ‘punctuation‘, ‘replace‘, ‘rfind‘, ‘rindex‘, ‘rjust‘, ‘rsplit‘, ‘rstrip‘, ‘split‘, ‘splitfields‘, ‘strip‘, ‘swapcase‘, ‘translate‘, ‘upper‘, ‘uppercase‘, ‘whitespace‘, ‘zfill‘]

>>> type(string.digits)

>>> type(string.find)

>>> print string.digits

0123456789

>>> print string.find.__doc__

find(s, sub [,start [,end]]) -> in

Return the lowest index in s where substring sub is found,

such that sub is contained within s[start,end]. Optional

arguments start and end are interpreted as in slice notation.

Return -1 on failure.

>>> string.find("banana","na")

2

>>> string.find("bob","b", 1,2)

-1

```

##7.12 字符的分类

```python

>>> print string.lowercase

abcdefghijklmnopqrstuvwxyz

>>> print string.uppercase

ABCDEFGHIJKLMNOPQRSTUVWXYZ

>>> print string.whitespace

>>>

```

string.whitespace中包含空格、tab(\t)、新行(\n)

##7.13 字符串的格式化

```

>>> "His name is %s." % "Arthur"

‘His name is Arthur.‘

>>> name="lifeng"

>>> age=30

>>> "I am %s and I am %d years old" % (name,age)

‘I am lifeng and I am 30 years old‘

```

***

#9 tuple(元组)

##9.1 可变性与tuple

字符串是不可变型的, 但是列表是可变型的。

python还有一个称谓tuple的型态。它和列表非常相似,只不过它是不可变的。

从语法上说tuple是一系列用逗号分隔的值, 一个元素的tuple必须在最后加上一个逗号,否则会被当成字符串:

```

>>> tuple=‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘

>>> type(tuple)

>>> t1=(‘a‘, ‘b‘)

>>> t2=(‘a‘,)

>>> type(t2)

>>> t3=(‘a‘)

>>> type(t3)

>>> tuple[0]

‘a‘

>>> tuple[1:3]

(‘b‘, ‘c‘)

```

##9.2 tuple指派

数值交换,传统的写法

```

>>> a=10

>>> b=20

>>> temp=a

>>> a=b

>>> b=temp

>>> a

20

>>> b

10

```

tuple指派的写法

```

>>> a=10

>>> b=20

>>> a,b=b,a

>>> a

20

>>> b

10

```

三值互换:

```

>>> a,b,c=10,20,30

>>> a,b,c=c,a,b

>>> a

30

>>> b

10

>>> c

20

```

##9.4 随机数字

random在数学上说并不是真正随机的。但是可以满足我们日常的要求:

```

>>> import random

>>> for i in range(10):

... x = random.random()

... print x

...

0.684719929612

0.0464362929874

0.395376767428

0.800637456994

0.99066361106

0.765716907162

0.989860584657

0.413398095796

0.935161433805

0.0607366842634

```

***

#10. 字典

***

#11. 文件和异常

当一个程序运作的时候,它的数据会在内存中,当这个程序结束的时候,数据就会丢失,要存储就应该将这些放入一个档案中。

```

>>> f=open("test.dat", "w")

>>> print f

>>>

```

写文件

```

>>> f.write("now learning python")

>>> f.write("now stop writing python")

>>> f.close()

```

读文件。 f.read()会读取文件的全部内容

```

>>> f=open("test.dat", "r")

>>> text = f.read()

>>> print text

new line

>>>

```

原文地址:http://www.cnblogs.com/kakafra/p/fac8cf9cd1a45398520e4a41c9ebbadb.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/716216
推荐阅读
相关标签
  

闽ICP备14008679号