程序的三大流程
在程序开发中,一共有三种流程方式:
顺序:从上向下,顺序执行代码
分支:根据条件判断,决定执行代码的分支
循环:让特定代码重复执行(解决程序员重复工作)
while循环语句
while 循环的基本使用
循环的作用就是让指定的代码重复的执行
while 循环最常用的应用场景就是让执行的代码按照指定的次数重复执行
while 语句的基本语法
初始条件设置 – 通常是重复执行的 计数器 (eg:i=1)
while 条件(判断 计数器 是否达到目标 目标次数):
条件满足时,做的事情 1
条件满足时,做的事情 2
条件满足时,做的事情 3
条件满足时,做的事情 4
………
处理条件(计数器 +1)
while 语句及缩进部分是一个完整的代码块
while_1.py
# _*_ coding:utf-8 _*_
"""
file:while_1.py
date:2018-07-19 1:04 PM
author:wwy
desc:
"""
# 定义一个整数变量,记录循环次数
i = 0
# 开始循环
while i<= 10:
# 希望在循环内执行的代码
print 'hello python'
# 处理循环计数
i += 1
print '循环结束, i = %d' %i
运行结果:
while_2.py
# _*_ coding:utf-8 _*_
"""
file:while_2.py
date:2018-07-19 1:12 PM
author:wwy
desc:
"""
# 计算0~100之间数字的求和
i = 0
result = 0
while i<= 100:
result += i
i += 1
print '0~100之间数字之和为 %d ' %result
运行结果:
while_3.py
# _*_ coding:utf-8 _*_
"""
file:while_03.py
date:2018-07-19 1:14 PM
author:wwy
desc:
计算0~100以内的偶数和与奇数和
"""
# 计算0~100之间的偶数和
i = 0
result = 0
while i<= 100:
if i % 2 == 0:
result += i
i += 1
print '偶数和是:%d' %result
# 计算0~100之间的奇数和
i = 0
result = 0
while i<= 100:
if i % 2 != 0:
result += i
i += 1
print '奇数和是:%d' %result
运行结果:
break与continue
break 和 continue
break 和 continue 是专门在循环中使用的关键字
break 某一条满足时,退出循环,不再执行后续重复的代码
continue 某一条满足时,不执行后续重复的代码,其他条件统统要执行
break 和 continue 只针对当前所在循环有效
break.py
# _*_ coding:utf-8 _*_
"""
file:break.py
date:2018-07-19 1:20 PM
author:wwy
desc:
"""
i = 0
while i < 10:
if i == 3:
# 满足某一条件的时候
# 退出循环,不再执行后续的重复的代码
break
print i
i +=1
print 'over'
运行结果:
continue.py
# _*_ coding:utf-8 _*_
"""
file:continue.py
date:2018-07-19 1:22 PM
author:wwy
desc:
"""
i = 0
while i <= 10:
i += 1
if i == 3:
continue
# continue不执行满足条件的循环
# 跳出该次循环后继续执行后面的条件
print i
运行结果:
while嵌套.py
# _*_ coding:utf-8 _*_
"""
file:while嵌套.py
date:2018-07-19 1:26 PM
author:wwy
desc:
*
* *
* * *
* * * *
* * * * *
"""
row = 1
while row <= 5:
col = 1
while col <= row:
col += 1
print '*', # 没有“,”数行排列
print '' # 添加换行
row += 1
运行结果:
使用while循环实现输出2-3+4-5…+100
嵌套循环——方法一.py
# _*_ coding:utf-8 _*_
"""
file:嵌套循环——方法一.py
date:2018-07-19 1:29 PM
author:wwy
desc:
使用while循环实现输出2-3+4-5...+100
"""
i = 2
O_result = 0
J_result = 0
result = 0
while i<= 100:
if i % 2 == 0:
O_result += i
else:
J_result += i
i += 1
result = O_result - J_result
print result
运行结果:
嵌套循环——方法二.py
# _*_ coding:utf-8 _*_
"""
file:嵌套循环——方法二.py
date:2018-07-19 1:31 PM
author:wwy
desc:
使用while循环实现输出2-3+4-5...+100
"""
i = 2
b = 0
while i <=100:
if i % 2 == 0:
b += i
else:
b -= i
i += 1
print b
运行结果:
转义字符
字符串的转义字符
\t:在控制台输出一个制表符,协助在输出文本时垂直方向保持对齐
\n:在控制台输出一个换行符
制表符的功能是在不使用表格的情况下在垂直方向按列对齐文本
转义字符.py
# _*_ coding:utf-8 _*_
"""
file:转义字符.py
date:2018-07-19 1:47 PM
author:wwy
desc:
"""
print '1 2 3'
print '10 20 30'
print '1\t2\t3'
print '10\t20\t30'
print 'hello python'
print 'hello\npython'
print "hello\"python"
print 'hello\"python'
运行结果:
乘法表.py
# _*_ coding:utf-8 _*_
"""
file:乘法表.py
date:2018-07-19 1:43 PM
author:wwy
desc:
"""
row = 1
while row <= 9:
col = 1
while col <= row:
result=col * row
print '%d*%d=%d\t' %(col,row,result),
col+=1
print ''
row +=1
运行结果: