Python学习手册(第13章)while和for循环

>>> # 判断y是否为质数
>>> y = 13
>>> x = y // 2
>>>
>>> while x > 1 :
...     if y%x == 0:
...             print(y,'has factor',x)
...             break
...     x -=1
... else:
...     print(y,'is prime')
...
13 is prime

嵌套for循环

items = ['aaa',111,(4,5),2.01]
tests = [(4,5),3.14]
for key in tests:
    for item in items:
        if item == key:
            print(key,"was found")
            break
    else:
        print(key,"not found!")
"""
结果如下:
(4, 5) was found
3.14 not found!
"""

items = ['aaa',111,(4,5),2.01]
tests = [(4,5),3.14]
for key in tests:
    if key in items:
        print(key,"was found")
    else:
        print(key,"not found!")
"""
结果如下:
(4, 5) was found
3.14 not found!
"""

seq1 = "spam"
seq2 = "scam"
res = []
for x in seq1:
    if x in seq2:
        res.append(x)
print(res)
"""
结果如下:
['s', 'a', 'm']
"""

#文件扫描
file = open("log.txt",'r')
print(file.read())    # 加载全部文件内容

file = open('log.txt')
while True:
    char = file.read(1)  #读取一个字符
    if not char:break
    print(char)

for char in open('log.txt').read():
    print(char)      



file = open('log.txt')
while True:
    line = file.readlines()
    if not line:break
    print(line)

for line in open('log.txt').readlines():
    print(line,end=" ")

for line in open('log.txt'):
    print(line,end=" ")
L = [1,2,3,4,5]
for i in range(len(L)):
    L[i]+=1
print(L)

L1 = [1,2,3,4,5]
L2 = [6,7,8,9,10]
print(zip(L1,L2))
print(list(zip(L1,L2)))
for (x,y) in zip(L1,L2):print(x,y,'--',x+y)

print(list(map(ord,'spam')))

S = 'spam'
for (offset,item) in enumerate(S):
    print(item,'appears at offset',offset)

E = enumerate(S)
print(E)
print(next(E))
print(next(E))
print(next(E))
print(next(E))
'''
结果如下:
[2, 3, 4, 5, 6]
<zip object at 0x000001AFFF2F1288>
[(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]
1 6 -- 7
2 7 -- 9
3 8 -- 11
4 9 -- 13
5 10 -- 15
[115, 112, 97, 109]
s appears at offset 0
p appears at offset 1
a appears at offset 2
m appears at offset 3

<enumerate object at 0x0000028639805948>
(0, 's')
(1, 'p')
(2, 'a')
(3, 'm')
'''

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值