本文主要是介绍Python百例-21~30,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
21-while-break
break是结束循环,break之后、循环体内代码不再执行。
while True:yn = input('Continue(y/n): ')if yn in ['n', 'N']:breakprint('running...')
22-while-continue
计算100以内偶数之和。
continue是跳过本次循环剩余部分,回到循环条件处。
sum100 = 0
counter = 0while counter < 100:counter += 1# if counter % 2:if counter % 2 == 1:continuesum100 += counterprint(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 = 0for
这篇关于Python百例-21~30的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!