>>> # 判断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')
'''