Python学习(3)while语句、for语句、len()函数、insert()函数
while语句
Python 编程中 while 语句用于循环执行程序,执行语句可以是单个语句或语句块。判断条件可以是任何表达式,任何非零、或非空(null)的值均为true。当判断条件假false时,循环结束。
#Python while语句 count=0; while count<10: print("The count is:"+str(count)) count+=1 print("Good bye!")
输出结果:
The count is:0 The count is:1 The count is:2 The count is:3 The count is:4 The count is:5 The count is:6 The count is:7 The count is:8 The count is:9 Good bye!
for语句
Python 中的for语句和 C#或 java中的略有不同,通常的循环可能会依据一个等差数值步进过程,或由用户来定义迭代步骤和中止条件,Python 的 for语句依据任意序列(链表或字符串)中的子项,按它们在序列中的顺序来进行迭代:
#python中for循环 words=['cat', 'window', 'defenestrate'] for w in words: print(w,len(w))
输出结果:
cat 3 window 6 defenestrate 12
len()函数
Python len() 方法返回对象(字符、列表、元组等)长度或项目个数。
#python len()函数 s="runoob" print("字符串长度"+str(len(s))) l=[1,2,3,4,5] print("数组长度"+str(len(l)))
输出结果:
字符串长度6
数组长度5
insert()函数
insert() 函数用于将指定对象插入列表的指定位置。
#Python insert()函数 array=["123", 'xyz', 'zara', 'abcgug'] print(array) for item in array[:]: if len(item) > 4: array.insert(0,item) print(array)
输出:
['123', 'xyz', 'zara', 'abcgug'] ['abcgug', '123', 'xyz', 'zara', 'abcgug']

浙公网安备 33010602011771号