Python基础知识——条件判断与循环

条件控制

  1. 用法
 if 条件1:
     执行语句
 elif 条件2:
     执行语句
 ...
 else:
     执行语句

2.Python不仅仅可以使用布尔型变量作为条件,它可以直接在if中使用任何表达式作为条件:
大部分表达式的值都会被当作True,但以下表达式值会被当作False:

  • False
  • None
  • 0
  • 空字符串,空列表,空字典,空集合

循环

while 循环
用法:

while <condition>:
    <statesments>

Python会循环执行,直到不满足为止。
空容器会被当成 False ,因此可以用 while 循环来读取容器中的所有元素

plays = set(['Hamlet', 'Macbeth', 'King Lear'])
while plays:
    play = plays.pop()
    print 'Perform', play
*运行结果*
Perform King Lear
Perform Macbeth
Perform Hamlet

for …in 循环

for <variable> in <sequence>:
    <indented block of code>

for 循环会遍历完中所有元素为止

continue 语句

遇到 continue 的时候,程序会返回到循环的最开始重新执行。

values = [7, 6, 4, 7, 19, 2, 1]
for i in values:
    if i % 2 != 0:
        # 忽略奇数
        continue
    print i/2
*运行结果*
3
2
1

break 语句
遇到 break 的时候,程序会提前结束循环

n=1
while n<=100:
    if n>10:
        break
    print(n)
    n=n+1
  *运行结果*
1
2
3
4
5
6
7
8
9
10

http://lijin-thu.github.io/02.%20python%20essentials/02.15%20loops.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值