Python基础入门篇

所属系列:【Python工程师系列】  

所属主题:【Python零基础】

Python入门

标签(空格分隔): 未分类


Python具有高级的数据结构,能高效地面向对象编程。它的优雅的语法、动态类型、解释属性使它能快速地在大部分平台开发应用程序。它的第三方包、工具和库都可以在这里找到:https://www.python.org/。

Python很容易通过C/C++函数或数据类型进行扩展。写扩展参看:扩展指导, C/C++的Python API

更多文档参看Python标准库,Python的API

通过这个入门教程,你将学习到Pyton的一些常用特性和标准库的一些方法或模块。

写在前面

对于每天在电脑面前工作的人来说,可能你需要做一些自动化的工作,比如批量替换,查找更改等,或者你想写一些界面程序,游戏等。

而对于专业的软件开发人员来说,通过C/C++/Java库去开发
、测试、编译等又太繁琐了。

这时候,Python是最佳的选择。

你可以写一些shell脚本或者bat脚本去移动文件或者修改数据,但不是很适合写界面程序或者游戏。C/C++/Java又太繁琐了。而Python比较适合快速的在各个平台(windows, Mac, Unix)完成你要的工作。

Python是一门真正的编程语言,它有高级的数据结构,比如可灵活操作的数组和字典。

Python是模块化的,它的标准库里面有你可用的一些模块,这些模块提供了比如文件I/O,sockets等功能。

Python可以写出比C/C++/Java更简洁的程序,原因有三:
1 有高级的数据结构
2 通过缩进进行区分声明块而不是括号
3 不需要变量或者参数声明

Python是可扩展的。你可以把Python解释器嵌入到C程序中。

使用Python解释器

运行python解释器

方式1:
Python解释器在linux下一般安装在/usr/local/bin/python目录下,切换到该目录下,输入以下命令可以运行python解释器

python

windows下一般安装在C:\Python27目录下,win+r快捷键,然后输入一下cmd,打开dos界面,输入以下命令,设置环境变量:

set path=%path%;C:\python27

则任意目录下,输入python命令即可打开python解释器
方式2:

python -c command [arg] ..

因为命令行可能有一些特殊字符或者空白,最好用单引号引起来。
退出python解释器:
Unix下在命令行界面输入快捷键:Control-D, Windows下输入Control-Z。
或者输入:

quit()

调用python模块(模块也就是python源文件):

python -m module [arg] ...

进入交互命令模式:

python -i ...
参数传递

命令行的参数会赋值给sys模块的argv变量。可以通过import sys访问参数。argv的长度至少有1。当没有参数的时候,sys.argv[0]是一个空串。当脚本的名字为”-“,则sys.argv[0]是”-“,当用了-c命令,则sys.argv[0]的值为”-c”。当用了-m,sys.argv[0]的值为模块的名字。-c和-m后面的参数,python解释器不会处理。

交互模式

多行模式前面是… 单行是>>>

>>> the_world_is_flat = 1
>>> if the_world_is_flat:
...     print "Be careful not to fall off!"
...
解释器和环境
设置代码编码

一般情况是不用设置的 默认为utf-8

#!/usr/bin/env python
# -*- coding: cp-1252 -*-

Python介绍

开头标识注释,>>>和…开头标识python语句

>>>
>>> #这是注释
... a = 1;#这是注释
>>> print a
1
把python当做计算器
数字
>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5.0*6) / 4
5.0
>>> 8 / 5.0
1.6

这里2是int 5.0是float,/的结果是什么类型是根据参与计算的两个数,如果有一个数是float则返回float类型。
//操作符是向下取数,小数位为0。

>>> 12//7.0
1.0
>>>

%是求余
**是多次方

>>> 5**2
25
>>>

声明变量n=12
如果使用一个未声明的变量会报错

>>> n
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
>>>

多项式计算,会自动进行数据类型的转换:int和float一起计算,int会自动转为float

交互模式下,最后一个打印的变量会赋值给_

>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06

_是只读的,不能被赋值。

字符串

单引号或者双引号里表示字符串,\用来转义
如果不想要转义:字符串前加一个r

>>> print 'C:\some\name'  # here \n means newline!
C:\some
ame
>>> print r'C:\some\name'  # note the r before the quote
C:\some\name

多行字符串:三个”””或者’’’

print """\
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
"""

\标识去掉换行,没有\输出是这样的:

>>> print """
... aef
... asdf
... """

aef
asdf

字符串拼接:+ 字符串重复:*

>>> "un"*2 +" awef"
'unun awef'
>>>

自动拼接:

>>> 'Py' 'thon'
'Python'

获取字符串的单个字符

>>> a = "python"
>>> a[0]
'p'

负数标识从尾部开始读取: -0等于0 最后一个字符是-1

>>> a = "python"
>>> a[-1]
'n'
>>>

取区间:

>>> a = "python"
>>> a[0:2]
'py'
>>> a[2:]
'thon'
>>> a[:4]
'pyth'
>>> a[-2:]
'on'
>>>

越界访问数组会报错:

>>> word[42]  # the word only has 6 characters
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

但是取不存在的区间不会报错:

>>> a[-2:45]
'on'
>>>

字符串无法被修改:

>>> word[0] = 'J'
  ...
TypeError: 'str' object does not support item assignment
>>> word[2:] = 'py'
  ...
TypeError: 'str' object does not support item assignment
unicode字符串

支持unicode字符串:字符串前加u

>>> u'Hello World !'
u'Hello World !'
>>> u'Hello\u0020World !'
u'Hello World !'

0x0020标识空格
支持原始模式: 字符串前面加入ur
python的默认编码方式是:ASCII码,如果Unicode字符串被打印或者写到文件或者是str()方法转化都会默认转为ASCII码,如果字符串不在0-127范围就会报错

>>> u"abc"
u'abc'
>>> str(u"abc")
'abc'
>>> u"äöü"
u'\xe4\xf6\xfc'
>>> str(u"äöü")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)

转换为特定编码:方法的参数为小写

>>> u"äöü".encode('utf-8')
'\xc3\xa4\xc3\xb6\xc3\xbc'
数组

定义一个数组

>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]

获取数组内元素

>>> squares[0]  # indexing returns the item
1
>>> squares[-1]
25
>>> squares[-3:]  # slicing returns a new list 例子三
[9, 16, 25]

获取数组内片段,比如上面例子三,会返回一个新的数组拷贝,原数组不会发生改变
数组合并:

>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

字符串的内容是不能被更改的,而数组是可以被更改的:

>>> cubes = [1, 8, 27, 65, 125]  # something's wrong here
>>> 4 ** 3  # the cube of 4 is 64, not 65!
64
>>> cubes[3] = 64  # replace the wrong value
>>> cubes
[1, 8, 27, 64, 125]

给数组添加元素:

>>> cubes.append(216)  # add the cube of 6
>>> cubes.append(7 ** 3)  # and the cube of 7
>>> cubes
[1, 8, 27, 64, 125, 216, 343]

可以赋值给截取的数组:

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # replace some values
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # now remove them
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> # clear the list by replacing all the elements with an empty list
>>> letters[:] = []
>>> letters
[]

获取数组的长度:

>>> letters = ['a', 'b', 'c', 'd']
>>> len(letters)
4

数组的元素也可以是一个数组:

>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'
终于开始编程了!

如何实现一个斐波那契:

>>> # 这是一个注释
... a, b = 0, 1  #分别给a赋值为0 b赋值为1 
>>> while b < 10:#这是一个循环
...     print b  #打印b的值(并且这里的代码前面有空格(也就是行缩进))
...     a, b = b, a+b #a赋值为b,b赋值为a+b的和
...
1
1
2
3
5
8

之前说过,行缩进标识接下来是一个代码块。
print方法,可以控制格式,比如增加空格:

>>> i = 256*256
>>> print 'The value of i is', i
The value of i is 65536

在print语句最后加一个逗号,避免打印结果换行:

>>> a, b = 0, 1
>>> while b < 1000:
...     print b,
...     a, b = b, a+b
...
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

控制流

if语句
>>> x = int(raw_input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0: #冒号可以开启多行模式
...     x = 0
...     print 'Negative changed to zero'
... elif x == 0:
...     print 'Zero'
... elif x == 1:
...     print 'Single'
... else:
...     print 'More'
...

if…elif..else(不是必须的)…

for

Python的for可以遍历数组和字符串(这个和C语言的for语句有略微不同)

>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
...     print w, len(w)
...
cat 3
window 6
defenestrate 12

在循环内修改一个数组:首先通过截取数组的方法对原数组进行拷贝(这个知识点之前有提过)

>>> for w in words[:]:  # words[:]可以对原数组进行拷贝
...     if len(w) > 6:
...         words.insert(0, w)
...
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']
range()函数

range函数能根据算法创建一个数组

>>> range(5, 10) #创建所有元素为5到10区间并递增的数组
[5, 6, 7, 8, 9]
>>> range(0, 10, 3)#递增3
[0, 3, 6, 9]
>>> range(-10, -100, -30)#递减30
[-10, -40, -70]

遍历数组的索引:

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
...     print i, a[i]
...
0 Mary
1 had
2 a
3 little
4 lamb
退出循环

break语句执行会退出里层的for循环;continue会跳过后面语句的执行(和C语言用法一样)。

>>> for n in range(2, 10):
...     for x in range(2, n):
...         if n % x == 0:
...             print n, 'equals', x, '*', n/x
...             break
...     else:
...         # loop fell through without finding a factor
...         print n, 'is a prime number'
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
pass语句

pass语句不会做任何事,只是用来占位用的

>>> class MyEmptyClass:
...     pass
...
>>> def initlog(*args):
...     pass   # Remember to implement this!
...
定义函数和调用函数
>>> def fib(n):    # def关键字标识定义函数,这里函数名为fib
...     """Print a Fibonacci series up to n.""" #
...     a, b = 0, 1
...     while a < n:
...         print a,
...         a, b = b, a+b
...
>>> # Now call the function we just defined:
... fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

注意函数体要代码要缩进
函数可以被赋值(fib会被加入符号表):

>>> fib
<function fib at 10042ed0>
>>> f = fib # f也会被加入符号表
>>> f(100)
0 1 1 2 3 5 8 13 21 34 55 89

即便函数没有return,也会返回一个None

>>> fib(0)
>>> print fib(0)
None

return后面没有跟任何东西也是返回None

>>> def fib2(n):  # return Fibonacci series up to n
...     result = []
...     a, b = 0, 1
...     while a < n:
...         result.append(a)    # 这里是调用数组的append方法
...         a, b = b, a+b
...     return result
...
>>> f100 = fib2(100)    # call it
>>> f100                # write the result
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

定义带参数的函数

参数带默认值:retries的默认值为4

def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
    while True: # True是关键字
        ok = raw_input(prompt) #raw_input是内置的函数,用于IO输入
        if ok in ('y', 'ye', 'yes'):
            return True
        if ok in ('n', 'no', 'nop', 'nope'):
            return False
        retries = retries - 1
        if retries < 0:
            raise IOError('refusenik user') # raise是关键字 抛出异常
        print complaint

默认值可以为变量:i是一个变量

i = 5

def f(arg=i):
    print arg

i = 6
f()

默认参数如果是一个可变的对象,会被赋值多次:

def f(a, L=[]):
    L.append(a)
    return L

print f(1)
print f(2)
print f(3)

会打印出:

[1]
[1, 2]
[1, 2, 3]

如果你不想L被改变,你可以这么做:

def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L

如果只接受一个参数,但是传递了两个参数会报错:

>>> def function(a):
...     pass
...
>>> function(0, a=0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: function() got multiple values for keyword argument 'a'

**kewords接收字典参数:

def cheeseshop(kind, *arguments, **keywords):
    print "-- Do you have any", kind, "?"
    print "-- I'm sorry, we're all out of", kind
    for arg in arguments:
        print arg
    print "-" * 40
    keys = sorted(keywords.keys()) #按字典顺序 
    for kw in keys:
        print kw, ":", keywords[kw]

*arg接受不确定个数的参数:

def write_multiple_items(file, separator, *args):
    file.write(separator.join(args))

自动解析参数:

>>> range(3, 6)             # 正常情况调用方式
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args)            # 从一个数组里解析参数
[3, 4, 5]
>>> def parrot(voltage, state='a stiff', action='voom'):
...     print "-- This parrot wouldn't", action,
...     print "if you put", voltage, "volts through it.",
...     print "E's", state, "!"
...
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !

文档字符串:

>>> def my_function():
...     """Do nothing, but document it.
...
...     No, really, it doesn't do anything.
...     """
...     pass
...
>>> print my_function.__doc__
Do nothing, but document it.

    No, really, it doesn't do anything.

Lambda表达式一个匿名函数,lambda a, b: a+b. a和b是两个参数,结果返回a和b的和:

>>> def make_incrementor(n):
...     return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43

lambda也可以作为参数传递:

>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

参考官方:https://docs.python.org/

欢迎关注:code_digger 关注跨行业编程

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值