目录

  • python的两种循环结构
  • while循环
  • for循环
  • 实例
  • for 循环进行数值循环
  • for循环遍历列表和元组
  • for循环遍历字典
  • 循环中的break和continue语句


python的两种循环结构

python有for循环和while循环两种结构

循环结构图:

Python中求1到n的和程序 python求1到n的和while_Python中求1到n的和程序

while循环

while循环语句的基本形式

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

注:python中没有do…while循环

实例1: 用while循环计算1到100的和:

n = 1
sum = 0
while n <= 100:
	sum = sum + n
	n += 1
print("1到100相加的和为:%d"%sum)

Python中求1到n的和程序 python求1到n的和while_迭代_02

实例2: 若条件永不为false则可以实现无限循环,例如

n = 1
while n == 1:
    num = input("请输入一个值:")
    print("您输入的值为:",num)

Python中求1到n的和程序 python求1到n的和while_python_03


注:用CTRL + C退出无限循环

while…else…循环语句的基本形式
当while后的条件为false时则执行else中的语句

while 条件语句1:
	执行语句1...
else:
	执行语句2...

若条件语句1为true则执行语句1,为false则执行语句2

实例1: 输出大于0小于等于5的所有整数

n = 0
while n <= 5:
	print(n)
	n += 1
else:
	print(n,"大于5")

Python中求1到n的和程序 python求1到n的和while_for循环_04

for循环

python中for循环的可循环范围很广,可以遍历任何可迭代对象(例如:列表,元组,字典, 集合或字符串)
for循环语句的基本形式

for 迭代变量 in 字符串|列表|元组|字典|集合:
	代码块...

for循环流程示意图:

Python中求1到n的和程序 python求1到n的和while_迭代_05

实例

for 循环进行数值循环

用for循环实现从1到100的累加

num = 0
for i in range(1,101):
	num += i
print(num)

Python中求1到n的和程序 python求1到n的和while_python_06


注:该实例中的range()函数是python的内置函数,用于生成一系列连续整数,多用于for循环中

for循环遍历列表和元组

列表:

list = [1,2,3,4,5]
for n in list:
	print(n)

Python中求1到n的和程序 python求1到n的和while_Python中求1到n的和程序_07


元组:

tuple = ("2","3","(1,2,3)","apple")
for n in tuple:
	print(n)

Python中求1到n的和程序 python求1到n的和while_python_08

for循环遍历字典

方法一: for循环+索引进行迭代

dict = {'name':'cn','age':19,'class':'thrift'}
for key in dict:
	print(key,":",dict[key])

Python中求1到n的和程序 python求1到n的和while_for循环_09

注:python 会自动将dict视为字典,并允许迭代其key键。然后就可以使用索引运算符,来获取每个value值。

方法二:keys( ) + 索引进行迭代

dict = {'name':'cn','age':19,'class':'thrift'}
for key in dict.keys():
	print(key,':',dict[key])

Python中求1到n的和程序 python求1到n的和while_for循环_10

方法三:items( ) 进行迭代

dict = {'name':'cn','age':19,'class':'thrift'}
for a,b in dict.items():
	print(a,":",b)

Python中求1到n的和程序 python求1到n的和while_Python中求1到n的和程序_11

循环中的break和continue语句

breakcontinue的执行流程图:

Python中求1到n的和程序 python求1到n的和while_Python中求1到n的和程序_12


break 语句可以跳出 for 和 while 的循环体。如果你从 for 或 while 循环中终止,任何对应的循环 else 块将不执行。

实例

n = 5while n > 0:	n -= 1	if n == 2: 
		break
	print(n)
print('循环结束。')

Python中求1到n的和程序 python求1到n的和while_for循环_13

continue 语句被用来告诉 Python 跳过当前循环块中的剩余语句,然后继续进行下一轮循环。

实例

n = 5while n > 0:	n -= 1	if n == 2: 
		continue
	print(n)
print('循环结束。')

Python中求1到n的和程序 python求1到n的和while_for循环_14