python 之 循环语句

python提供了for循环和while循环以及嵌套循环(在python中没有do..while循环)

while 循环语法:

while 判断条件:
   执行语句......

实际案例:

numbers=[12,37,5,42,8,3]
even=[];
odd=[];
while len(numbers)>0:
    number=numbers.pop();
    if(number%2==0):
        even.append(number)
    else:
        odd.append(number);

结果:
  numbers=[];
  even=[8,42,12];
  odd=[3,5,37]
    

循环使用else语句 实例:

count = 0
while count < 5:
   print count, " is  less than 5"
   count = count + 1
else:
   print count, " is not less than 5“

结果;
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5
 

做一些简单的小游戏练习

猜大小的游戏

import random
s = int(random.uniform(1,10))
#print(s)
m = int(input('输入整数:'))
while m != s:
    if m > s:
        print('大了')
        m = int(input('输入整数:'))
    if m < s:
        print('小了')
        m = int(input('输入整数:'))
    if m == s:
        print('OK')
        break;

猜拳小游戏

import random
while 1:
    s = int(random.randint(1, 3))
    if s == 1:
        ind = "石头"
    elif s == 2:
        ind = "剪子"
    elif s == 3:
        ind = ""
    m = raw_input('输入 石头、剪子、布,输入"end"结束游戏:')
    blist = ['石头', "剪子", ""]
    if (m not in blist) and (m != 'end'):
        print "输入错误,请重新输入!"
    elif (m not in blist) and (m == 'end'):
        print "\n游戏退出中..."
        break
    elif m == ind :
        print "电脑出了: " + ind + ",平局!"
    elif (m == '石头' and ind =='剪子') or (m == '剪子' and ind =='') or (m == '' and ind =='石头'):
        print "电脑出了: " + ind +",你赢了!"
    elif (m == '石头' and ind =='') or (m == '剪子' and ind =='石头') or (m == '' and ind =='剪子'):
        print "电脑出了: " + ind +",你输了!"

摇筛子游戏

import random
import sys
import time

result = []
while True:
    result.append(int(random.uniform(1,7)))
    result.append(int(random.uniform(1,7)))
    result.append(int(random.uniform(1,7)))
    print result
    count = 0
    index = 2
    pointStr = ""
    while index >= 0:
        currPoint = result[index]
        count += currPoint
        index -= 1
        pointStr += " "
        pointStr += str(currPoint)
    if count <= 11:
        sys.stdout.write(pointStr + " -> " + "" + "\n")
        time.sleep( 1 )   # 睡眠一秒
    else:
        sys.stdout.write(pointStr + " -> " + "" + "\n")
        time.sleep( 1 )   # 睡眠一秒
    result = []

python for 循环可以遍历任何序列的项目,如一个列表或者一个字符串。

for循环的语法:

for iterating_var in sequence
  statements(s)

简单案例

for letter in 'Python':     # 第一个实例
   print '当前字母 :', letter
 
fruits = ['banana', 'apple',  'mango']
for fruit in fruits:        # 第二个实例
   print '当前水果 :', fruit

通过序列索引迭代:将列表编程序列索引

fruits=["banana","apple","mango"]
for index in range(len(fruits)):
    print(index)
    print("当前水果:"+fruits[index])

循环使用else语句

在python中,for...else 表示这样的意思,for中的语句和普通的没有区别,else中的语句会在循环正常执行完(即for不是通过break跳出而中断的) 的情况下执行,while...else也是一样

for num in range(10,20):
    for i in range(2,num):
        if(num%i)==0:
           j=num/i
           print("%d 等于 %d * %d" %(num,i,j))
           break
    else:
       print(str(num) +“是一个质数”)

使用内置enumerate 函数进行遍历  案例:

sequence=[12,34,34,23,45,76,89]
for i ,j in enumerate(sequence):
    print(i,j)

 

posted @ 2017-07-26 22:34  zmztyas  阅读(747)  评论(0编辑  收藏  举报