while循环

  while 条件:

    代码块

  条件为真时,执行代码块,如果不为真,就跳过while循环的代码块。

  break:直接跳出当前的循环while。

  while、else:当while不满足的时候会走else。当while不是正常退出(break就是非正常退出),不会走else,当while是正常退出的话,才会走else下面的模块。

 1 age_of_oldboy = 56
 2 count = 0
 3 while count<3:
 4     guess_age = int(input(">>>:"))
 5     if age_of_oldboy == guess_age:
 6         print("yes,you got it")
       break
7 elif age_of_oldboy > guess_age: 8 print("think bigger!") 9 else: 10 print("think smaller!") 11 count+=1 12 else: 13 print("you try more")

  while循环版本优化

1 for i in range(10):
2     print(i)

  i:是临时变量

  range:其实是一个迭代器,但是这里大家可以暂时理解为【0,1,2,3,4,5,6,7,8,9】,每循环一次,就是将数组里面的值赋值给i。

  如果我们想隔一个值打印怎么办?判断是否可以被2整除吗?NO,太LOW

  

for i in range(0,10,2):
    print(i)

  从0开始循环,2是步长,隔2个打印。

  下面是优化代码:

 1 age_of_oldboy = 56
 2 count = 0
 3 while count<3:
 4     guess_age = int(input(">>>:"))
 5     if age_of_oldboy == guess_age:
 6         print("yes,you got it")
 7         break
 8     elif age_of_oldboy > guess_age:
 9         print("think bigger!")
10     else:
11         print("think smaller!")
12     count+=1
13     if count==3:
14         guess_confirm = input("are you going on....")
15         if guess_confirm!='n':
16             count = 0
17 else:
18     print("you try more")

  for , else 与while ,else 一样只有当程序正常退出的时候,我们才执行else里面的代码,但是当break非正常退出时,不会执行else下面代码的。

 1 age_of_oldboy = 56
 2 count = 0
 3 for i in range(3):
 4     guess_age = int(input(">>>:"))
 5     if age_of_oldboy == guess_age:
 6         print("yes,you got it")
 7         break
 8     elif age_of_oldboy > guess_age:
 9         print("think bigger!")
10     else:
11         print("think smaller!")
12 else:
13     print("you try more")

 continue:结束本次循环,直接跳到下次循环

 break:结束当前循环

 1 '''
 2 for i in range(10):
 3     if i < 5:
 4         print(i)
 5     else:
 6         continue
 7     print("hehe")
 8 
 9 '''
10 for i in range(10):
11     print("-----------------",i)
12     for i in range(10):
13         print(i)
14         if i >5:
15             break

 

posted on 2018-04-04 15:32  Linux的爱好者  阅读(161)  评论(0编辑  收藏  举报