程序员Python 运维Python语言与信息数据获取和机器学习

Python笔记4:控制流

2017-11-04  本文已影响10人  世外大帝

if语句

虽然语法比较严格,但是语法糖也是较多的,比如我尝试用下面的if语句写了一个表达式,多样性的

>>> x = int(input("enter num"))
enter num50
>>> if(x<0):
...     x=0
...     print("归零")
... elif x==0:
...     print("0")
... elif(x==1):
...     print("1")
... else:
...     print("more")
...
more

for循环

Python中的for循环与C和java中的不太一样,格式和kotlin有点像,但也可以看出他的含义,注意语法就行了

# python普通for循环
>>> nums = ['one','two','three']
>>> for num in nums:
...     print(num,len(num))
...
one 3
two 3
three 5

# kotlin和python的普通循环方式很像
val nums = arrayOf("one", "two", "three")
for (num in nums) {
    println(num)
}

# 传统java的循环方式
String[] nums = new String[]{"one","two","three"};
for (String num : nums) {
    System.out.println(num);
}

# python循环添加
>>> nums = ["one","two","three"]
>>> nums
['one', 'two', 'three']

# 循环中的切片副本必须显式调用
>>> for num in nums[:]:
...     if len(num) >3:
...             nums.insert(0,num)
...
>>> nums
['three', 'one', 'two', 'three']

range()函数

如果需要迭代遍历数字,那可以直接用内置函数range(),它会生成等差数列

# 类似传统的普通for循环
>>> for num in range(3):
...     print(num)
...
0
1
2

# 范围循环
>>> for num in range(5,10):
...     print(num)
...
5
6
7
8
9

# 间隔循环
>>> for num in range(0,10,3):
...     print(num)
...
0
3
6
9

# 间隔负循环
>>> for num in range(0,-100,-25):
...     print(num)
...
0
-25
-50
-75

# 遍历序列索引,合并range()和len()函数
>>> 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

# 配合list
>>> list(range(5))
[0, 1, 2, 3, 4]

后面还有一些循环技巧,例如

>>> for i ,j in enumerate(["zhangsan","lisi","wangwu"]):
...     print(i,j)
...
0 zhangsan
1 lisi
2 wangwu

控制流都这么多,这些技巧的到后面必须掌握一些

pass语句

一般程序执行的时候,什么都不做就什么都不用写,但是python不行,需要显式调用pass,表示忽略,或者可以理解为抽象方法,抽象类等等

调试的时候,不是经常这么干么?创建了一个函数,还来不及具体实现?就可以先用pass顶上


# 空循环
>>> while True:
...     pass
...

# 空类
>>> class EmptyClass:
...     pass
...

# 待定义函数
>>> def init(*args):
...     pass
...

定义函数def

普通应用

# 定义一个斐波那契数列
>>> def fib(n):
...     a,b = 0,1
...     while a<n:
...             print(a,end=" ")
...             a,b = b,a+b
...     print()
...

# 测试结果
>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

# 值传递
>>> fibonacci = fib
>>> fibonacci(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

# 打印出来的函数可以为None
# 先证明是有值的
>>> fib(20)
0 1 1 2 3 5 8 13

>>> fib(0)

>>> print(fib(0))

None

带返回值

上面的斐波那契数列虽然能打印出来,但其实是没有返回值的,以返回数组为例

>>> def fib(n):
...     # 初始化一个空数组
...     result = []
...     a,b = 0,1
...     while a<n:
                # append是追加到末尾的
                # 等价于result = result + [a]
...             result.append(a)
...             a,b = b, a+b
...     return result
...
>>> fib(100)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

# 并且也可以赋值
>>> fib50 = fib(50)
>>> fib50
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

高级定义函数

参数默认值

顾名思义,就是给参数赋默认值,用Python自带的IDLE试试

默认值

# 定义函数,prompt必填,后两个选填
>>> def sayOk(prompt, retries = 4, reminder = "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 -= 1
        if(retries) < 0:
            raise ValueError("invalid user response")
        print(reminder)

# 不填prompt会直接跳出
>>> sayOk()
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    sayOk()
TypeError: sayOk() missing 1 required positional argument: 'prompt'

# 至少填一个,剩下为空会赋默认值
>>> sayOk("are you quit?")
are you quit?
try again!
are you quit?y
True

# 也可以都填
>>> sayOk("are you OK?",3,"say!you 倒是 say啊, 就say个yes或者no!")
are you OK?
say!you 倒是 say啊, 就say个yes或者no!
are you OK?no
False

参数累积

# 当默认值是可变参数时,会在后续调用中传递给它的参数累积
>>> def fun(a, List = []):
    List.append(a)
    return List

>>> print(fun(1))
[1]
>>> print(fun(2))
[1, 2]
>>> print(fun(3))
[1, 2, 3]

# 除非每次都置空
    def fun(a, list=None):
        if list is None:
            list = []
            list.append(a)
            return list

    print(fun(1))
    print(fun(2))
    print(fun(3))
    
[1]
[2]
[3]

关键字参数

关键词参数的好处在于,不需要按照定义的顺序去传参。

# 4个参数
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(voltage=1000000, action='VOOOOOM') 
parrot(action='VOOOOOM', voltage=1000000)

# 没有关键词参数,会按照入参顺序排列
parrot('a million', 'bereft of life', 'jump')

无效的情况

parrot()                     # 没有请求参数
parrot(voltage=5.0, 'dead')  # 关键字参数后面不能跟非关键字参数
parrot(110, voltage=220)     # 会被判为相同参数,导致重复
parrot(actor='John Cleese')  # 参数错误导致的未知参数

可变参数列表

一般的可变参数列表,不限数量,不限格式

>>> def concat(*args, sep="/"):
    return sep.join(args)

>>> concat("one","two","three")
'one/two/three'

>>> concat("one","two","three",sep=" .")
'one .two .three'

复杂的例子

# *name必须在**name的前面
>>> def cheeseshop(kind, *args, **keywords):
    print("--你这有",kind,"吗?")
    print("--有,",kind,"是我们的招牌,咋能没有么!")
    for arg in args:
        print(arg)
    print("-" * 40)
    for key in keywords:
        print(key,":",keywords[key])
        
# 输出
# 关键字参数的顺序和函数调用的顺序相同
>>> cheeseshop("肉夹馍","可好吃啦!全是肉","给我拿两个", laoban="陕西人", client="南方人")

# 结果
--你这有 肉夹馍 吗?
--有, 肉夹馍 是我们的招牌,咋能没有么!
可好吃啦!全是肉
给我拿两个
----------------------------------------
laoban : 陕西人
client : 南方人
上一篇 下一篇

猜你喜欢

热点阅读