x = 'spam'
while x:
print(x, end=' ')
x = x[1:] # spam pam am m
def func():
pass
def func():
...
x = 10
while x:
x = x-1
if x % 2 ==0:continue
print(x, end=' ') # 9 7 5 3 1
#判断是不是质数
#x = y //2
#while x > 1:
#else:
for i in 'spam':
print(i, end='') # spam
sum = 0
for i in [1, 2, 3]:
sum += i
print(sum) # 6
sum = 1
for i in [1, 2, 3, 4]:sum *= i
print(sum) # 24
#for循环中的元组赋值和解包
for (i, j) in ((1, 2),(3, 4)): # 1 2
print(i, j) # 3 4
d = {'a':1,'b':2,'c':3} # 'a' 1
for i in d: # 'b' 2
print(i, d[i]) # 'c' 3
for (i, j) in d.items(): # 'a' 1
print(i, j) # 'b' 2
t = [(1, 2), (3, 4), (5, 6)]
for both in t: # 1, 2
a, b = both # 3, 4
print(a, b) # 5, 6
for ((a, b), c) in [((1, 2),3), ((4, 5), 6)]: # 1 2 3
print(a, b, c) # 4 5 6
for ((a, b), c) in [((1, 2),3), ('xy', 6)]: # 1 2 3
print(a, b, c) # x y 6
a, *b, c = (1, 2, 3, 4)
print(a, b, c) # 1 [2, 3] 4
for (a, *b, c) in [(1, 2, 3, 4), (5, 6, 7, 8)]:
print(a, b, c)
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')
for key in tests:
if key in items:
print(key, 'was found')
else:
print(key, 'not found')
#编写循环技巧
#灵活使用range, range在py3 中是迭代器
print(range(5)) # range(0, 5)
print(list(range(5))) # [0, 1, 2, 3, 4]
l = [1, 2, 3, 4, 5]
for x in l:
x += 1
print(l) # [1, 2, 3, 4, 5]
#每次经过循环时, x会引用从列表中取出来的下一个整数。
#也就是2, 但是没更新1所来自的那个列表
l = [1, 2, 3, 4, 5]
for i in range(len(l)):
l[i] += 1
print(l) # [2, 3, 4, 5, 6]
print([i+1 for i in [1, 2, 3, 4, 5]])
#并行遍历,zip 和 map
#元素配成对
l1 = [1, 2, 3, 4]
l2 = [5, 6, 7, 8]
print(zip(l1, l2)) #
print(list(zip(l1, l2))) # [(1, 5), (2, 6), (3, 7), (4, 8)]
for (x, y) in zip(l1, l2):
print(x, y, '-->', x+y)
s1 = 'abc'
s2 = 'xyz123'
#print(list(map(None, s1, s2)))
print(list(map(ord, 'spam'))) # [115, 112, 97, 109]
#用zip构造字典
k = ['spam', 'eggs', 'toast']
v = [1, 3, 5]
print(list(zip(k, v)))
d = {}
for i, j in zip(k, v):
d[i] = j
print(d)
k = ['spam', 'eggs', 'toast']
v = [1, 3, 5]
d = dict(zip(k, v))
print(d)
{'spam': 1, 'eggs': 3, 'toast': 5}
s = 'spam'
for i, j in enumerate(s):
print(i,'-->',j)
e = enumerate('spam')
print(e)
#这个对象有个next方法,可以在每次迭代的时候返回一个元组,
#可以在for中循环通过元组赋值将运算解包
print(next(e))
print(next(e))
print(next(e))
另外有需要云服务器可以了解下创新互联cdcxhl.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。