当前位置: 代码迷 >> 综合 >> 【Python笔记】(4)条件、循环及其它语句
  详细解决方案

【Python笔记】(4)条件、循环及其它语句

热度:24   发布时间:2024-01-26 10:54:42.0

条件控制语句 if-else

首先来看一个简单的例子:设计一个程序比较两个数 A 和 B 的大小,如果 A 和 B 不相等则打印较大数的值,如果相等则打印 A。

Python 代码如下:

if A >= B:print('The larger number is:',A) 
else:print('The larger number is:',B)

上面只是一个很简单的实例,一般地,Python 条件控制语句的形式为:

if Condition1:Action1 
elif Condition2:Action2
else:Action3  

上面的代码表示:

  1. 如果 Condition1 为True,将执行 Action1;
  2. 如果 Condition1 为False,将继续判断 Condition2;
  3. 如果 Condition2 为True,将执行 Action2;
  4. 如果 Condition2 为False,将执行 Action3。

注意要点

  1. 每个条件后面要使用冒号 :,冒号后的内容表示满足条件后要执行的语句块。
  2. 使用缩进来划分语句块,相同缩进数的语句在一起组成一个语句块(IDE 会自动缩进)。
  3. 在 Python 中没有 switch–case 语句。

条件控制语句实例

实例1:从控制台输入两个数字 A、B,判断大小后输出较大数字,如果相等则输出提示和数值。

#从控制台输入数据默认为字符串类型,需要强制转换为int类型
A = int(input("Please enter the number A:"))
B = int(input("Please enter the number B:"))
if A > B:print('The larger number is:',A) 
elif A == B:print('A and B are equal to ',A)  
else:print('The larger number is:',B) 

执行结果:

Please enter the number A:123
Please enter the number B:456
The larger number is: 456

实例2:从控制台输入学号,如果学号正确则输出考试成绩;如果学号有误,输出报错提示。

#创建一个“学号-成绩”字典
exam_results = {'2018002':95,'2018013':'90','2018023':87}
#接收从控制台输入的学号,默认为字符串类型
stu_num = input("Please enter the student number:")
#删除输入学号首尾空格,避免影响查询
stu_num = stu_num.strip()
#判断输入的学号是否存在于“学号-成绩”字典中
if stu_num in exam_results.keys():print('Your score is :',exam_results.get(stu_num)) 
else:print('The student number you entered is incorrect!')  

执行结果:

Please enter the student number:2018002
Your score is : 95

for 循环语句

Python 中有两种循环语句,for 循环和 while 循环,本节先介绍 for 循环。一般,我们通过 for 循环来遍历序列中的项目,这里序列包括但不限于字符串、列表、元组、字典。

for循环的一般形式如下:

for <item> in <sequence>:<actions>

当 <item> in <sequence> 为 True 时,执行 <actions>。

实例1:求一组数据的平均值。

#测试数据集
num_set = [98,94,82,67,58,90,86]
sumOfNum = 0
#遍历列表中的元素,求和
for element in num_set:sumOfNum += element
#求平均值并打印结果    
average = sumOfNum/len(num_set)
print("The average is:%f"%(average))

执行结果:

The average is:82.142857

实例2:通过 range() 函数遍历数据序列,range() 函数可以生成数列,将生成的数列作为索引,我们可以遍历数字序列。range() 函数的参数是可变的:

  1. range(n):生成步长为1的数列:1,2,3……n;
  2. range(m, n):生成步长为1的数列:m,m+1,m+2,……,n;
  3. range(m, n, s):生成步长为s的数列:m,m+s,m+2s,……,X(<=n)
for index in range(4):print("index:",index)

执行结果:

index: 0
index: 1
index: 2
index: 3

实例3:for 循环结合 range() 遍历数据序列。

#测试数据集
city_set = ['BeiJin','TianJin','ShangHai','HangZhou','SuZhou']
#索引从0开始,以步长2遍历
for index in range(0,len(city_set),2):print("city_set[%d]:%s"%(index,city_set[index]))

执行结果:

city_set[0]:BeiJin
city_set[2]:ShangHai
city_set[4]:SuZhou

while 循环

与 for 循环不同,while 循环不是采用遍历数据序列的方式来进行循环操作的,其循环的依据是条件判断,while 循环的一般形式如下,即当 condition 为 True,则执行 Action,否则退出。

while Conditon:Action

实例1:求一组数据的平均值。

#初始化测试数据
num_set = [98,94,82,67,58,90,86]
sumOfNum = 0
index = 0while index < len(num_set):sumOfNum += num_set[index]index += 1
#求平均值并打印结果    
average = sumOfNum/len(num_set)
print("The average is:%f"%(average))

执行结果:

The average is:82.142857

break 语句

break 语句用于跳出 for 和 while 循环体,也就意味着循环结束。

如下例子:检测数据集中是否存在小于60的数字,存在则打印提示信息并终止。

#初始化测试数据
num_set = [98,94,82,67,58,90,86]
for i in range(len(num_set)):if num_set[i] < 60:print("Someone failed!")breakelse:print(num_set[i])

执行结果:

98
94
82
67
Someone failed!

在实际应用中,break 语句经常和 while 语句结合使用,当条件满足的时候跳出循环。如下例子:

while True:a = input('Please enter a number:')if int(a) > 100:print('error!!!')breakelse:print(a)

执行结果:

Please enter a number:23
23
Please enter a number:45
45
Please enter a number:101
error!!!

continue 语句

与 break 不同,continue 不会退出循环体,而是跳过当前循环块的剩余语句,继续下一轮循环。

如下例子:遍历数据集,遇到小于60的数据打印提示。

#初始化测试数据
num_set = [98,94,82,67,58,90,86]
for i in range(len(num_set)):if num_set[i] < 60:print("Someone failed!")continueprint(num_set[i])

执行结果:

98
94
82
67
Someone failed!
90
86

Pass 语句

Python pass 是空语句,一般用做占位,不执行任何实际的操作,只是为了保持程序结构的完整性。为了直观,举一个不是很恰当的实例:

#初始化测试数据
num_set = [98,82,67,58,90]
for i in range(len(num_set)):if num_set[i] < 60:print("Someone failed!")passprint(num_set[i])

执行结果:

98
82
67
Someone failed!
58
90

上面的例子可以看出,pass 语句没有执行任何操作。不过,在实际应用中,我们不会这样写代码,没有任何意义,pass 语句用于占位,如下例子,else 语句本来可以不写,但写上更为完整,这时候 pass 占位的意义就体现出来了。

#初始化测试数据
num_set = [98,94,82,67,58,90,86]
for i in range(len(num_set)):if num_set[i] < 60:print("Someone failed!")else:pass
  相关解决方案