for、while循环的洪荒之力

在python里,如果说print语句是用得最多的话,那么,要我说,除了for语句,谁都不敢认老二。

下面,让我们来看看for语句能搞出什么花样

1. 计时(无限次数)

说到计时,我们先来试下显示当前时间

 1 # coding: utf-8
 2 
 3 import time
 4 import os
 5 
 6 while True:
 7     # 注意 " 时:分:秒 " 三个字母必须要大写
 8     print time.strftime("%H:%M:%S")  
 9     time.sleep(1)
10     # 清屏命令, 也可用clear, 清除控制台powershell或者命令行窗口输入和显示的数据
11     os.system('cls')   
展开

利用清屏命令,动态显示时间信息。

补充一下:

import time

print time.ctime()

也可显示当前时间,当然格式就改不了了!—8/21/2016

--------------------------------------------------------------------------------------------------------

 1 # coding: utf-8
 2  
 3 import time
 4 import os
 5  
 6 s = 0           # s:(second) 设置秒
 7 m = 0           # m:(minute) 设置分 
 8 n = 1           # n等下在暂停计时后进入新的分钟时发挥作用
 9 while True:     
10      try:
11          for s in range(n, 61):     # s从1到60, 循环共执行60次
12          
13              if s < 10 and m < 10:        
14                  print "0%d:0%d" % (m, s)
15              elif s < 10 and m >=10:
16                  print "%d:0%d" % (m, s)
17              elif 10 <= s < 60 and m < 10:
18                  print "0%d:%d" % (m, s)
19              elif 10 <= s < 60 and m >= 10:
20                  print "%d:%d" % (m, s)
21              elif s == 60 and m < 10:
22                  m += 1
23                  print "0%d:00" % m
24              elif s == 60 and m >= 10:
25                  m += 1
26                  print "%d:00" % m
27              # 设置每隔1秒打印一次信息
28              time.sleep(1)            
29              # 清屏, (也可用'clear'), 清除当前在显示的数据之外的所有信息 
30              os.system("cls")      
31          # 当暂停计时后再继续时, for循环从n = s(当前秒数)开始,但下一次还是从n = s开始, 所以n = 1是为了从第1秒开始
32          n = 1
33      # 异常类型:'键盘中断', 用产生该异常的快捷键 "Ctrl + C" 作为暂停键
34      except KeyboardInterrupt:   
35          try:
36              # 由于暂停计时, 等下的分和秒都不能变, 所以要改变for语句的起始n值
37              n = s          
38              print "Pause..."
39              raw_input("")
40          # 异常类型(End of file Error):"结束文件时出错", 输入时按 "Ctrl + Z" 作为重新计时的快捷键
41          except EOFError:        
42              s = 0
43              m = 0
44              print u"重新计时" 
点我

主要利用whie循环和for循环,加上异常处理(系统本身自带的Ctrl+C退出键能引发KeyboardInterrupt异常)

中断按Ctrl + C,只能按1次,继续按回车键。清零在中断之后按Ctrl + Z,也只能按1次,回车再继续。重复

以上步骤即可重复计时。

---------------------------------------------------------------------------------------------------------

2. 有序筛选出列表中重复的元素

 1 # coding: utf-8
 2 
 3 txt = "Let it go! Let it go!"
 4 repeated_list = txt. split()      # 按空格划分单词,加入到列表中
 5 new_list = []
 6 
 7 for word in repeated_list:
 8     pop = repeated_list.pop(0)    # 逐个弹出列表第1个元素
 9     if pop in repeated_list:      # 弹出的元素与列表剩余的元素作对比,若列表还有重复的元素,用replace替换掉
10         new_list.append(pop)      # 弹出的元素加入到空列表中
11         
12 print new_list
显示

主要利用逐个弹出重复列表中的元素再与剩余元素作对比从而判断是否重复,若重复,刚添加到新的空列表中

----------------------------------------------------------------------------------------------------------

3. 删除字符串中的数字

 1 # coding: utf-8
 2 
 3 txt = "You can call 110 or 120 to ask for help!"
 4 
 5 n = 0
 6 
 7 while n <10:                              # 数字无非就是0~9,当n=10时,条件不成立,终止while循环
 8     for i in txt:                         # str(n)把int整数型的数字变为str字符型
 9         if i == str(n):                   # 注意,n是int整数型数字,'==' 两边字符类型要相同
10            txt =  txt.replace(str(n), "") # 如果if成立,就用replace(),把和n相同的部分替换掉
11     n +=1
12 
13 print txt
代码

 ---------------------------------------------------------------------------------------------------------

4. 删除空行

这一题有个坑,暂时解释不了,就是如果是用

for each in txt:

    txt.remove("")

等下总是不能把空白元素删除干净

(只能删掉列表元素个数的一半或者一半加0.5)

 1 # coding: utf-8
 2 
 3 txt = u"""
 4 行千里路,读万卷书,布衣亦可傲王侯!
 5 
 6 海到无边天岸,山登绝顶我为峰!
 7 
 8 百年的孤独,千夜的颂歌!
 9 
10 
11 """
12 
13 txt = txt.split("\n")
14 
15 while "" in txt:
16     txt.remove("")
17 
18 for each in txt:
19     print each
有坑

posted @ 2016-08-04 20:47  坏小孩D_R  阅读(235)  评论(0编辑  收藏  举报