2018.6.1 Python第二课

六一儿童节,今天课堂主要讲解了Python的循环语句

python循环主要分为两个部分,一个是for循环,一个是while循环


  1. for循环

    Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。
    
    for循环基本语法:
     list=[1,2,3,4,5]
     for i in list:
         print (i)
    

#输出等腰三角形

   *
  ***
 *****
******* 
代码如下
for i in range(1,7):
    print(" "*(6-i),"*"*(2*i-1))

每个班级有五名学生,分别求每个学生的3科成绩的平均值

for i in range(1,6):
     a=int(input("请输入1科成绩"))
     b=int(input("请输入2科成绩"))
     c=int(input("请输入3科成绩"))
     print("同学",i,"三科成绩平均值为",(a+b+c)/3)`

让用户输入一个数字,判断这个数字在1-10之间能否有被整除的数 ”’

a=int(input("输入一个数字"))
#定义一个布尔变量,判断是否进入循环里的if判断
tag=True 
for i in range(1,11):
     if i%a==0:
        tag=False
         print(i)
          if tag==True:
     print("不存在")

求1-100之间能被3整除的数,只要求得到前10个

count=0 #先定义一个计数器
for i in range(1,101):
    if i%3==0:
        print(i,end="\t")
        count+=1
        #当计数器大于10次的时候结束循环
        if count>9:
            break

for…..else结构:当循环中有break时,如果没有执行if,则执行else
a=int(input("请输入一个数字"))
for i in range(1,11):
    if i%a==0:
        print(i)
        break
else:
    print("不存在")

二. while循环

Python 编程中 while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务。

基本结构为
while 判断条件
    执行语句块...
count = 0
while  count < 9:
   print('The count is:', countcount = count + 1
 print "Good bye!"

以上代码运行结果为:
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!


  • while 语句时还有另外两个重要的命令 continue,break 来跳过循环,continue 用于跳过该次循环,break 则是用于退出循环,此外”判断条件”还可以是个常值,表示循环必定成立,具体用法如下:

continue 和 break 用法

i = 1
while i < 10:   
    i += 1
    if i%2 > 0:     # 非双数时跳过输出
        continue
    print i         # 输出双数2、4、6、8、10
i = 1
while 1:            # 循环条件为1必定成立
    print i         # 输出1~10
    i += 1
    if i > 10:     # 当i大于10时跳出循环
        break

  • 在 python 中,while … else 在循环条件为 false 时执行 else 语句块:
count = 0
while count < 5:
   print count, " is  less than 5"
   count = count + 1
else:
   print count, " is not less than 5"

以上输出结果为:
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5

猜你喜欢

转载自blog.csdn.net/weixin_40313627/article/details/80552336