for循环和while循环

一、循环、遍历、迭代

 python里面循环有两种:while和for循环

1.while

 count = 8 #计数器
 while count<10:
 print('你好!')
 count=count+1
 #循环体
 else:
 print('再见。')

2.break,退出循环,break只能在循环里面用,如果在循环里面遇到,那么立即退出循环

count = 0 # 计数器

while count < 10:

print('你好!')
count = count + 1
if count==5:
break

3.continue的用法,continue的作用是退出本次循环
 count = 0 # 计数器
 while count < 10:
 count = count + 1
 if count==5:
 continue
 print('你好!'%count)

4.for循环,里面的break
 for i in range(10):
 print('你好,%s'%i)
 if i==6:
 break


5.for continue用法
 for i in range(10):
 if i==7:
 continue
 print('你好,%s'%i)

 

 6.for count in range(1,11):#顾头不顾尾
 print(count)
 else:
 print('over。。。')
 for循环对应的else,只有当for正常循环结束才会执行


7.import random
#随机数模块
sub_str=random.randint(1,101) #生成1-100的一个随机数
while 1:#while的意思就是,让它一直为真,也就是死循环,下面通过break来停止循环(非0即真,非空即真)
num=int(input('plase enter a num , 1-100:'))
if num>100 or num<1: #判断输入的数字是否在1-100之间
print('num error,plase enter 1-100.')
continue
else:
if num==sub_str: #如果猜对了,结束循环
print('You win. game over,the num is %d'%sub_str)#不懂这个的请看下面的第十四,字符串格式化输出
break
elif num < sub_str:#如果猜小了,就跳出本次循环,提示猜小了
print('The num is small,plase enter other num.')
continue
else:#就三种情况,大、小等于,前面两种是等于和小雨,那么else就是大于了,如果猜大了,就跳出本次循环,提示猜大了
print('The num is too big,plase enter other num.')
continue

8.引号

      里面有双引号的,外面用单引号,里面有双引号的外面用单引号;如果里面双引号单引号都有的话,就用三个引号''' ''';三个单引号还有批量注释的功能。
input()函数接收到的值,全部都是字符串类型的,如果要和int类型做比较的话,必须用int()把字符串强制转成int类型的,才能做比较。

9.运算

print(1/2)
print(1//2)#就是自动取整,不会四舍五入,直接把小数部分抹去

posted on 2017-05-17 23:21  国元  阅读(897)  评论(0编辑  收藏  举报

导航