Python 文档阅读02

if语句

else是可以选择的,elif(else if缩写)也是可以0个或多个。

>>> x = int(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')
...
More

for语句

python的for语句与常见的C语言中的for语句是不同的。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[:]:  # Loop over a slice copy of the entire list.
...     if len(w) > 6:
...         words.insert(0, w)
...
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']

range()函数

如果想要一个只包含数字的序列,可通过内置函数range()来操作;该函数共有3个参数,当只填写一个时,默认改值为结束位置,起始为0,步数为1;当填写两个时,默认为起始与结束位置,步数为1;很显然,第三个参数为步数;注意,结束位置永远不包含在内。如下

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4
>>>
range(5, 10)
   5 through 9

range(0, 10, 3)
   0, 3, 6, 9

range(-10, -100, -30)
  -10, -40, -70

为了在迭代中显示索引,可通过range()与len()实现;第二种更常用的方法是通过enumerate()函数。

>>> 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
>>>
>>>li = ['a', 'b', 'c', 'd']
>>>for i in enumerate(li, 0):
...    print(i)
...    
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')

为了节省空间,range()返回的是一个迭代器对象,我们只有通过迭代才能将值取出来,for语句可用于迭代,list()也可用于迭代。

>>> print(range(5))
range(0, 5)
>>> list(range(5))
[0, 1, 2, 3, 4]

break, continue语句以及循环中else子句

break用于跳出最近的for或while循环;循环中的else子句是循环结束或条件为假并且不由break终止时执行的语句;try语句中的else当没有异常发生时执行,循环中的else当没有break时执行;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
>>>
>>> for num in range(2, 10):
...     if num % 2 == 0:
...         print("Found an even number", num)# even number 偶数
...         continue
...     print("Found a number", num)
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9

pass语句

pass语句用于占位符,不执行任何操作,但符合语法结构,以示解释器不会报错。

>>> while True:
...     pass  # Busy-wait for keyboard interrupt (Ctrl+C)
...
>>> class MyEmptyClass:
...     pass
...

定义函数

def是定义函数的关键字,后面还必须要有函数名与括号,参数可选;函数整体的语句是缩进的;函数缩进语句块中的第一行建议写函数注释;函数括号中的参数通常称之为形参,函数调用时的参数称之为实参;函数内部是无法修改外部的变量,除非调用global语句。如下产生斐波拉契数列

>>> def fib(n):    # write Fibonacci series up to n
...     """Print a Fibonacci series up to n."""
...     a, b = 0, 1
...     while a < n:
...         print(a, end=' ')
...         a, b = b, a+b
...     print()
...
>>> # 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
>>>
>>>
>>> f = fib
>>> f(100)
0 1 1 2 3 5 8 13 21 34 55 89

当函数没有return语句时默认返回None;函数调用是函数对象的调用,如下;result.append(a)也是result对象调用appen方法。

>>> fib
<function fib at 10042ed0>
>>>
>>> print(fib(0))
None
>>>
>>> def fib2(n):  # return Fibonacci series up to n
...     """Return a list containing the Fibonacci series up to n."""
...     result = []
...     a, b = 0, 1
...     while a < n:
...         result.append(a)    # see below
...         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]

函数定义的更多方法

默认参数值

最常用的方式是对一个或多个参数指定默认值,这样当函数被调用时可以传入更少的值。

def ask_ok(prompt, retries=4, reminder='Please try again!'):
    while True:
        ok = input(prompt)
        if ok in ('y', 'ye', 'yes'):
            return True
        if ok in ('n', 'no', 'nop', 'nope'):
            return False
        retries = retries - 1
        if retries < 0:
            raise ValueError('invalid user response')
        print(reminder)

示例中有三种调用方式:

  • 必须给一个参数:ask_ok('Do you really want to quit?')
  • 给两个参数: ask_ok('OK to overwrite the file?', 2)
  • 给三个参数: ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')
    示例中还展示了in关键字,该关键字用来测试某个元素是否在该序列中。
i = 5
def f(arg=i):
    print(arg)
i = 6
f()

参数的默认值只会计算一次,所以上示例中会打印5;但如果默认值是可变的,情况就有可能不同。如下示例

def f(a, L=[]):
    L.append(a)
    return L
print(f(1))
print(f(2))
print(f(3))
# 输出,因为L是指向[]的位置,而[]中的值是可变的
[1]
[1, 2]
[1, 2, 3]
# 下面方式可以避免
def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L
关键字参数

函数可通过kwarg=value传值。

def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
    print("-- This parrot wouldn't", action, end=' ')
    print("if you put", voltage, "volts through it.")
    print("-- Lovely plumage, the", type)
    print("-- It's", state, "!")

调用上面函数,必须的参数有一个,可选的有两个。
可通过一下方式调用:

parrot(1000)                                          # 1 positional argument
parrot(voltage=1000)                                  # 1 keyword argument
parrot(voltage=1000000, action='VOOOOOM')             # 2 keyword arguments
parrot(action='VOOOOOM', voltage=1000000)             # 2 keyword arguments
parrot('a million', 'bereft of life', 'jump')         # 3 positional arguments
parrot('a thousand', state='pushing up the daisies')  # 1 positional, 1 keyword

下面是错误的调用

parrot()                     # required argument missing
parrot(voltage=5.0, 'dead')  # 位置参数要放前面,关键字参数必须放位置参数后面
parrot(110, voltage=220)     # duplicate value for the same argument
parrot(actor='John Cleese')  # unknown keyword argument

*name可以接受一个tuple以及将多余的参数收进去;**name可以接受一个字典;前者必须在后者前面

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])

调用如下

cheeseshop("Limburger", "It's very runny, sir.",
           "It's really very, VERY runny, sir.",
           shopkeeper="Michael Palin",
           client="John Cleese",
           sketch="Cheese Shop Sketch")

打印如下

-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch
任意参数的列表
>>> def concat(*args, sep="/"):
...     return sep.join(args)
...
>>> concat("earth", "mars", "venus")
'earth/mars/venus'
>>> concat("earth", "mars", "venus", sep=".")
'earth.mars.venus'
参数列表拆包

是用或者*分别对list与dict进行拆包传入

>>> list(range(3, 6))            # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> list(range(*args))            # call with arguments unpacked from a list
[3, 4, 5]
>>> def parrot(voltage, state='a stiff', action='voom'):
...     print("-- This parrot wouldn't", action, end=' ')
...     print("if you put", voltage, "volts through it.", end=' ')
...     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 !
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值