Python 基础

注释

  • 单行注释 # 注释 # 后面直到行尾
  • 多行注释 以 3 个单引号开头('''),并在注释结束的位置以 3 个单引号(''')结尾

变量

给变量赋值时,python 判断变量的类型,无需事先声明,示例

    a = 0
    b = 2
    print(a + b)

结果

    2

python 自动识别 a 和 b 为数字,现在试下 0 和 2 都是字符串并创建新字符串 "02"

    a = "0"
    b = "2"
    print(a + b)

结果

    02

将变量造型为特定类型

    a = "0"
    b = 2
    print(int(a) + b)

结果

    2

几个重要的 python 造型函数

  • int(x) 将变量造型为整数
  • str(x) 将变量造型为字符串
  • float(x) 将变量造型为浮点数

操作符

编程语言都有操作符,python 也不例外。操作符用于 5 个不同的区域:算术,赋值,加/减,比较,逻辑。

算术操作符

    print (3 + 4)
    print (3 - 4)
    print (3 * 4)
    print (3 / 4)
    print (3 % 2)
    print (3 ** 4) # 3 to the fourth power 3 的 4 次方
    print (3 // 4) # floor division 除法取整,即先做除法,再去掉结果里小数点后的数

结果

    7
    -1
    12
    0.75
    1
    81
    0

不要忘记,+ 号可以连接字符串

赋值操作符

    a = 0
    a += 2
    print(a)

结果

    2

if 语句

    a = 20
    if a >= 22:
        print("if")
    elif a >= 21:
        print("elif")
    else:
        print("else")

结果

    else

if 语法

  • 每个条件后面,有个冒号(:)
  • 满足条件后要执行的语句,需要新起一行,并以 4 个空格开头。并非一定要用 4 个空格,但应该和你之前用来缩进的空格一致。
  • 满足条件后要执行的语句不止一句,那么每个语句都要新起一行并用同样数量的空格开头

函数

使用 def 关键字来定义函数,可以传递参数增加灵活性。

    def someFunction():
        print("boo")
    someFunction()

结果

    boo

在调用之前定义函数是必要的

带参数的函数

    def someFunction(a, b):
        print(a+b)
    someFunction(12, 451)

结果

    463

函数作用域

除非明确表示变量是全局变量,否则 python 不支持全局变量。用例子演示比解释更容易:

def someFunction():
    a = 10
someFunction()

print (a)

上面例子会导致错误,因为变量 a 只在 someFunction 的局部范围内。所以,当我们想要打印 a,python 会说 a 没有定义。理论上,它是定义过的,但不是全局范围内。接下来看一个例子

a = 10

def someFunction():
    print (a)
someFunction()

这个例子里,我们在全局范围定义 a。这表示可以在任何地方调用或修改它,包括在函数内部。但是,不能在函数内部局部范围声明一个变量,在函数外部全局范围使用。

for 循环

for 循环很简单,使一些代码循环一定的次数。在接触列表之前,不会演示 for 循环有多么的灵活。

for a in range(1,3):
    print(a)

结果

    1
    2
  • print 语句的缩进
  • 本例中,a 是什么?a 是一个在每次循环都自增的变量。我们使用 range 关键字设置起点和在刚好在其之前结束的终点——所以 3 没有打印。python 很喜欢这种趋近但不包括的方式。
  • 注意 in 关键字,这是 for 循环的一部分,在学习了列表和字典后将会加深对它的理解。这里先不深入。

while 循环

如果你想要,while 循环可以和 for 循环很相似。本质上都是循环给定的次数,但是 while 循环会更不确定些。通常,while 循环有一个条件,及随后的一些语句,然后是条件变量的增长。

    a = 1
    while a < 10:
        print(a)
        a += 1

结果

    1
    2
    3
    4
    5
    6
    7
    8
    9

while 循环的牛逼之处在于,可以设置一个永远满足的条件,例如 1==1,从而造就一个死循环(这有什么牛逼的),可以用于监听器或游戏里。。。

python 没有 do-while 循环。

字符串

    myString = ""
    print (type(myString))

结果

    <class 'str'>

type() 很牛逼的(又来了)。它返回括号内变量的类型。

常用方法

  • stringVar.count('x') - 'x' 的数量
  • stringVar.find('x') - 'x' 的位置
  • stringVar.lower() - 小写形式
  • stringVar.upper() - 大写形式
  • stringVar.replace('a', 'b') - 将 'a' 用 'b' 替换
  • stringVar.strip() - 清除前导/后缀的空格

字符串索引

在 python 里,几乎一切都可以用索引分解/切分/分片,字符串概莫能外。对字符串来说,索引的实际上是字符。可以获取单个字符或指定一系列字符。

    a = "string"
    print(a[1:3])
    print(a[:-1])

结果

    tr
    strin

讨论一下 print(a[1:3])

  • python 的索引,都从 0 开始,这里就是 's'
  • 前面说过,python 很喜欢趋近但不包含的套路,所以 [1:3] 就是 1,2

然后是 print(a[:-1])

  • 欢迎来到 python 优美的一面
  • 在索引里,冒号(:)后/前的负数,表示你想要 python 从末尾向前逆行。所以,这里我们告诉 python 我们想要从第一个字符到倒数第二个字符
  • 如果冒号前面木有数字?那表示从头开始
  • 如果冒号后面木有数字?那表示直到末尾

列表

python 木有数组,但是有列表。

    sampleList = [1,2,3,4,5,6,7,8]
    print (sampleList[1])

结果

    2

python 索引从 0 开始。

    sampleList = [1,2,3,4,5,6,7,8]
    for a in sampleList:
        print (a)

结果

    1
    2
    3
    4
    5
    6
    7
    8

在学习 for 循环时提到过,学习列表和字典时会加深对 in 关键字的理解。基本上,变量 a 是列表里的元素,循环会增加列表的索引。

常用的列表方法

列表的所有方法可参阅 Python 文档

  • .append(value) - 添加一个元素到列表尾部
  • .count('x') - 统计 'x' 的数量
  • .index('x') - 'x' 元素的索引
  • .insert('y','x') - 将 'x' 添加到 'y' 的位置
  • .pop() - 返回列表最后一个元素,并从列表里移除
  • .remove('x') - 找到并移除列表里的第一个 'x'
  • .reverse() - 反转列表元素
  • .sort() - 按数字或字母升序排列

元组

作为一个老司机,元组这个名词还真是第一次听说捏。。。

在 python 里,元组和列表几乎没什么不同,主要是元组不能改变(这叫没有什么区别?),就是说,不能添加、修改或删除元组里的元素。

嗯,一个不可变的列表,就是元组。

    myList = [1,2,3]
    myList.append(4)
    print (myList)

    myTuple = (1,2,3)
    print (myTuple)

    myTuple2 = (1,2,3)
    myTuple2.append(4)
    print (myTuple2)

结果

    [1, 2, 3, 4]
    (1, 2, 3)
    Traceback (most recent call last):
    File "C:/Python32/test", line 9, in
        myTuple2.append(4)
    AttributeError: 'tuple' object has no attribute 'append'

嗯,列表用方括号,元组是用圆括号的

元组不能添加元素,如果你一定要这么做,试试下面这个例子

    myTuple = (1,2,3)
    myList = list(myTuple)
    myList.append(4)
    print (myList)

结果

    [1, 2, 3, 4]

元组是不可变的,如果你一定要变,不要用元组,用列表来实现你的企图

字典

嗯,字典看上去很像 map

    myExample = {'someItem': 2, 'otherItem': 20}
    print(myExample['otherItem'])

结果

    20

也许你会试着执行 print(myExample[1]),会出错。。。字典不是基于索引滴,字典不是有序滴。。。添加一个键值对到字典,其位置是随机的

注意,字典不支持创建重复的键,python 会覆盖相同键的值。

    myExample = {'someItem': 2, 'otherItem': 20}
    myExample['newItem'] = 400
    for a in myExample:
        print (a)

结果

    newItem
    otherItem
    someItem

纳尼,不是说字典是无序的吗?这里输出的结果怎么是按字母排序的?实际上这是个巧合。。。

    myExample = {'someItem': 2, 'otherItem': 20,'newItem':400}
    for a in myExample:
        print (a, myExample[a])

结果

    ('newItem', 400)
    ('otherItem', 20)
    ('someItem', 2)

关于字典最后一个重要的地方:使用 in 关键字,如果是列表,循环输出的是列表元素的值,如果是字典的话,输出的是字典元素的键

格式化

数字格式化成字符串

    print('The order total comes to %f' % 123.44)
    print('The order total comes to %.2f' % 123.444)

结果

    The order total comes to 123.440000
    The order total comes to 123.44

在第一个 % 后面的 ffloat 的简写,告诉 python 要格式化的是带小数的数字;其左侧的 % 告诉 python 在哪里放置格式化后的字符串(占位符的感觉),在第二个 % 后是想要格式化的值。

python 读取该字符串,直到第一个 %,然后 python 停止读取并跳转到下一个 %,拿到第二个 % 后的值,根据第一个 % 来格式化该值。最后,python 将第二个值放置到第一个 % 所在的位置。可以使用单个的值诸如字符串或数字,也可以使用元组或字典

格式化字符串

格式化字符串和格式化数字相似,区别是使用 s 而非 f 来表示字符串。可以限制字符串的字符数

    a ="abcdefghijklmnopqrstuvwxyz"
    print('%.20s' % a)

结果

    abcdefghijklmnopqrst

异常

通常,使用异常的目的是执行替代的代码,用我们的语言通知用户出了什么问题及如何绕过障碍

异常和错误

    var1 = '1'
    try:
        var1 = var1 + 1 # since var1 is a string, it cannot be added to the number 1 
    except:
        print(var1, " is not a number") # so we execute this
    print(var1)

所谓处理异常:把想要执行的代码放到 try 块,如果异常发生了,python 执行 except 块的代码

一般不会去处理错误,let it go~~

另外,注意到 print 接收了 2 个参数吗?呃,它可以接收你发送的多个参数,并全部打印出来,彼此用空格分隔。

优雅滴处理错误

来看下上面的 try/except,对程序的可用性没有神马价值。基本上就是,出错了,告诉用户出错了。重点是什么?应该要在一定程度上处理异常来帮助程序继续执行下去



结果

    var1 = '1'
    try:
        var2 = var1 + 1 # since var1 is a string, it cannot be added to the number 1 
    except:
        var2 = int(var1) + 1 
    print(var2)

感觉好些了,用户根本不知道程序发生过小小的异常

读取文件

对 python 来说读取文件不过是 a piece of cake

打开文件

文件 test.txt 如下

I am a test file.
Maybe someday, he will promote me to a real file.
Man, I long to be a real file
and hang out with all my new real file friends.
    f = open("test.txt", "r") # opens file with name of "test.txt"

openr 告诉 python 我们想要读取(w 表示想要写入文件)。

读取文件

  • file.read(n) 从文件读取 n 个字符,如果 n 为空则读取整个文件
  • file.readline(n) 从文本文件读取一整行
    f = open("test.txt","r") # opens file with name of "test.txt"
    print(f.read(1))
    print(f.read())

结果

I
 am a test file.
Maybe someday, he will promote me to a real file.
Man, I long to be a real file
and hang out with all my new real file friends.

有点点困惑?首先,我们如愿打开文件,然后,read(1),python 打印出 "I",接下来 read() 理应打印出整个文件,因为我们未传递参数,但是实际打印出来的为包含 "I"。

可以这样理解,read 隐含了一个游标,python 每次 read 后,都会移动游标,下一次的 read 是以这个游标作为起点而不是以文件的第一个字符作为起点。刚打开文件时,游标指向文件的第一个字符。

接下来看看行读取

  f = open("test.txt","r") # opens file with name of "test.txt"
  print(f.readline())
  print(f.readline())

结果

I am a test file.
Maybe someday, he will promote me to a real file.

显然,行读取也存在一个指向行的游标,每读取一行,该游标会移动到下一行

关于 python 的读取能力的最后一个重要、复杂和牛逼的地方

    f = open("test.txt","r") # opens file with name of "test.txt"
    myList = []
    for line in f:
        myList.append(line)
    print(myList)

结果

['I am a test file.\n', 'Maybe someday, he will promote me to a real file.\n', 'Man, I long to be a real file\n', 'and hang out with all my new real file friends.']
  • 首先,\n 是换行符
  • 其次,在 for 循环里用 in 关键字将文件分片成多行。神奇又聪明的 python 知道你想要把文件拆分成行。
  • 再次,在循环里将文件的每一行添加到列表 myList
  • 最后,打印整个列表

关闭文件

    f = open("test.txt","r") # opens file with name of "test.txt"
    print(f.read(1))
    print(f.read())
    f.close()

永远记得用 close() 关闭文件。

写入文件

警告!open 方法里邪恶的 "w"

    f = open("test.txt","w") #opens file with name of "test.txt"
    f.close()

啊哦,我们的内容捏?一旦你给 open 传递了 w 作为第二个参数,python 会清空那个文件,现在让我们重建它

    f = open("test.txt","w") #opens file with name of "test.txt"
    f.write("I am a test file.")
    f.write("Maybe someday, he will promote me to a real file.")
    f.write("Man, I long to be a real file")
    f.write("and hang out with all my new real file friends.") 
    f.close()

现在我们将内容重新写入到文件了。但是,你会发现和之前的内容不一样,没错,朋友~现在看看怎么修复

按行写入

    f.write("Maybe someday, he will promote me to a real file.\n")

追加到文件

    f = open("test.txt","a") #opens file with name of "test.txt"
    f.write("and can I get some pickles on that")
    f.close()

open() 方法的 a 参数表示追加

创建类

#ClassOne.py
class Calculator(object):
        #define class to simulate a simple calculator
        def __init__ (self):
                #start with zero
                self.current = 0
        def add(self, amount):
                #add number to current
                self.current += amount
        def getCurrent(self):
                return self.current

class 关键字来创建一个类,后面是要创建的类的名字,参数 object 是要创建的类的父类。

def __init__(self): 构造函数?参数 self 就是当前实例吧,类似 java 的 this

使用类

from ClassOne import * #get classes from ClassOne file 从 ClassOne 文件获取类
myBuddy = Calculator() # make myBuddy into a Calculator object 使 myBuddy 成为一个 Calculator 对象
myBuddy.add(2) #use myBuddy's new add method derived from the Calculator class
print(myBuddy.getCurrent()) #print myBuddy's current instance variable

在另一个文件里写入上面的代码。现在来解析一下

  1. 假设所有的类都在 python 目录下
  2. from ClassOne,告诉 python 引用哪个文件,import *,意思是我们需要该文件里的所有类
  3. myBuddy = Calculator(),创建一个 Calculator 的实例 myBuddy,在 python 里不需要 new 关键字

Django

Django 是个优秀的 MVC 模式 web 框架。Django 最大的迷惑是把 MVC view 称为 template,MVC controller 称为 view。

编辑器

Notepad++ 也好过默认的编辑器

PyCharm

支持调试;专业版可维护 Django 项目,但要付费。

PyDev

可以在 eclipse 里安装,可免费用于 Django 开发

其他的编辑器

WingIDE 强大,古老,诡异。。。

results matching ""

    No results matching ""