21-while-break
break 是结束循环,break 之后、循环体内代码不再执行。
while True:
yn = input('Continue(y/n): ')
if yn in ['n', 'N']:
break
print('running...')
22-while-continue
计算 100 以内偶数之和。
continue 是跳过本次循环剩余部分,回到循环条件处。
sum100 = 0
counter = 0
while counter < 100:
counter += 1
# if counter % 2:
if counter % 2 == 1:
continue
sum100 += counter
print(sum100)
23-for 循环遍历数据对象
astr = 'hello'
alist = [10, 20, 30]
atuple = ('bob', 'tom', 'alice')
adict = {'name': 'john', 'age': 23}
for ch in astr:
print(ch)
for i in alist:
print(i)
for name in atuple:
print(name)
for key in adict:
print('%s: %s' % (key, adict[key]))
24-range 用法及数字累加
# range(10) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# >>> list(range(10))
# range(6, 11) # [6, 7, 8, 9, 10]
# range(1, 10, 2) # [1, 3, 5, 7, 9]
# range(10, 0, -1) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
sum100 = 0
for i in range(1, 101):
sum100 += i
print(sum100)
25-列表实现斐波那契数列
列表中先给定两个数字,后面的数字总是前两个数字之和。
fib = [0, 1]
for i in range(8):
fib.append(fib[-1] + fib[-2])
print(fib)
26-九九乘法表
for i in range(1, 10):
for j in range(1, i + 1):
print('%s*%s=%s' % (j, i, i * j), end=' ')
print()
# i=1 ->j: [1]
# i=2 ->j: [1,2]
# i=3 ->j: [1,2,3]
# 由用户指定相乘到多少
n = int(input('number: '))
for i in range(1, n + 1):
for j in range(1, i + 1):
print('%s*%s=%s' % (j, i