循环结构(while、for)


循环结构(while 、for)

什么是循环结构

循环机构就是重复执行某段代码块

为什么要用循环结构

人类某些时候需要重复做某件事情

所以程序中必须有相应的机制来控制计算机具备人的这种循环做事的能力

如何使用循环结构

python中有while和for两种循环机制

while循环语法

while循环称之为条件循环,语法如下:

while 条件:
	代码1
    代码2
    代码3
else:
    代码a

while的运行步骤:
步骤1:如果条件为真,那么执行:代码1、代码2、代码3、……
步骤2:执行完毕代码块后再次判断条件,如果条件继续为True则再次执行:代码1、代码2、代码3、……, 如果条件为False了,则结束while循环。
步骤3:如果while循环不是通过break提前终止的,则会在循环完整结束后执行else内的代码a
    
结束循环的条件:
1.判断条件为False
2.break提前跳出循环

continue 提前结束当前一次循环,进入下一次循环

preview

while循环案例

案例一:

username = "jason"
password = "123"
count = 0  # 记录错误次数
while count < 3:  # 最多错误3次
    inp_name = input("请输入用户名:")
    inp_pwd = input("清输入密码:")
    if inp_name == username and inp_pwd == password:
        print("登陆成功")
    else:
    	print("输入的用户名或用户错误")
        count += 1

案例二:while+break的使用

上述案例使用while循环后,代码精简很多,但问题是用户输入了正确的用户名和密码后无法结束循环,那如何结束掉循环呢?这就需要使用到break了!

username = "jason"
password = "123"
count = 0  # 记录错误次数
while count < 3:  # 最多错误3次
    inp_name = input("请输入用户名:")
    inp_pwd = input("清输入密码:")
    if inp_name == username and inp_pwd == password:
        print("登陆成功")
        break  # 用于结束循环
    else:
    	print("输入的用户名或用户错误")
        count += 1

案例三:while循环嵌套+break

如果while循环嵌套了很多层,要想退出每一层循环则需要在每一层循环都有一个break

username = "jason"
password = "123"
count = 0  # 记录错误次数
while count < 3:  # 最多错误3次
    inp_name = input("请输入用户名:")
    inp_pwd = input("清输入密码:")
    if inp_name == username and inp_pwd == password:
        print("登陆成功")
        while True:
        	cmd = input(">>: ")
            if cmd == 'quit':
                break # 用于结束本层循环,即第二层循环
            else:
                print('run <%s>' % cmd)
        break  # 用于结束本层循环,即第一层循环
    else:
    	print("输入的用户名或用户错误")
        count += 1

案例四:while+continue的使用

break代表结束本层循环,而continue则用于结束本次循环,直接进入下一次循环

# 打印1到10之间,除7以外的所有数字
number=1
while number<11:
    if number == 7:
        continue # 结束掉本次循环,即本次循环continue之后的代码就不会执行了,而是直接进入下一次循环。
    print(number)
    num += 1

案例五:while+else的使用

在while循环的额后面,可以使用else语句,当while循环正常执行完并且中间没有被break中止的话,就会执行else后面的语句,所以可以用else来验证,循环收否正常结束

count = 0
whlie coount <= 5:
    count += 1
    print("Loop", count)
else:
    print("循环正常执行完啦")
print("-----out of while loop -----")
输出
Loop 1
Loop 2
Loop 3
Loop 4
Loop 5
Loop 6
循环正常执行完啦   #没有被break打断,所以执行了该行代码
-----out of while loop -----

如果执行过程中被break中止,就不会执行else的语句

count = 0
while count <= 5:
    count += 1
    if count == 3:
        break
    print("Loop", count)
else:
    print("循环正常执行完啦")
print("-----out of while loop -----")
输出
Loop 1
Loop 2
-----out of while loop ----- #由于循环被break打断了,所以不执行else后的输出语句

练习1:

寻找 1到100之间数字7最大的倍数

num = 100
while num > 0:
    if num % 7 == 0:
        print(num)
        break
    num -= 1

练习2:

猜年龄 且最多猜3次

age = 18
count = 0
while count < 3:
    count += 1
    guess = int(input('>>: '))
    if guess > age:
        print("太大了")
    elif guess < age:
        print("猜小了")
    else:
    	print("猜对啦")
        break
else:
    print("三次都没猜对,下次再来玩吧")

for循环语法

for 变量名 in 可迭代对象:
    代码一
    代码二
    。。。
    
 # 例1
for item in ['a', 'b', 'c']:
    print(item)
# 运行结果
a
b
c

# 参照例1来介绍for循环的运行步骤
# 步骤1: 从列表['a', 'b', 'c']中读出第一个值赋值给item(item = 'a'), 然后执行循环体代码
# 步骤2: 从列表['a', 'b', 'c']中读出第二个值赋值给item(item = 'b'), 然后执行循环体代码
# 步骤3: 重复上述过程直至列表中的值读尽

img

案例一:打印数字0-5

# 简单版:for循环的实现方式
for count in range(6):
    print(count)

# 复杂版:while循环的实现方式
count = 0
while count < 6:
    print(count)
    count += 1

案例二:遍历字典

# 简单版:for循环的实现方式
for k in {'name':'jason','age':18,'gender':'male'}:  # for 循环默认取的是字典key
	print(k)

# 复杂版:while循环确实可以遍历字典,后续将会迭代器部分详细介绍

案例三:for循环嵌套

# 请用for循环嵌套的方式打印如下图形:
*****
*****
*****

for i in range(3):
    for j in range(5):
        print('*', end='')
    print()  # print()可以换行

注意:break与continue也可以用于for循环,用法与在while循环中相同

练习一:

打印九九乘法表

for i in range(1,10):
    for j in range(i,10):
        res = i*j
        print("{x}x{y}={r}".format(x=i,y=j,r=res), end=' ')
    print()

# 结果:
1x1=1 1x2=2 1x3=3 1x4=4 1x5=5 1x6=6 1x7=7 1x8=8 1x9=9 
2x2=4 2x3=6 2x4=8 2x5=10 2x6=12 2x7=14 2x8=16 2x9=18 
3x3=9 3x4=12 3x5=15 3x6=18 3x7=21 3x8=24 3x9=27 
4x4=16 4x5=20 4x6=24 4x7=28 4x8=32 4x9=36 
5x5=25 5x6=30 5x7=35 5x8=40 5x9=45 
6x6=36 6x7=42 6x8=48 6x9=54 
7x7=49 7x8=56 7x9=63 
8x8=64 8x9=72 
9x9=81 

练习二:

打印金字塔

max_piles = 7
for i in range(1, max_piles+1):
    temp_str = '*'*(i*2-1)
    print(temp_str.center(2*max_piles-1))
    
# 结果:
      *      
     ***     
    *****    
   *******   
  *********  
 *********** 
*************


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM