顺序----从上向下,顺序执行代码
分支----根据条件判断,决定执行代码的分支
循环----让特定代码重复执行
1.while
1.1 格式
i = 1 # 定义一个整数变量,记录循环次数
while i <= 5:
print("hello world") # 希望在循环内执行的代码
i = i + 1 # 处理计数器
死循环
i = 1 # 定义一个整数变量,记录循环次数
while i <= 5:
print("hello world") # 希望在循环内执行的代码
1.2 赋值运算符
注意:赋值运算符中间不能有空格
1.3 python中的计数方法
①自然计数法(从1开始)
②程序计数法(从0开始)
i = 0 # 定义一个整数变量,记录循环次数
while i < 5: # 打印五遍hello world
print("hello world") # 希望在循环内执行的代码
i += 1 # 处理计数器
# 实现0-100之间所以数的累加求和
n = 0 # 定义循环次数
result = 0 # 和
while n <= 100: # 1-100
result += n
n += 1
print("和为:%d" % result)
# 实现0-100之间所以偶数的累加求和
n = 0 # 定义循环次数
result = 0 # 和
while n <= 100: # 1-100
if n % 2 == 0:
result += n
n += 1
print("和为:%d" % result)
# 实现0-100之间所以奇数的累加求和
n = 0 # 定义循环次数
result = 0 # 和
while n <= 100: # 1-100
if n % 2 != 0:
result += n
n += 1
print("和为:%d" % result)
2.break和continue
break:当满足某一条语句时,退出循环,不再执行后续重复的代码
i = 0
while i < 5:
if i == 4:
break
i += 1
print(i)
输出:4
continue:当满足某一条语句时,不执行后续重复的代码
i = 0
while i < 5:
if i == 3:
i += 1 # 避免死循环
continue # i=3,跳出循环,再进行判断
print(i)
i += 1
输出:
0
1
2
4
3.while的循环嵌套:while里面还有while
3.1 用循环嵌套打印小星星
row = 1
while row <= 5:
print("*" * row)
row += 1
line = 1
while line <= 5:
# 每一行打印星星是和行数一样的
col = 1
while col <= line:
print("*", end="")
col += 1
print("")
line += 1
注意:向控制台输出内容结束后,不会换行
print("*", end="---")
print("*")
输出:
*---*
3.2 九九乘法表
row = 1
while row <= 9:
col = 1
while col <= row:
print("%d * %d = %d" % (row, col, col*row), end="\t")
col += 1
print("")
row += 1
(在行尾时)---------续行符
print("line1 \
... line2 \
... line3")
line1 line2 line3
\ ------------反斜杠符号
print("\\")
\
’ -------------单引号
print('\'')
'
" -------------双引号
print("\"")
"
\a --------------响铃
执行后电脑有响声。
print("\a")
\b ----------------退格(Backspace)
print("Hello \b World!")
Hello World!
\000 ----------------空
print("\000")
\n -----------------换行
print("hello world")
print("hello\nworld")
hello world
hello
world
\v --------------纵向制表符
print("Hello \v World!")
Hello
World!
\t --------------横向制表符
print("1\t2\t3")
print("10\t20\t30")
1 2 3
10 20 30
1 2 3
10 20 30
\r ----------------回车,将 \r 后面的内容移到字符串开头,并逐一替换开头部分的字符,直至将 \r 后面的内容完全替换完成。
print("Hello\rWorld!")
World!
print('google runoob taobao\r123456')
123456 runoob taobao
\f --------------换页
print("Hello \f World!")
Hello
World!
\yyy ---------------八进制数,y 代表 0~7 的字符,例如:\012 代表换行。
print("\110\145\154\154\157\40\127\157\162\154\144\41")
Hello World!
\xyy ---------------十六进制数,以 \x 开头,y 代表的字符,例如:\x0a 代表换行
print("\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64\x21")
Hello World!
\other --------------其它的字符以普通格式输出