python:while循环、for循环

循环:

在python编程中,python提供了for循环和while循环

while循环:

基本语法为:

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

1、while循环用于循环执行程序,以处理需要重复处理的任务。

2、while循环用于多次判断同一个条件,if 语句只能判断一个条件一次

3、执行语句可以是单个语句或语句块。判断条件可以是任何表达式,所有非空(null)、非零的值都为真(True)。当判断条件为假(False)时,循环结束

4、while循环的执行流程图如下:

该流程图的意思为:首先对while条件进行判定,当条件为ture时,执行语句块,执行完语句块后再次对条件进行判定,若为仍为true,则继续执行语句块,直到条件为false时结束循环


5、循环中使用else语句:

在python中,while....else..在循环条件为false时执行else语句块

number = 1
while number < 5:
	print(number)
	number += 1
else:    #else与while为同一缩进
	print("number的值为5")

6、while.....if.....语句
例1:

import random

number = random.randint(0,10)
guess = int(input("请输入你认为正确的数字:"))

while guess != number:
    guess = int(input("您猜错了,请输入你认为正确的数字:"))

    if guess > number:
        print("稍微大了一点,需要再小一点")
    else:
        if guess < number:
            print("稍微小了一点,需要再大一点")
    if guess == number:
        print("正确")

例2:

list = [12,37,5,42,8,3]
list_1 = []
list_2 = []
while len(list) > 0:
	number = list.pop()
	if number % 2 == 0:
		list_1.append(number)

	else:
		list_2.append(number)
print(list_1)
print(list_2)

在上面的例2中先是通过while、if 条件的判断,分别得到list_1、list_2,在最后一次判断中while为False,则不执行循环执行输出

for循环:

1、在python中,for关键字叫做for循环,for循环可以遍历任何一个序列,如一个列表或字符串

2、for循环的基本语法格式如下:

for iterating_var in sequence:
    statements(s)

sequence是需要迭代的任意序列,iterating_var是序列中需要遍历的元素(即序列中元素的变量名),statements(s)是待执行的语句块


3、使用while遍历序列中的元素:

list = [12,37,5,42,8,3]
n = 0
while 0 < len(list):
	print("当前字母是 %s" % list[n])
	n += 1
	if n == 6:
		break  #n等于6时跳出循环,避免n的值超出序列的长度

4、for循环与range()函数:

for number in range():
    print(number)

range(star,stop,step) : 用于生成一个指定序列
参数star:表示生成的序列的开始数字,无此参数时,表示序列从0开始
参数stop:表示生成序列的结束数字
参数step:表示生成序列的递增数(该参数不能是浮点数),无此参数时,表示默认递增数为1
注:该函数的返回值为一个列表且生成的序列包含star参数但不会包含stop参数(包左不包右)

循环遍历字典中的元素(序列解包):
例1:

tups = {"小明":"001","小红":"002"}
for name in tups:
	print("%s : %s" % (name,tups[name]))

单纯的对字典进行循环迭代时,只能对键进行迭代,若同时想得到键对应的值时只能通过字典索引的方式得到

例2:

tups = {"小明":"001","小红":"002"}
for name,number in tups.items():
	print("%s : %s" % (name,number))

例2中先是通过items()函数得到由键值对组成元组,在对返回的元组利用序列解包的方式同时对键值对进行迭代

同时迭代两个序列(并行迭代):

例1:

name = ["小红","小张","小强"]
number = ["001","002","003"]
for student_ID in range(len(name)):
	print("学生的名字:%s,学号为: %s" % (name[student_ID],number[student_ID]))

例2:

name = ["小红","小张","小强"]
number = ["001","002","003"]
for student_name,student_ID in zip(name,number):
	print(student_name,"的学号是",student_ID)

例2中先通过函数zip()将两个序列打包成一个元组列表,再通过序列解包和循环迭代的方法得到对应学生的学号和名字,

zip()函数可以作用于任意数量的学列,并且可以应付不等长的序列,当短序列用完时,就会停止。

在for循环中使用else语句:

在for条件语句为false或结束后没有被break中断时,执行else语句
例1:

ist = ["xiaozhang","xiaohong"]
for name in list:
	if name == "xiao":
		print("名称: ",name)
		break
	print("当前名称: ",name)
else:  #与for语句为同一缩进
	print("没有循环数据了")
print("循环结束")

break:终止当前循环并跳出整个循环

1、break语句用在while和for循环中
2、break语句用于跳出当前循环,并且不会再执行break下面的代码
3、break语句通过if语句来对条件进行判定,当if语句为True时,执行break语句
例1:

str = ("hello")
for letter in str:
	if letter == "l":
		break
	print(letter)

例2:

number = 10
while number > 2:
	if number == 6:
		break   #跳出整个循环,不会再执行下面的代码
	print(number)
	number -= 1

continue:终止当前的循环,继续下一循环
1、continue语句用来告诉python跳过当前循环的剩余语句,然后继续进行下一轮循环
2、continue语句用在while和for循环中
3、continue语句通过if语句来对条件进行判定,当if语句为True时,执行continue语句
4、continue语句的作用为终止当前循环(不会执行continue下面的代码),并开始下一轮循环(重新开始)

例1:

number = 1
while number < 10:
	if number == 5:
		number += 1
		continue
	if number == 7:
		break
	print(number)
	number += 1

例2:

str = ("hello")
for letter in str:
	if letter == "l":
		continue
	print(letter)

由输出结果来看,相比与break,使用continue语句只是跳过了某次循环 ,不会跳出整个循环

备注:

1、while循环和for循环两者的相同点在于都能循环做一件重复的事情。不同的是for循环是在序列穷尽时停止;while循环是在条件不成立时停止。

2、for 循环提供了python中最强大的循环结构(for循环是一种迭代循环机制,而while循环是条件循环迭代即重复相同的逻辑操作,每次操作都是基于上一次的结果,而进行的)

3、Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。

4、for循环可以用来遍历某一对象(遍历:通俗点说,就是把这个循环中的第一个元素到最后一个元素依次访问一次

一般来说for循环的执行过程为:迭代出一个元素后,继续执行for所属代码块,后面的代码块执行完后,在进行下一个迭代

例子:

list = [1,2,3,4]
list_1 = []
for num in list:
    list_1.append(num)
    print(list_1)

"""
上面代码的输出结果为:
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
"""

例子:

list = [1,2,3,4]
list_1 = []
for num in list:
    list_1.append(num)
print(list_1)  #print()的位置不同:执行完全部for后,再输出


#上面代码的输出结果为:[1, 2, 3, 4]

猜你喜欢

转载自blog.csdn.net/qq_39314932/article/details/79596749