趣学python第6章循环for
# -*- coding: utf-8 -*-
"""2018-1-23@author: linda"""
for x in range(0,5):
print('hello,world!')
=================== RESTART: C:\Python27\lianxi\2018123.py ===================
hello,world!
hello,world!
hello,world!
hello,world!
hello,world!
重复打印动作5次
range范围,数字从0开始到5之前的数字都执行for
从0 开始数数,数到5之前停下。
对于其中的每个数,都把值放到变量x中。
for x in range(0,5):
print('hello,world!%s'% x)
=================== RESTART: C:\Python27\lianxi\2018123.py ===================
hello,world!0
hello,world!1
hello,world!2
hello,world!3
hello,world!4
2.for循环中使用range或者list函数
# -*- coding: utf-8 -*-
"""2018-1-23@author: linda"""
list1 = ('cat','da','monkey',10,20)
list2 = (1,2,3,4,5,6,7)
print ("list1 :",list1)
print ("list2 :",list2)
list12= list1+list2
print (list12)
for i in range(0,len(list12)):
print (list12[i])
执行结果
=================== RESTART: C:\Python27\lianxi\2018123.py ===================
list1 : ('cat', 'da', 'monkey', 10, 20)
list2 : (1, 2, 3, 4, 5, 6, 7)
('cat', 'da', 'monkey', 10, 20, 1, 2, 3, 4, 5, 6, 7)
cat
da
monkey
10
20
1
2
3
4
5
6
7
>>> 1
for i in list12:
print (i)
for i in range(0,len(list12)):
这两段代码的执行结果是相同的。print (list12[i])
第一段代码,对于list12中的每个元素,把它的值放到变量i里,然后打印出来这个变量的值
第二段代码,对于0,到list12的长度-1,中的每一个数字,把数字的值给i,然后打印出列表的元素list12[i]
=================== RESTART: C:\Python27\lianxi\2018123.py ===================list = ['leg','book','good','better','let','money'] for x in list: print (x)
leg
book
good
better
let
money
列表可以很方便的用for来遍历。字符串中的字母也可以遍历
=================== RESTART: C:\Python27\lianxi\2018123.py ===================for letter in 'apple': print ('apple 中的字母有:',letter)
apple 中的字母有: a
apple 中的字母有: p
apple 中的字母有: p
apple 中的字母有: l
apple 中的字母有: e
=================== RESTART: C:\Python27\lianxi\2018123.py ===================animals =['cat','dog','monkey','kongque','daxiongmao','laohu'] for animal in animals: print ('动物有:',animal) print('----------------') for x in range(len(animals)): print ('动物有:',animals[x])
动物有: cat
动物有: dog
动物有: monkey
动物有: kongque
动物有: daxiongmao
动物有: laohu
----------------
动物有: cat
动物有: dog
动物有: monkey
动物有: kongque
动物有: daxiongmao
动物有: laohu
编写一段计算银行利息的代码# -*- coding: utf-8 -*- """2018-1-23@author: linda""" benjin = 10000.0 print ("benjin =10000,年息=3.3%") yuexi =3.3/100/12 yueli =0.0 li =0.0 for x in range(1,13): yueli =benjin*yuexi benjin =yueli+benjin li+= yueli print ("第%s个月的月利是%0.2f, 总利息是%0.2f" % (x,yueli,li))
>>>
=================== RESTART: C:\Python27\lianxi\2018123.py ===================
benjin =10000,年息=3.3%
第1个月的月利是27.50, 总利息是27.50
第2个月的月利是27.58, 总利息是55.08
第3个月的月利是27.65, 总利息是82.73
第4个月的月利是27.73, 总利息是110.45
第5个月的月利是27.80, 总利息是138.26
第6个月的月利是27.88, 总利息是166.14
第7个月的月利是27.96, 总利息是194.10
第8个月的月利是28.03, 总利息是222.13
第9个月的月利是28.11, 总利息是250.24
第10个月的月利是28.19, 总利息是278.43
第11个月的月利是28.27, 总利息是306.69
第12个月的月利是28.34, 总利息是335.04
>>> 结果还好吧。