python基础 二、控制流程

第四章 控制流程

计算机程序在解决某个具体问题时,包括三种情形,即顺序执行所有的语句、选择执行部分的语句和循环执行部分语句,这正好对应着程序设计中的三种程序执行结构流程:顺序结构、选择结构和循环结构。

if语句

x = int(input("请输入您的总分:"))
if x >= 90:
    print('优')
elif x>=80:
    print('良')
elif x >= 70:
    print('中')
elif x >= 60:
    print('合格')
else:
    print('不合格')

三目运输

a  =   3
if  a > 5:
    print(True)
else:
    print(False)
#转化为三目运算
a  =   3
True  if   a>5  else False

while语句

count = 0
while count < 5:
   print(count, " is  less than 5")
   count = count + 1
else:
   print(count, " is not less than 5")

for循环语句

for num in range(10,20):
    for i in range(2,num):
        if num % i == 0:
            j = num/i
            print("%d等于%d*%d" % (num,i,j))
            break
    else:
        print("%d是一个质数" % num)

break语句

break语句用在while和for循环中,break语句用来终止循环语句,即循环条件没有False条件或者序列还没被完全递归完,也会停止执行循环语句。

#break是终止本次循环,比如你很多个for循环,你在其中一个for循环里写了一个break,满足条件,只会终止这个for里面的循环,程序会跳到上一层for循环继续往下走
for i in range(5):
    print("-----%d-----" %i)
    for j in range(5):
        if j > 4:
            break
        print(j)

continue语句

continue语句用在while和for循环中,continue 语句用来告诉Python跳过当前循环的剩余语句,然后继续进行下一轮循环。 continue 语句跳出本次循环,而break跳出整个循环。

#continue通过if判断触发,跳出当前一层for循环,继续下一次for.
for letter in 'Python':
if letter == 'h':
continue #此处跳出for枚举'h'的那一次循环
print('当前字母 :', letter)

pass语句

Python pass是空语句,是为了保持程序结构的完整性。pass 不做任何事情,一般用做占位语句。

for element in "Python":  
     if element == "y":  
         pass  
     else:  
         print(element)

猜你喜欢

转载自www.cnblogs.com/xjl-dwy/p/10411690.html
今日推荐