从0开始学Python——判断和循环结构

判断和循环结构

1. if语句

if语句用来判断当某个条件成立(非0或为True)时,执行下一个语句。常与else一起使用,表示除if判断条件之外的其他情况。

示例:

>>> num = 130 
>>> if num%2 == 0: 
...  print(num, "is a even number") 
... else: 
...  print(num, "is a odd number") 
... 130 is a even number

注意:
可以有多个elif,else是可选的。elif是“else if”的缩写,对于避免过多的缩进非常有用,else与它最近的前一个if或elif匹配。

示例:

>>> x = 32 
>>> if x < 0: 
...  print("Negative changed to zero") 
... elif x == 0: 
...  print("Zero") 
... elif x == 1: 
...  print("Single") 
... else: ...  
print("More") 
... 
More

注意:
由于Python严格的缩进格式,为避免出错,最好用四个空格键进行缩进。

示例:

>>> x = 32 
>>> if x > 0: 
...  print("x > 0") 
... print("hello") 
... else: 
...  print("x <= 0") 
... Traceback (most recent call last):  
File "<stdin>", line 3 
SyntaxError: invalid syntax

2. while语句

while语句用于循环执行程序,即在某条件下,循环执行某段程序。

示例:

>>> i = 5 
>>> while i > 0: 
...  print(i) 
...  i = i-1 
... 
5 
4 
3 
2 
1

3. for语句

for语句用于循环执行程序,并按序列中的项目(一个列表或一个字符串)顺序迭代。

示例:

>>> words = ['www', 'DFRobot', 'com', 'cn'] 
>>> for w in words: 
...  print(w, len(w)) 
... www 3 
DFRobot 7 
com 3 
cn 2

如果需要在for循环内修改迭代的顺序或条件,可以在for循环中增加条件判断。

示例:

 >>> words = ['www', 'DFRobot', 'com', 'cn'] 
 >>> for w in words: 
 ...  if len(w) < 7: 
 ...   print(w) 
 ...   
 ...   
 ... 
 www com cn

range()函数

如果你需要遍历一系列的数字,可以使用内置函数range()。

示例:

>>> for i in range(4): 
...   print(i) 
...   
...   
... 
0 
1 
2 
3

4. break语句

break语句用于退出for或while循环。

示例:

>>> for x in range(2, 10): 
...  if x == 5: 
...   break 
...  print(x) 
... 
2 
3 
4

5. continue语句

continue语句用于退出for或while语句的当前循环,进入下一次循环。

示例:

>>> for x in range(2, 10): 
...  if x == 5: 
...   continue 
...  print(x) 
... 
2 
3 
4
6 
7 
8 
9

6. pass语句

pass语句表示空语句,不做任何事情,一般用作占位语句,用来保持程序结构的完整性。

示例:

>>> for letter in 'hello': 
...  if letter == 'l': 
...   pass 
...   print("This is pass") 
...  print("Current letter:", letter) 
... 
Current letter: h 
Current letter: e 
This is pass 
Current letter: l 
This is pass 
Current letter: l 
Current letter: o
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Vicky__3021

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值