python语句与语法(赋值、if else、while、break、contine、pass、for、迭代器、文档)

1、赋值

1.1、变量在首次赋值时创建 ,在被引用前必须赋值 

x,y ='china','beijing'
print(x,y)
x = y ='china'
print(x,y)

x,y ='SL'
print(x,y)

((x,y),z) = 'SL','xy' #特殊用法
print(x,y,z)

x = 1
y = 2
x,y =y,x  #常用用法
print(x,y)


输出:
china beijing
china china
S L
S L xy
2 1

1.2、print与重定向

import sys
previous = sys.stdout
sys.stdout = open('temp.txt','a')
print('welcome')

sys.stdout.close()
sys.stdout = previous
print('welcome')

输出:
在文件temp.txt里显示welcome
welcome

1.3、真值判断

None, False, 0, 0.0, [], (), {} 都是False  其他都为True

or 找到第一个真值则结束,短路操作,如果没有真值,则返回最后的值 

and 如果是真会往右找,直到找到的为flase为止,如果没有,则返回最后的值 

x = 2 or 3
print(x)

x = 2 and 3
print(x)

x = None or 2
print(x)

x = [] or ()
print(x)

x = 3 and []
print(x)


输出:
2
3
2
()
[]

2、if else

2.1、基本用法说明

依次执行每一个测试,只要一个满足就执行对应的语句,执行完后结束

x = 'china'
if x == 'us':
    print('us')
elif x == 'china':
    print('india')
elif x =='china':
    print('china')
else:
    print('no match')

输出:
india

2.2、其他的表示

3、while

4、break、contine、pass

break 跳出最近的循环

contine 跳出此次循环,继续下一次

pass 空位占位符,什么事情也不做

i = 0
while True:
    if i > 4:
        break
    i += 1
    print(i, end=',')

print('\n')

j = 0
while j < 10:
    j += 1
    if j < 6:
        print(j, end=',')
    else:
        continue
        print('***')

print('\n')

k = 0
while k < 10:
    k += 1
    if k < 6:
        print(k, end=',')
    else:
        pass
        print('***')

输出:
1,2,3,4,5,

1,2,3,4,5,

1,2,3,4,5,***
***
***
***
***

5、for

可以遍历任何有序的序列对象内的元素 ,字符串、列表、元组、其他可迭代内置对象 

for x in {1:'key1',2:'key2'}:
    print(x)

for x in {1:'key1',2:'key2'}.items():
    print(x)

输出:
1
2
(1, 'key1')
(2, 'key2')
for i in range(1,10,2): # 起始 结尾 步长
    print(i)

输出:
1
3
5
7
9

6、迭代器

6.1、类型介绍

内置可迭代对象:list 、 tuple 、 dict 、 set 、 str 等

可以使用 isinstance() 判断一个对象是否是 Iterable对象

import collections
print(isinstance([], collections.Iterable))

输出:
True

参考:https://www.cnblogs.com/python-road/p/10504474.html

凡是可作用于 for 循环的对象都是 Iterable 类型;

凡是可作用于 next() 函数的对象都是 Iterator 类型

集合数据类型如 list 、 dict 、 str 等是 Iterable 但不是 Iterator ,不过可以通过 iter() 函数获得一个 Iterator 对象

from  collections import Iterable
a=[1,2,4,6,8,6,10]
a=iter(a)
print(next(a))
print(next(a))
print(next(a))

输出:
1
2
4

 

迭代器方法:

6.2、range

for i in range(5):
    print(i,end=',')

输出:
0,1,2,3,4,

6.3、map 映射

map()会根据提供的函数对指定序列做映射。

参考:https://www.runoob.com/python/python-func-map.html

def square(x):
    return x ** 2

a = map(square,[1,2,3,4,5])
print(list(a))

输出:
[1, 4, 9, 16, 25]

6.3、enumrate 枚举

for i in enumerate(range(5,10)):
    print(i,end=',')

for index,value in enumerate(range(5,10)):
    print('index=%d => %d' %(index,value))


输出:
(0, 5),(1, 6),(2, 7),(3, 8),(4, 9),
index=0 => 5
index=1 => 6
index=2 => 7
index=3 => 8
index=4 => 9
 

6.4、sorted  排序

更加详细请参考:https://www.runoob.com/python/python-func-sorted.html

D = [3,4,6,3,0,7]
D1 = sorted(D)
print(D1)


输出:
[0, 3, 3, 4, 6, 7]

6.5、sum、min、max

D = [3,4,5,6,7]
print(sum(D))
print(min(D))
print(max(D))


输出:
25
3
7

6.6、zip

zip()函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。

参考:https://www.runoob.com/python/python-func-zip.html

           https://www.cnblogs.com/wushuaishuai/p/7766470.html

zip 与zip(*)相当于压缩和解压缩的过程

a = [1,2,3,4,5]
c = [4,5,6,7]
b = list(zip(a,c))
print(b)
print(type(b))
d = zip(*b) #b的类型要是list,不是zip
print(list(d))

输出:
[(1, 4), (2, 5), (3, 6), (4, 7)]
<class 'list'>
[(1, 2, 3, 4), (4, 5, 6, 7)]


a = [1,2,3,4,5]
c = [4,5,6,7]
b = zip(a,c)
d = zip(*b)
print(list(d))

输出:
[(1, 2, 3, 4), (4, 5, 6, 7)]

6.7、列表解析

D = [3,4,5,6,7]
D1 = []
for item in D:
    D1.append(item *2)
print(D1)

D1 = [item *2 for item in D] #注意这种用法
print(D1)


输出:
[6, 8, 10, 12, 14]
[6, 8, 10, 12, 14]

6.8、文件迭代器

fp = open('temp.txt')
print(fp.readline())  #特别注意:每一行后还有一个换行符\n
print('----')
print(fp.readline())
print('----')
print(fp.readline())
print('----')

fp = open('temp.txt')
for line in fp:
    print(line)


输出:
ni

----
hao

----
ma

----
ni

hao

ma

7、文档

7.1、注释

7.2、dir函数

查看对象,模块等属性

a = []
print(dir(a))

7.3、文档字符串 __doc__

def cluster():
    """
    cluster is a method to get many nodes information
    """
    pass
print(cluster.__doc__)


输出:

    cluster is a method to get many nodes information
    

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值