六个方面诠释Python的代码结构
这篇文章主要介绍了六个方面诠释Python的代码结构,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
一、注释
使用#或三引号注释。
二、连接
使用反斜线 连接。
立即学习“Python免费学习笔记(深入)”;
>>> alphabet = 'abcdefg' + ... 'hijklmnop' + ... 'qrstuv' + ... 'wxyz'
在Python表达式占行很多的前提下,行连接符也是必须的。
>>> 1 + 2 + ... 36
三、if、elif和else
常见的运算符:
算数运算符:
比较运算符:
赋值运算符:
逻辑运算符:
成员运算符:
身份运算符 :
位运算符:
*按位取反运算规则(按位取反再加1) 详解http://blog.csdn.net/wenxinwukui234/article/details/42119265
运算符优先级:
input()输入的是字符串;
字符串和整数型之间的转换————int() str()
短路原则:
and 第一个为假时就不去判断后面的了,直接为false;
or 第一个为真就不去判断第二个了,直接为true。
会被认为是False的情况:
布尔 | False |
null类型 | None |
整型 | 0 |
浮点型 | 0.0 |
空字符串 | '' |
空列表 | [] |
空元组 | () |
空字典 | {} |
空集合 | set() |
四、使用while进行循环
使用if、elif和else条件判断的例子是自顶向下执行的,但是有时候我们需要重复一些操作——循环。
>>> count = 1>>> while count <p><span style="font-size:12pt;">使用break跳出循环</span></p><pre class="brush:php;toolbar:false">>>> while True:... stuff = input("String to capitalize [type q to quit]:")... if stuff == 'q':... break... print(stuff.capitalize())...String to capitalize [type q to quit]:testTestString to capitalize [type q to quit]:darren chenDarren chenString to capitalize [type q to quit]:q
使用continue调到循环开始
while True: value = input('Integer ,please [q to quit]:') if value == 'q': break number = int(value) if number % 2 == 0: continue print(number,'squared is',number*number) Integer ,please [q to quit]:>? 11 squared is 1Integer ,please [q to quit]:>? 2Integer ,please [q to quit]:>? 33 squared is 9Integer ,please [q to quit]:>? 55 squared is 25Integer ,please [q to quit]:>? 6Integer ,please [q to quit]:>? q
循环外使用else:
当while循环正常结束(没有使用break跳出),程序将进入到可选的else段 。
numbers = [1,3,5]position = 0while position <p style="font-family:Monaco;font-size:9pt;color:rgb(51,51,51);"><strong><span style="font-size:14pt;"><br></span></strong><br></p><p><strong><span style="font-size:14pt;">五、使用for迭代</span></strong></p><p>表、字符串、元组、字典、集合等都是Python中可迭代的对象。元组或列表在一次迭代过程中产生一项,而字符串迭代会产生一个字符。<br></p><pre class="brush:php;toolbar:false">word = 'Darren Chen'for i in word: print(i) DarrenChen
对一个字典(或字典的key()函数)迭代将返回字典中的键
home = {"man":'chenda','woman':'lvpeipei'}for i in home: print(i) manwoman
想对值迭代,可以使用字典的values()
>>> for value in accusation. values(): ... print( value) ... ballroom lead pipe
同while一样,可以使用break跳出循环,使用continue调到循环开始。
循环外使用else:
>>> cheeses = [] >>> for cheese in cheeses: ... print(' This shop has some lovely', cheese) ... break ... else: # 没有 break 表示 没有 找到 奶酪 ... print(' This is not much of a cheese shop, is it?') ... This is not much of a cheese shop, is it?
使用zip()对多个序列进行并行迭代:
>>> days = ['Monday', 'Tuesday', 'Wednesday'] >>> fruits = ['banana', 'orange', 'peach'] >>> drinks = ['coffee', 'tea', 'beer'] >>> desserts = ['tiramisu', 'ice cream', 'pie', 'pudding'] >>> 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()函数配对两个元组。函数的返回值既不是元组也不是列表,而是一个整合在一起的可迭代变量:
>>> english = 'Monday', 'Tuesday', 'Wednesday' >>> french = 'Lundi', 'Mardi', 'Mercredi'>>> list( zip( english, french) ) [('Monday', 'Lundi'), ('Tuesday', 'Mardi'), ('Wednesday', 'Mercredi')]#配合dict()函数和zip()函数的返回值就可以得到一本微型的词典:>>> dict( zip( english, french) ) {'Monday': 'Lundi', 'Tuesday': 'Mardi', 'Wednesday': 'Mercredi'}
使用range()生成自然数序列
>>> for x in range( 0, 3): ... print( x) ... 0 1 2>>> list( range( 0, 11, 2) ) [0, 2, 4, 6, 8, 10]
六、推导式
推导式是从一个或者多个迭代器快速简介地创建数据结构的一种方法。
列表推导式
>>> number_ list = list( range( 1, 6)) >>> number_ list [1, 2, 3, 4, 5]>>> number_ list = [number for number in range( 1, 6)] >>> number_ list [1, 2, 3, 4, 5]>>> number_ list = [number- 1 for number in range( 1, 6)] >>> number_ list [0, 1, 2, 3, 4]>>> a_ list = [number for number in range( 1, 6) if number % 2 == 1] >>> a_ list[1,3,5]#嵌套循环>>> rows = range( 1, 4) >>> cols = range( 1, 3) >>> cells = [(row, col) for row in rows for col in cols] >>> for cell in cells: ... print( cell) ... (1, 1) (1, 2) (2, 1) (2, 2) (3, 1) (3, 2)
字典推导式
{ key_ expression : value_ expression for expression in iterable }>>> word = 'letters' >>> letter_ counts = {letter: word. count( letter) for letter in set( word)} >>> letter_ counts {'t': 2, 'l': 1, 'e': 2, 'r': 1, 's': 1}
集合推导式
>>> a_ set = {number for number in range( 1, 6) if number % 3 == 1} >>> a_ set {1, 4}
生成器推导式——元组是没有推导式的,其实,圆括号之间的是生成器推导式,它返回的是一个生成器对象。
>>> number_ thing = (number for number in range( 1, 6))>>> type( number_ thing) #可以直接对生成器对象进行迭代>>> for number in number_ thing: ... print( number) ... 1 2 3 4 5
#通过对一个生成器的推导式调用list()函数,使它类似于列表推导式
>>> number_ list = list( number_ thing) >>> number_ list [1, 2, 3, 4, 5] 一个生成器只能运行一
次。列表、集合、字符串和字典都存储在内存中,但是生成器仅在运行中产生值,不会被存下来,所以不能重新使用或者备份一个生成器。
如果想再一次迭代此生成器,会发现它被擦除了:
>>> try_ again = list( number_ thing) >>> try_ again [ ]