Python基础循环

Python基础循环

循环的概念

循环是计算机程序的三大语句结构之一,它是在满足条件的情况下,反复执行某一语句块的计算过程。

for循环

使用索引,将列表中的元素逐个输出:

numberList = [10, 20, 30, 40, 50]
print(numberList[0])
print(numberList[1])
print(numberList[2])
print(numberList[3])
print(numberList[4])

感受循环的便捷:

numberList = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
for number in numberList:
    print(number)

其中,for是关键字,和关键字in搭配,代表将列表中的元素赋值给变量number。变量number会被赋值6次。

例:

fruitList = ["apple", "grape", "cherry"]
for fruit in fruitList:
    print(fruit)
'''apple
grape
cherry'''
numberList = [10, 20, 30, 40, 50, 60]
for number in numberList[1 : 6]:
    print(number)
'''20
30
40
50
60'''

遍历

通过某种顺序,对一个数据结构中的所有元素进行访问的操作,称为遍历

遍历字典的键

使用for循环遍历字典的键,有两种方法:

  1. 和列表一样:
dict_name = {}
for key in dict_name:
    print(key)
  1. 使用keys函数,将字典的键生成一个列表,再遍历该列表:
dict_name = {}
for key in dict_name.keys():
    print(key)

遍历字典的值

我们可以通过字典的键查询并遍历对应的值。

首先使用for循环遍历字典,将键赋值给变量,通过dict_name[key]查询对应的值,并赋值给新的变量:

dict_name = {}
for key in dict_name:
    value = dict_name[key]
    print(value)

例:

studentAge = { "Gary" : 14, "Adam" : 13, "Jack" : 15, "Max" : 13, "Tim" : 14}
for key in studentAge:
    studentAge[key] = 16
print(studentAge)
#{'Gary': 16, 'Adam': 16, 'Jack': 16, 'Max': 16, 'Tim': 16}


循环累加

计算一个列表中所有元素的和,称为累加。

例:

jdList = [109.0, 21.5, 30.0, 509.0, 11.2]
total = 0	#初始化变量
for x in jdList:	#遍历列表,获取加数
    total += x	#变量自增
print(total)

计数器

记录当前的循环次数的变量,称为计数器

例:

students = ["Tom", "Blue", "Max", "Shufen", "Joe", "Tim"]
count = 0	#初始化计数器
for name in students:
    count += 1	#计数器自增,记录循环次数
    print(f"第{count}名是{name}")
'''第1名是Tom
第2名是Blue
第3名是Max
第4名是Shufen
第5名是Joe
第6名是Tim'''

条件判断

循环中,我们可以嵌套语句块,使用if进行条件判断。



while循环

while循环,又称条件循环,用于判断条件是否成立,以决定是否执行循环内的语句。

当判断为真时,语句会循环执行,当判断为假时,终止循环。

条件循环的判断条件,称为边界条件,当其为False时,终止循环。

例:

nameList = ["Max", "Tom", "Jim", "Ken", "Kim"]
count = 0
while count <= 2:
    print(nameList[count])
    count += 1
'''Max
Tom
Jim'''

当count未自增时:

nameList = ["Max", "Tom", "Jim", "Ken", "Kim"]
count = 0
while count <= 2:	#其值总是为True
    print(nameList[count])

这个循环永远无法终止,我们称之为死循环,它是一种循环类型。死循环可能会导致程序崩溃或卡死,因为它会占用大量的计算资源,并且无法终止。

请注意,死循环是一个编程错误,应避免在代码中出现。



练习题

报数

使用while循环,实现输出1到50的所有数值。

num = 1
while num < 51:
    print(num)
    num += 1

等差数列求和

让电脑来帮我们做一道数学题:

用while循环,从1累加到50,输出计算结果。

num = 1
sum = 0
while num < 51:
    sum += num
    num += 1
print(sum)	#1275

隔天训练

路飞最近开始训练,为了锻炼更有效率,所以选择隔一天训练一次。

为了确定那些天去训练,请输出小于等于30的所有正奇数,以帮助路飞确定训练的日期。

提示:判断奇偶数可以利用if判断+取模(%)的知识哦~

num = 1
while num < 31:
    if num % 2 == 1:
        print(num)
    num += 1


break

break用于跳出当前的循环语句块的执行。

例:

numList = [1, 10, 100, 50, 40, 30, 200]
for num in numList:
    if num > 100:
        print(num)
        break
#200

continue

continue用于跳过本次循环内的剩余语句。

例:

numList = [1, 10, 100, 50, 40, 30, 200]
for num in numList:
    if num <= 50:
        continue
    print(num)
'''100
200'''
posted @ 2023-10-31 02:09  .hello  阅读(82)  评论(0)    收藏  举报