【笔记】python控制语句

赋值号右边的表达式会在赋值变动之前执行,右边表达式的执行顺序是从左往右的。如下是生成一个斐波纳契数列

a,b=0,1
while b < 10 :
    print(b)
    b,a = a+b,b

1. 条件语句

注意:elif 而非 else if

if condition_1:
    statement_block_1
elif condition_2:
    statement_block_2
else:
    statement_block_3

 

注意:

  • 1、每个条件后面要使用冒号 :,表示接下来是满足条件后要执行的语句块。
  • 2、使用缩进来划分语句块,相同缩进数的语句在一起组成一个语句块。
  • 3、在Python中没有switch – case语句

 if嵌套

if 表达式1:
    语句
    if 表达式2:
        语句
    elif 表达式3:
        语句
    else:
        语句
elif 表达式4:
    语句
else:
    语句

 代码示例

number = int(input('please input number:   '))
if number%2 == 0 :
    if number%3 == 0:
        print(f'the nember you input ({number}) could be devided by 2 and 3')
    else :
        print(f'the nember you input ({number}) could be devided by 2 but 3')
else :
    if number%3 == 0:
        print(f'the nember you input ({number}) could be devided by 3 but 2')
    else :
        print(f'the nember you input ({number}) could not be devided by 2 or 3')

 输出结果

2. while循环语句

while循环:

while 判断条件(condition):
    执行语句(statements)……

while...else...语句

while <expr>:
    <statement(s)>
else:
    <additional_statement(s)>

代码示例。(与if类似,如果while循环体中只有一条语句,可以将该语句与while或else写在同一行中)

num = 0
sum = 0
while num <= 100 :
    sum += num
    num += 1
else : print(sum)
print('end of while...else...')

在 Python 中没有 do..while 循环。

3. for循环

与其他语言的for循环不同,Python for循环可以(主要用于)遍历任何序列的项目,如一个列表、一个字符串、集合等。

for <variable> in <sequence>:
    <statements>
else:
    <statements>

 代码示例

sets = {'forest','li','name','math','english'}
for x in sets :
    if x == 'li' :
        print("'li' is in the sets")
        break
print('search end')

 

此外,<variable>可以是多个变量

for x,y in [(1,2),(1,3),(1,4)]:
    print(x,y)

 

4. range函数

range(start,end,step) 三个参量分别为序列的首值、末值、步长。start默认值为0;step默认值为1,他们两个可以被省略。

我们在C语言中使用for循环一般会用比较符号限定i的范围,而python使用这个函数来限定,达到同样的效果。

比如查找0~1000范围内能被17整除的数

i,j = 0,0
for i in range(0,1000) :
    if i % 117 == 0 :
        j += 1
        print(i,end=',')
    i += 1
print('\ntotle',j)

遍历序列

set1 = [554,78,'forest','good',89,12,'nihao',32]
for i in range(len(set1)):
    print(f'{i}:',set1[i])

创建一个列表

list1 = list(range(5,18,3))
print(list1)

 

5. break 、 continue和pass

break 语句可以跳出 for 和 while 的循环体。如果你从 for 或 while 循环中终止,任何对应的循环 else 块将不执行。

continue 语句被用来告诉 Python 跳过当前循环块中的剩余语句,然后继续进行下一轮循环。

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

注意pass和continue、break不一样,后者用于处理循环语句,后者什么都可以,它就是个空语句,这条语句什么都不执行。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值