首页 > 编程语言 > 详细

Python入门基础语法-分支与循环

时间:2020-03-21 02:15:17      阅读:66      评论:0      收藏:0      [点我收藏+]

一、程序控制

1、常见的控制结构:顺序、分支、循环 

单分支:

if conditon:
    代码块
    condition必须是一个bool类型,这个地方有一个隐式转换bool(condition)

代码块:
    类似于if 语句的冒号后面的就是一个语句块
    在if、fordef、class等关键字后使用代码块

双分支及多分支:

if...elif...else语句
if condition1:
    代码块1
elif condition2:
    代码块2
elif condition3:
    代码块3
......
else:
    代码块

分支嵌套

score = -1
if score < 0 :
    print(error input)
elif score <= 100:
    print(right score)
elif score == 0:
    print(zero)
else:
    print(please check it right)

if score < 0:
    print(error input)
else:
    if score == 0:
        print(zero)
    elif score <= 100:
        print(right score)
    else:
        print(input too big)

循环语句(适合在不知道要执行多少次是使用)--while循环

语法
while condition:
    block
当条件满足即condition为True,进入循环体,执行block
示例:计算1+2+3...+10 = ? sum
= 0 flag=10 while flag: sum += flag flag -= 1 print(sum)
#九九乘法表
i = 1
while i < 10:
j = 1
while j < 10:
if i >= j:
print(‘{} * {} = {}‘.format(i,j,i*j),end=‘\t‘)
j += 1
i += 1
print()

循环语句(当可迭代对象中的元素可进行迭代,进入循环体,执行block)

for i in range(1,10):
    print(i)

 

循环--continue语句:终止本次循环进入下一次循环

#打印奇数
for i in range(1,10):
    if i % 2 == 0:
        continue
    print(i)

 

循环--break语句:终止本次循环

count = 0
for i in range(0,100,7):
    count += 1
    if count > 10:
        break
    print(i)

 

Python入门基础语法-分支与循环

原文:https://www.cnblogs.com/alrenn/p/12535387.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!