python外壳,代码结构

1.1 True与False

以下集中在判断时为False,其余都是True

类型
布尔值 False
null类型 None
整数 0
浮点数 0.0
空字符串 ''
空Tuples ()
空Lists []
空Dictionaries {}
空Set set()

1.2循环

使用break可以跳出循环
使用continue可以跳过次循环的后续,进行下一次循环
使用else可以判断沒有使用break时的情況。

使用zip()可以对多组Object同时进行循环迭代!!

days = ['Monday', 'Tuesday', 'Wednesday']
fruits = ['banana', 'orange', 'peach']
drinks = ['coffee', 'tea', 'beer']
desserts = ['tiramisu', 'ice cream', 'pie', 'pudding']
print('原方法:')
for i in range(len(days)):
    print(days[i], ": drink", drinks[i], "- eat", fruits[i], "- enjoy", desserts[i])

print('\nzip()用法:')
for day, fruit, drink, dessert in zip(days, fruits, drinks, desserts):
    print(day, ": drink", drink, "- eat", fruit, "- enjoy", dessert)
原方法:
Monday : drink coffee - eat banana - enjoy tiramisu
Tuesday : drink tea - eat orange - enjoy ice cream
Wednesday : drink beer - eat peach - enjoy pie

zip()用法:
Monday : drink coffee - eat banana - enjoy tiramisu
Tuesday : drink tea - eat orange - enjoy ice cream
Wednesday : drink beer - eat peach - enjoy pie
english = 'Monday', 'Tuesday', 'Wednesday'
french = 'Lundi', 'Mardi', 'Mercredi'
 
print('转换成list包tuple')
print(list( zip(english, french) ))
print('转换成Dictionarie')
print(dict( zip(english, french) ))
转换成list包tuple
[('Monday', 'Lundi'), ('Tuesday', 'Mardi'), ('Wednesday', 'Mercredi')]
转换成Dictionarie
{'Monday': 'Lundi', 'Tuesday': 'Mardi', 'Wednesday': 'Mercredi'}

1.3Comprehensions 推导式


list推导式 

listObj = [expression for item in iterable if condition]
print([number for number in range(1,6) if number % 2 == 1])  #[1, 3, 5]
rows = range(1,4)
cols = range(1,3)
cells = []
for row in rows:
    for col in cols:
        cells.append((row, col))
与一下代码等价
cells = [(r,c) for r in range(1, 4) for c in range(1, 3)]

dictionary推导式 

dictionaryObj = { key_expression : value_expression for expression in iterable if condition}
# 计算一个单字里字母的出现的次数
# 使用Set排除重复字母
word = 'letters'
letter_counts = {letter: word.count(letter) for letter in set(word) if letter.lower() not in 'aeiou'}
print(letter_counts)  #{'t': 2, 'l': 1, 's': 1, 'r': 1}

set推导式

set_Obj = {expression for expression in iterable if condition}
print({number for number in range(1,6) if number % 3 == 1})  #{1, 4}

generator推导式 

tuples没有推导式的用法,使用()包起來是generator推导式的用法
简单来说就是可以产生像是range()的Object,亦表示可以直接对齐迭代

记住!!!generator只能使用一次!!!

number_thing = (number*3-2 for number in range(1, 6))
print((1,))  #(1,)
print(number_thing)  #<generator object <genexpr> at 0x7ff1e00276d0>
for number in number_thing:
    print(number)#正常输出
# 或者转为list使用
number_list = list(number_thing)
print(number_list)  #[]
print('因为只能使用一次,所以上面这边找不到东西了')
number_thing = (number*3-2 for number in range(1, 6))
number_list = list(number_thing)
print(number_list)#正常输出

1.4 Function函数

不一定要return,但有return一定要有变量接住他,或是使用他。若此function沒有return则返回None

位置参数与关键字参数

要把参数传进function中有两种方法,位置参数与关键字参数,示例如下 (如果同时出现,则以位置参数优先)

可以在定义函数时,设定默认值,若使用function时沒有填入改参数,則使用默认值,有的话则覆盖。

# 特別注意!!!!若把空list当做默认值会发生意料之外的事情
def buggy(arg, result=[]):
    result.append(arg)
    print(result)
# 第一次使用时OK
buggy('a')  #['a']
# 第二次使用时就会残存上次的结果
buggy('b')  #['a','b']
# 可以使用以下方法修改function
def works(arg):
    result = []
    result.append(arg)
    print(result)
def nonbuggy(arg, result=None):
    if result is None:
        result = []
    result.append(arg)
    print(result)
works('a') #['a']
works('b')  #['b']
nonbuggy('a')  #['a']
nonbuggy('b')  #['b']

使用*与**收集位置参数和关键字参数

*收集的参数会以Tuples储存,**收集的参数会以Dictionary储存

print('全部都给收集器')
def print_args(*args):
    print('Positional argument tuple:', args)
print_args() #()
print_args(1,2,3) #(1,2,3)
print('\n混合位置参数使用,剩下的都给收集器')
def print_more(required1, required2, *args):
    print('Need this one:', required1)
    print('Need this one too:', required2)
    print('All the rest:', args)
print_more('cap', 'gloves', 'scarf', 'monocle', 'mustache wax') 
#Need this one: cap
#Need this one too: gloves
#All the rest: ('scarf', 'monocle', 'mustache wax')

def print_kwargs(**kwargs):

    print('Keyword arguments:', kwargs)
print_kwargs(wine='merlot', entree='mutton', dessert='macaroon')
#Keyword arguments: {'wine': 'merlot', 'entree': 'mutton', 'dessert': 'macaroon'}

function说明文字

为了提高代码的可读性,可以对自行定义出的函数加上说明文字,他人在使用时就可以使用help叫出文字。

def echo(anything):
    'echo returns its input argument'
    return anything
def print_if_true(thing, check):
    '''
Prints the first argument if a second argument is true.
The operation is:
1. Check whether the *second* argument is true.
2. If it is, print the *first* argument.
    '''
    if check:
        print(thing)
help(echo)
print('--------------------------------')
help(print_if_true)
print('\n仅叫出文字↓')
print(echo.__doc__)
print('--------------------------------')
print(print_if_true.__doc__)
#Help on function echo in module __main__:
#echo(anything)
#   echo returns its input argument
#--------------------------------
#Help on function print_if_true in module __main__:
#print_if_true(thing, check)
#    Prints the first argument if a second argument is true.
   
 #   The operation is: 
 #  1. Check whether the *second* argument is true.   
 #   2. If it is, print the *first* argument.
#仅叫出文字↓
echo returns its input argument
--------------------------------
Prints the first argument if a second argument is true.
The operation is:
1. Check whether the *second* argument is true.
2. If it is, print the *first* argument.
#

一等公民:function

在python的设计中,function是一级公民。
换句话说python是Object导向的语言,所有的东西都是Object,连function也是。所以说function可以当成参数传入其他function,也可以将function当成结果回传。

def run_something(func, a, b):
    print(func(a, b))
def add(a, b):
    return a + b
run_something(add, 2, 3)  #5
test = add
test(3,5)  #8

内部函数

function内部可以再定义function

def outer(a, b):
    def inner(c, d):
        return c + d
    return inner(a, b)
print(outer(4, 7))  #11

闭包

可以动态生成函數,可用来记录外部传入的变量

def knights2(saying):
    def inner2():
        return "We are the knights who say: '%s'" % saying
    return inner2
a = knights2('XDD')
print(a())  #We are the knights who say: 'XDD'

lambda()

当想要传入一个小function作为使用时,却又不想定义出来,可以使用匿名函数。

def edit_story(words, func):
    for word in words:
        print(func(word))
stairs = ['thud', 'meow', 'thud', 'hiss']
def enliven(word):
    return word.capitalize() + '!'
# 原做法
edit_story(stairs, enliven)
print('-----')
# 匿名函数做法
edit_story(stairs, lambda word: word.capitalize() + '!')

Generators生成器

生成器是用来创建一个序列object,但是又不用需要事前把整个序列存入内存中,会随着每次执行而改变数值,每次循环生成器时,它会记录上一次调用的位置,并返回下一个值,这一点和普通的函数是不一样的,一般函數都不记录前一次调用用,而且都会在函数的第一行开始执行。內建的range()就是一种生成器。

# 自制range函数
def my_range(first=0, last=10, step=1):
    number = first
    while number < last:
        yield number
        number += step
ranger = my_range(1, 5)
for x in ranger:
    print(x)
print('------')
print(my_range)
for x in my_range(1, 5):
    print(x)

Namespace 与Scope 命名空间与作用域

在主程序main()中的变量称为全局变量,可以在函数中调用,但不能改变它。在函数内出现与全局变量相同名称的变量则是另一个不同的变量,则可以改变值。

animal = 'fruitbat'
def print_global():
    print('inside print_global:', animal)
print('可以在函数内调用全部变量。')
print_global()
def change_and_print_global():
#    print('inside change_and_print_global:', animal)
    animal = 'wombat'
print('但无法改变他,会出错。')
# 可以尝试取消注释试试
change_and_print_global()
def change_and_print_global():
    animal = 'wombat'
    print('inside change_and_print_global:', animal)
print('\n若要在函数内使用相同名称的变量,且需不同于全局变量,必须先赋值方可使用。')
change_and_print_global()
print('\n若是在函数内想改变全局变量则使用 global即可')
def change_and_print_global():
    global animal
    animal = 'wombat'
    print('inside change_and_print_global:', animal)
change_and_print_global()
print('\n外面的同时也会被改变', animal)

猜你喜欢

转载自blog.csdn.net/leon_lavie/article/details/82493980
今日推荐