第三篇 条件控制和循环

1.条件控制

if语句的形式一般为:

1 if 条件1:
2   语句1
3 elif 条件2:
4   语句2
5 else:
6   语句3

注意:代码的缩进为一个tab键,或者4个空格,建议使用空格。

实例:

 1 userInput=input("请输入您的年龄:")
 2 userAge=int(userInput)
 3 if userAge>=18:
 4     print("you are a adult")
 5 elif userAge>=8:
 6     print("you are a teenager")
 7 else:
 8     print("you are a kid")
 9 
10 --------输出结果-------
11 请输入您的年龄:26
12 you are a adult

注意:(1)每个条件后面要使用冒号,以表示接下来是满足条件后要执行的代码块。

   (2)使用缩进来划分语句块,相同的缩进为一个代码块。

   (3)if和else语句以及各自的缩进部门共同是一个完整的代码块。

在第二篇中学习到的操作符,在if语句中经常使用的比较运算符,如下:

操作符描述
>大于
>=大于等于
<小于
<=小于等于
==相等
!=不相等

 

 

 

 

 

 

另外,在程序开发过程中,通常需要判断多个条件,多个条件满足时才能执行后续代码,这个时候需要用到逻辑运算符,逻辑运算符可以把多个条件按照逻辑进行连接,Python中的逻辑运算符包括:and、or、not三种。

条件1 and 条件2:条件1和条件2同时成立时才返回True。

1 python_score = 70
2 c_score = 29
3 
4 if python_score > 60 and c_score > 60:
5     print("成绩不错")

条件1 or 条件2:条件1和条件2有一个成立就返回True。

1 python_score = 70
2 c_score = 29
3 
4 if python_score > 60 or c_score > 60:
5     print("成绩不错")
6 
7 ------输出结果------
8 成绩不错

not 条件:条件为真返回False,条件为假返回True。

1 is_man = False
2 
3 if not is_man:
4     print("不是个男人")
5 
6 -----输出结果-----
7 不是个男人

说明,当多个逻辑运算符在一起时,可以进行换行,建议的格式如下:

 1 # 导入包的时候,应该将导入的语句放在文件的顶部,这样方便下方代码可以在任何使用使用工具包中的代码
 2 import random
 3 player = int(input("请输入您要出的拳:1(剪刀)/2(石头)/3(布)"))
 4 
 5 computer = random.randint(1,3)
 6 print("您出的拳为:%s,电脑出的拳为:%s" %(player,computer))
 7 if ((player == 1 and computer == 3)
 8         or (player == 2 and computer == 1)
 9         or (player == 3 and computer == 2)):
10     print("电脑输了")
11 elif player == computer:
12     print("平局")
13 else:
14     print("电脑赢了")

if语句可以进行嵌套,如下:

 1 userInput=input("请输入你的年龄:")
 2 userAge=int(userInput)
 3 
 4 if userAge<=25:
 5     if userAge>=14:
 6         print("你是一个青年")
 7     elif userAge>=8:
 8         print("你是一个少年")
 9     else:
10         print("你是一个儿童")
11 else:
12     if userAge>=86:
13         print("你已经暮年")
14     elif userAge>=76:
15         print("你是寿年")
16     elif userAge>=66:
17         print("你是老年")
18     elif userAge>=56:
19         print("你是中年")
20     elif userAge>=46:
21         print("你是达年")
22     elif userAge>=36:
23         print("你是盛年")
24     else:
25         print("你是壮年")

注:所有的标准对象均可用于布尔测试,同类型的对象可以比较大小,每个对象天生都有True或者False值与其对应。

None,0,0.0+0.0j,"",[],()等的布尔值均为False。

if not None:
    print("None的布尔值是False")
if not 0:
    print("0的布尔值是False")
if not 0.0+0.0j:
    print("0.0+0.0j:的布尔值是False")
if not "":
    print("\"\"的布尔值是False")
if not []:
    print("[]的布尔值是False")
if not ():
    print("()的布尔值是False")
if not {}:
    print("{}的布尔值是False")

-------输出结果-----
None的布尔值是False
0的布尔值是False
0.0+0.0j:的布尔值是False
""的布尔值是False
[]的布尔值是False
()的布尔值是False
{}的布尔值是False

三元表达式

例如如果x>y的结果为真,则a=12,否则a=13:

a=12 if x>y else 13

2.while循环

程序的三大流程分别为顺序(从上到下),分支(根据条件判断,决定执行代码的分支),循环(让特定代码重复执行)。

 while语句的一般形式为:

1 while 条件:
2     循环体

实例,计算1+2+3+...99的和。

 1 i=1
 2 count=0
 3 while i<=99:
 4     count+=i
 5     i+=1
 6 
 7 print("1+2+3+...+99的和为:",count)
 8 
 9 ------输出结果-----
10 1+2+3+...+99的和为: 4950

可以使用while无限循环来控制用户无限次数输入年龄:

 1 while True:
 2     userInput = input("请输入你的年龄:")
 3     userAge = int(userInput)
 4 
 5     if userAge <= 25:
 6         if userAge >= 14:
 7             print("你是一个青年")
 8         elif userAge >= 8:
 9             print("你是一个少年")
10         else:
11             print("你是一个儿童")
12     else:
13         if userAge >= 86:
14             print("你已经暮年")
15         elif userAge >= 76:
16             print("你是寿年")
17         elif userAge >= 66:
18             print("你是老年")
19         elif userAge >= 56:
20             print("你是中年")
21         elif userAge >= 46:
22             print("你是达年")
23         elif userAge >= 36:
24             print("你是盛年")
25         else:
26             print("你是壮年")
27 
28 ------输出结果-------
29 请输入你的年龄:16
30 你是一个青年
31 请输入你的年龄:29
32 你是壮年
33 请输入你的年龄:25
34 你是一个青年
35 请输入你的年龄:24
36 你是一个青年
37 请输入你的年龄:27
38 你是壮年
39 请输入你的年龄:

注:可以使用Ctrl+C来结束循环。

while...else语句

当while条件中为False时执行else代码块:

i=1

while i<10:
    print("i的值为:",i)
    i+=1
else:
    print("i的值为10,程序跳出while循环,执行else语句块内容")

------输出结果------
i的值为: 1
i的值为: 2
i的值为: 3
i的值为: 4
i的值为: 5
i的值为: 6
i的值为: 7
i的值为: 8
i的值为: 9
i的值为10,程序跳出while循环,执行else语句块内容

如果while循环体的语句只有一条语句,则该语句可以和while在同一行。

1 i=1
2 while i:print("无限循环")

while嵌套

1 rows = 1
2 
3 while rows <= 9:
4     cols = 1
5     while cols <= rows:
6         print("%d * %d = %d" %(cols,rows,cols * rows),end="\t")
7         cols += 1
8     rows += 1
9     print("")

3.for循环

for循环可以用来遍历任何序列,如列表和字符串等。

for循环的一般形式为:

1 for 变量名 in sequence:
2     循环体
3 else:
4 没有通过break退出循环,循环结束后,会执行的代码

实例:

1 names=["zhangsan","lisi","wangwu","boxiaoyuan"]
2 for name in names:
3     print(name)
4 
5 ------输出内容-----
6 zhangsan
7 lisi
8 wangwu
9 boxiaoyuan

应用场景:

在迭代遍历嵌套的数据类型时,例如一个列表包含了多个字典。

需求:要判断某一个字典中是否存在指定的值,如果存在,提示并且退出循环,如果不存在,在循环整体结束后,给出一个统一的提示。

 1 # -*-coding=utf-8 -*-
 2 students = [
 3             {"name": "小明", "sex": "", "age": "18"},
 4             {"name": "张红", "sex": "", "age": "22"}
 5 ]
 6 
 7 for student in students:
 8     if student.get("name") == "小山":
 9         break
10 else:
11     print("抱歉,没有找到小山")

4.range()函数

range()可以用来数字列表,根据传入的值生成可迭代对象,顾头不顾尾,例如range(0,10,1),其中0为开始值(包括),10为结束值(不包括),1为步长,因此会生成[0,1,2,3,4,5,6,7,8,9]。

 1 for i in range(0,10,1):
 2     print(i)
 3 
 4 ------输出结果------
 5 0
 6 1
 7 2
 8 3
 9 4
10 5
11 6
12 7
13 8
14 9

另外,也可以使用len方法结合range,遍历列表:

1 names=["zhangsan","lisi","wangwu","boxiaoyuan"]
2 for i in range(len(names)):
3     print(names[i])
4 
5 -------输出结果-----
6 zhangsan
7 lisi
8 wangwu
9 boxiaoyuan

5.break和continue

break关键字用来结束for循环或者while循环,for...else或者while...else后的else均不执行,continue关键字用来结束for或者while的本次循环,然后接着执行下次循环

break

 1 i=0
 2 while i<5:
 3     i+=1
 4     if(i==3):
 5         break
 6     print(i)
 7 
 8 -----输出结果------
 9 1
10 2

注:当i等于3时,结束循环,i=4和i=5不再执行。

continue

 1 i=0
 2 while i<5:
 3     i+=1
 4     if(i==3):
 5         continue
 6     print(i)
 7 
 8 ------输出结果-----
 9 1
10 2
11 4
12 5

注:当i等于3时,结束本次循环,不执行print语句输出3,接着进行下次循环,输出4和5。

while...else,当while中遇到break也不会执行else中语句块:

 1 i=0
 2 while i<5:
 3     i+=1
 4     if i==3:
 5         break
 6     print(i)
 7 else:
 8     print("执行了else中的内容")
 9 
10 ------输出结果-----
11 1
12 2

当i=3时循环结束,没有执行else中的语句。

6.pass语句

pass是为了保证程序的完整性,一般用作占位符。

 1 names=["zhangsan","lisi","wangwu","boxiaoyuan"]
 2 for name in names:
 3     if name=="wangwu":
 4         pass
 5         print("执行了pass")
 6     print("name的值:",name)
 7 
 8 ------输出结果-----
 9 name的值: zhangsan
10 name的值: lisi
11 执行了pass
12 name的值: wangwu
13 name的值: boxiaoyuan

 

转载于:https://www.cnblogs.com/zhuzhaoli/p/10251753.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值