Python应用for循与range函数

        大家好!在Python的编程世界中,for循环和range函数是两个强大的工具,它们可以让我们轻松地对集合中的元素进行迭代和操作。今天,我将分享我学习for循环和range函数的一些过程。​

        知识介绍:

  • for循环常用于对可迭代对象(如字符串、列表、字典等)进行遍历。它的基本语法是:for 变量名 in 可迭代对象。
  • range函数可以生成一系列数字,通常用于for循环中。

         代码介绍:

      for循环

  1. 我首先尝试了用for循环遍历一个温度列表。在代码实例中,我们定义了一个 temperature_list ,然后用 append 方法添加了一个新元素。接着,用for循环对列表中的每个温度进行检查,如果温度大于或等于38,就会输出该温度,并提醒用户可能发烧了。
  2. ​遍历字典​​在学习字典的遍历时,我了解到字典的 items() 方法可以返回所有键值对。在字典的for循环中,我通过遍历键值对,检查每个温度是否大于或等于38,如果满足条件,就输出对应的people_id。
  3. ​遍历字典的另一种方式​​另一种遍历字典的方式是先获取 items() 方法返回的元组,然后再分别提取键和值。这种方法可以让我们更灵活地处理键值对。​

        range函数

  1. 基本用法​​range函数可以指定起始值和结束值,生成一个左闭右开的整数序列。例如,range(3,10) 会生成3到9的数字序列。​
  2. 指定步长​​在range函数中,可以使用第三个参数来指定步长。例如,range(1,10,2) 会生成1到9之间的奇数序列。
  3. ​计算1到100的和​​利用range函数和for循环,可以轻松计算出1到100的和。在代码中,我们初始化一个sum变量为0,然后用for循环遍历1到100的数字,将每个数字加到sum上,最后输出sum的值。

           代码呈现:

#在for循环里可对字符串,列表字典进行迭代
#for 变量名 in 可迭代对象
#1.
temperature_list = [37.2,36.4,35.2,38.6,37.2,38,36.6,37.2]                
temperature_list.append(38.9)#append:附加
for temperature in temperature_list:
    if temperature >= 38:
        print(temperature)
        print("您发烧了,请及时就医。")
      #2.
temperature_dict = {"1":37.2,"2":36.4,"3":35.2,"4":38.6,"5":37.2,"6":38,"7":36.6,"8":37.2} 
temperature_dict["9"] = 38.9#添加
#temperature_dict.keys()   所有键
#temperature_dict.values() 所有值
#temperature_dict.items()  所有键值对
for people_id,temperature in temperature_dict.items():
    if temperature >= float(38):
        print(people_id)
#3.
temperature_dict = {"1":37.2,"2":36.4,"3":35.2,"4":38.6,"5":37.2,"6":38,"7":36.6,"8":37.2} 
temperature_dict["9"] = 38.9
for temperature_tuple in temperature_dict.items():
    people_id = temperature_tuple[0]
    temperature = temperature_tuple[1]
    if temperature >= float(38):
        print(people_id)
#4
#range(3,10)第一个数为起始值,第二个为结束值。左闭右开区间,[3,10),3,4,5,6,7,8,9
for i in range(3,10):
    print(i)
#range(1,10,2)第三个数为步长,跨两个数
for i in range(1,10,2):#不指明步长,默认为1。
    print(i)
#1-100和
sum=0#sum:和
for i in range(1,101):
    sum=sum+i
    print(sum)#print写这里输出每次循环的答案
print(sum)#这里得出总值


        总结:

         通过这次学习,我对Python中的for循环和range函数有了更深入的理解。希望我的这篇学习日志能够帮助其他初学者更好地理解和掌握for循环和range函数的用法。​

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值